A platform for community discussion. Free, open, simple.
FEATURE: simplifed event creation in the composer (#39835)
Krisf52e08067b63
diff --git a/app/assets/stylesheets/common/components/date-time-input.scss b/app/assets/stylesheets/common/components/date-time-input.scssindex fcde295c9a7..a38ee9646f2 100644--- a/app/assets/stylesheets/common/components/date-time-input.scss+++ b/app/assets/stylesheets/common/components/date-time-input.scss@@ -13,11 +13,8 @@}.d-time-input {- width: 90px;-.select-kit-header {border-color: transparent;- width: 90px;}}diff --git a/app/assets/stylesheets/common/components/time-input.scss b/app/assets/stylesheets/common/components/time-input.scssindex 78e1e8e3ed6..802654d3cb7 100644--- a/app/assets/stylesheets/common/components/time-input.scss+++ b/app/assets/stylesheets/common/components/time-input.scss@@ -2,8 +2,7 @@display: inline-flex;.combo-box {- width: 65px;- min-width: auto;+ min-width: 7em;&:not(.has-selection) {.select-kit-selected-name .name {@@ -38,6 +37,10 @@white-space: nowrap;overflow: hidden;text-overflow: ellipsis;++ small {+ display: none;+ }}}}diff --git a/app/assets/stylesheets/common/form-kit/_control-checkbox-upcoming-changes.scss b/app/assets/stylesheets/common/form-kit/_control-checkbox-upcoming-changes.scssindex 46a4d5c97c1..4c918156b29 100644--- a/app/assets/stylesheets/common/form-kit/_control-checkbox-upcoming-changes.scss+++ b/app/assets/stylesheets/common/form-kit/_control-checkbox-upcoming-changes.scss@@ -6,6 +6,7 @@opacity: 0;&-label {+ position: relative;display: flex;gap: 0.75em;margin: 0;@@ -43,7 +44,7 @@left: 50%;width: 50%;height: 50%;- background: var(--tertiary-high);+ background: var(--tertiary);border-radius: 50%;transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);opacity: 0;@@ -73,7 +74,7 @@.form-kit__control-checkbox-label:hover.form-kit__control-checkbox-checkmark {- border-color: var(--tertiary-high);+ border-color: var(--tertiary);}.form-kit__control-checkbox:checked + .form-kit__control-checkbox-checkmark {diff --git a/frontend/discourse/app/form-kit/components/fk/container.gjs b/frontend/discourse/app/form-kit/components/fk/container.gjsindex 22321ca306b..f64873fc404 100644--- a/frontend/discourse/app/form-kit/components/fk/container.gjs+++ b/frontend/discourse/app/form-kit/components/fk/container.gjs@@ -2,6 +2,7 @@ import { concat } from "@ember/helper";import FormText from "discourse/form-kit/components/fk/text";import { eq } from "discourse/truth-helpers";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { i18n } from "discourse-i18n";const FKContainer = <template><div@@ -16,6 +17,11 @@ const FKContainer = <template>{{#if @title}}<span class="form-kit__container-title">{{@title}}+ {{#if @optional}}+ <span class="form-kit__container-optional">({{i18n+ "form_kit.optional"+ }})</span>+ {{/if}}</span>{{/if}}diff --git a/frontend/discourse/app/ui-kit/d-time-input.gjs b/frontend/discourse/app/ui-kit/d-time-input.gjsindex 0ba59edf517..56b0f0886d5 100644--- a/frontend/discourse/app/ui-kit/d-time-input.gjs+++ b/frontend/discourse/app/ui-kit/d-time-input.gjs@@ -6,16 +6,32 @@ import { trustHTML } from "@ember/template";import { isPresent } from "@ember/utils";import { tagName } from "@ember-decorators/component";import ComboBox from "discourse/select-kit/components/combo-box";+import I18n, { i18n } from "discourse-i18n";++const AM_PM_REGEX = /^\s*(\d{1,2}):(\d{2})\s*(am|pm)\s*$/i;function convertMinutes(num) {return { hours: Math.floor(num / 60), minutes: num % 60 };}+function uses12HourTime() {+ const format = i18n("dates.time", { defaultValue: "" });+ if (format) {+ return /[aA]/.test(format.replace(/\[[^\]]*\]/g, ""));+ }+ return I18n.currentLocale()?.startsWith("en");+}+function convertMinutesToString(n) {- const hoursAndMinutes = convertMinutes(n);- return `${hoursAndMinutes.hours+ const { hours, minutes } = convertMinutes(n);+ if (uses12HourTime()) {+ const period = hours >= 12 ? "PM" : "AM";+ const displayHours = hours % 12 || 12;+ return `${displayHours}:${minutes.toString().padStart(2, "0")} ${period}`;+ }+ return `${hours.toString().padStart(2, "0")}:${minutes.toString()- .padStart(2, "0")}:${hoursAndMinutes.minutes.toString().padStart(2, "0")}`;+ .padStart(2, "0")}`;}function convertMinutesToDurationString(n) {@@ -157,35 +173,47 @@ export default class DTimeInput extends Component {@actiononChangeTime(time) {- if (isPresent(time) && this.onChange) {- if (typeof time === "string" && time.length) {- let [hours, minutes] = time.split(":");- if (hours && minutes) {- if (hours < 0) {- hours = 0;- }- if (hours > 23) {- hours = 23;- }- if (minutes < 0) {- minutes = 0;- }- if (minutes > 59) {- minutes = 59;- }-- this.onChange({- hours: parseInt(hours, 10),- minutes: parseInt(minutes, 10),- });+ if (!isPresent(time) || !this.onChange) {+ return;+ }++ if (typeof time === "string" && time.length) {+ const ampmMatch = time.match(AM_PM_REGEX);++ let hours;+ let minutes;+ if (ampmMatch) {+ hours = parseInt(ampmMatch[1], 10);+ minutes = parseInt(ampmMatch[2], 10);+ const isPm = ampmMatch[3].toLowerCase() === "pm";+ if (isPm && hours !== 12) {+ hours += 12;+ } else if (!isPm && hours === 12) {+ hours = 0;}} else {- this.onChange({- hours: convertMinutes(time).hours,- minutes: convertMinutes(time).minutes,- });+ const [h, m] = time.split(":");+ if (!h || !m) {+ return;+ }+ hours = parseInt(h, 10);+ minutes = parseInt(m, 10);+ }++ if (!Number.isFinite(hours) || !Number.isFinite(minutes)) {+ return;}++ hours = Math.max(0, Math.min(23, hours));+ minutes = Math.max(0, Math.min(59, minutes));+ this.onChange({ hours, minutes });+ return;}++ this.onChange({+ hours: convertMinutes(time).hours,+ minutes: convertMinutes(time).minutes,+ });}<template>diff --git a/frontend/discourse/tests/integration/ui-kit/d-date-time-input-range-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-date-time-input-range-test.gjsindex 1824c8ea8ee..22d496140cf 100644--- a/frontend/discourse/tests/integration/ui-kit/d-date-time-input-range-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-date-time-input-range-test.gjs@@ -27,7 +27,7 @@ module("Integration | ui-kit | DDateTimeInputRange", function (hooks) {assert.dom(".from.d-date-time-input .date-picker").hasValue("2019-01-29");assert.dom(".from.d-date-time-input .d-time-input .combo-box-header")- .hasAttribute("data-name", "14:45");+ .hasAttribute("data-name", "2:45 PM");assert.dom(".to.d-date-time-input .date-picker").hasNoValue();assert.dom(".to.d-date-time-input .d-time-input .combo-box-header")@@ -38,16 +38,16 @@ module("Integration | ui-kit | DDateTimeInputRange", function (hooks) {await toTimeSelectKit.expand();let rows = toTimeSelectKit.rows();- assert.dom(rows[0]).hasAttribute("data-name", "14:45");- assert.dom(rows[rows.length - 1]).hasAttribute("data-name", "23:45");+ assert.dom(rows[0]).hasAttribute("data-name", "2:45 PM");+ assert.dom(rows[rows.length - 1]).hasAttribute("data-name", "11:45 PM");await toTimeSelectKit.collapse();await fillIn(".to.d-date-time-input .date-picker", "2019-01-30");await toTimeSelectKit.expand();rows = toTimeSelectKit.rows();- assert.dom(rows[0]).hasAttribute("data-name", "00:00");- assert.dom(rows[rows.length - 1]).hasAttribute("data-name", "23:45");+ assert.dom(rows[0]).hasAttribute("data-name", "12:00 AM");+ assert.dom(rows[rows.length - 1]).hasAttribute("data-name", "11:45 PM");});test("setting relativeDate results in correct intervals (4x 15m then 30m)", async function (assert) {@@ -69,8 +69,8 @@ module("Integration | ui-kit | DDateTimeInputRange", function (hooks) {await toTimeSelectKit.expand();let rows = toTimeSelectKit.rows();- assert.dom(rows[4]).hasAttribute("data-name", "15:45");- assert.dom(rows[5]).hasAttribute("data-name", "16:15");+ assert.dom(rows[4]).hasAttribute("data-name", "3:45 PM");+ assert.dom(rows[5]).hasAttribute("data-name", "4:15 PM");});test("timezone support", async function (assert) {@@ -95,7 +95,7 @@ module("Integration | ui-kit | DDateTimeInputRange", function (hooks) {assert.dom(".from.d-date-time-input .date-picker").hasValue("2019-01-29");assert.dom(".from.d-date-time-input .d-time-input .combo-box-header")- .hasAttribute("data-name", "14:45");+ .hasAttribute("data-name", "2:45 PM");assert.dom(".to.d-date-time-input .date-picker").hasNoValue();assert.dom(".to.d-date-time-input .d-time-input .combo-box-header")@@ -104,7 +104,7 @@ module("Integration | ui-kit | DDateTimeInputRange", function (hooks) {await fillIn(".to.d-date-time-input .date-picker", "2019-01-29");const toTimeSelectKit = selectKit(".to .d-time-input .select-kit");await toTimeSelectKit.expand();- await toTimeSelectKit.selectRowByName("19:15");+ await toTimeSelectKit.selectRowByName("7:15 PM");assert.strictEqual(this.state.to.toString(),diff --git a/frontend/discourse/tests/integration/ui-kit/d-date-time-input-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-date-time-input-test.gjsindex 907a25f5026..abc8ae88605 100644--- a/frontend/discourse/tests/integration/ui-kit/d-date-time-input-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-date-time-input-test.gjs@@ -16,7 +16,7 @@ module("Integration | ui-kit | DDateTimeInput", function (hooks) {assert.dom(".date-picker").hasValue("2019-01-29");assert.dom(".d-time-input .combo-box-header")- .hasAttribute("data-name", "14:45");+ .hasAttribute("data-name", "2:45 PM");});test("prevents mutations", async function (assert) {diff --git a/frontend/discourse/tests/integration/ui-kit/d-time-input-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-time-input-test.gjsindex 90f1b64ee61..348913e7285 100644--- a/frontend/discourse/tests/integration/ui-kit/d-time-input-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-time-input-test.gjs@@ -3,6 +3,7 @@ import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import selectKit from "discourse/tests/helpers/select-kit-helper";import DTimeInput from "discourse/ui-kit/d-time-input";+import I18n from "discourse-i18n";function setTime(time) {this.setProperties(time);@@ -24,7 +25,7 @@ module("Integration | ui-kit | DTimeInput", function (hooks) {</template>);- assert.strictEqual(this.subject.header().name(), "14:58");+ assert.strictEqual(this.subject.header().name(), "2:58 PM");});test("prevents mutations", async function (assert) {@@ -38,7 +39,7 @@ module("Integration | ui-kit | DTimeInput", function (hooks) {await this.subject.expand();await this.subject.selectRowByIndex(3);- assert.strictEqual(this.subject.header().name(), "14:58");+ assert.strictEqual(this.subject.header().name(), "2:58 PM");});test("allows mutations through actions", async function (assert) {@@ -57,6 +58,25 @@ module("Integration | ui-kit | DTimeInput", function (hooks) {await this.subject.expand();await this.subject.selectRowByIndex(3);- assert.strictEqual(this.subject.header().name(), "00:45");+ assert.strictEqual(this.subject.header().name(), "12:45 AM");+ });++ test("renders 24-hour time when the locale's dates.time has no am/pm token", async function (assert) {+ const originalFormat = I18n.translations[I18n.locale].js.dates.time;+ I18n.translations[I18n.locale].js.dates.time = "HH:mm";++ try {+ this.setProperties({ hours: "14", minutes: "58" });++ await render(+ <template>+ <DTimeInput @hours={{this.hours}} @minutes={{this.minutes}} />+ </template>+ );++ assert.strictEqual(this.subject.header().name(), "14:58");+ } finally {+ I18n.translations[I18n.locale].js.dates.time = originalFormat;+ }});});diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjsnew file mode 100644index 00000000000..f7e08630342--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/compact-event-editor.gjs@@ -0,0 +1,855 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import didUpdate from "@ember/render-modifiers/modifiers/did-update";+import { next } from "@ember/runloop";+import { service } from "@ember/service";+import DTooltip from "discourse/float-kit/components/d-tooltip";+import DButton from "discourse/ui-kit/d-button";+import DExpandingTextArea from "discourse/ui-kit/d-expanding-text-area";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import PostEventBuilder from "discourse/plugins/discourse-calendar/discourse/components/modal/post-event-builder";+import {+ defaultEventState,+ reconcileDefaultReminder,+} from "discourse/plugins/discourse-calendar/discourse/lib/raw-event-helper";+import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";++export default class CompactEventEditor extends Component {+ @service capabilities;+ @service composer;+ @service currentUser;+ @service modal;++ @tracked name;+ @tracked location;+ @tracked description;+ @tracked startsAt;+ @tracked endsAt;+ @tracked allDay;+ @tracked maxAttendees;+ @tracked status;+ @tracked timezone;+ @tracked reminders;+ @tracked recurrence;+ @tracked recurrenceUntil;+ @tracked showLocalTime;+ @tracked chatEnabled;+ @tracked minimal;+ @tracked url;+ @tracked image;+ @tracked allowedGroups;+ @tracked closed;+ @tracked customFields;+ #previousRsvpStatus = "public";+ #lastInitialStateRef;+ @tracked _maxAttendeesOverride;++ constructor() {+ super(...arguments);+ this.#syncFromInitialState();+ }++ @action+ syncIfStateChanged() {+ if (this.args.initialState !== this.#lastInitialStateRef) {+ this.#syncFromInitialState();+ }+ }++ #syncFromInitialState() {+ const s = { ...defaultEventState(), ...(this.args.initialState || {}) };+ this.name = s.name;+ this.location = s.location;+ this.description = s.description;+ this.startsAt = s.startsAt;+ this.endsAt = s.endsAt;+ this.allDay = s.allDay;+ this.maxAttendees = s.maxAttendees;+ this.status = s.status;+ this.timezone = s.timezone;+ this.reminders = s.reminders;+ this.recurrence = s.recurrence;+ this.recurrenceUntil = s.recurrenceUntil;+ this.showLocalTime = s.showLocalTime;+ this.chatEnabled = s.chatEnabled;+ this.minimal = s.minimal;+ this.url = s.url;+ this.image = s.image;+ this.allowedGroups = s.allowedGroups;+ this.closed = s.closed;+ this.customFields = { ...s.customFields };++ if (this.status && this.status !== "standalone") {+ this.#previousRsvpStatus = this.status;+ }+ this.#lastInitialStateRef = this.args.initialState;+ }++ get currentState() {+ return {+ name: this.name,+ location: this.location,+ description: this.description,+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ allDay: this.allDay,+ maxAttendees: this.maxAttendees,+ status: this.status,+ timezone: this.timezone,+ reminders: this.reminders,+ recurrence: this.recurrence,+ recurrenceUntil: this.recurrenceUntil,+ showLocalTime: this.showLocalTime,+ chatEnabled: this.chatEnabled,+ minimal: this.minimal,+ url: this.url,+ image: this.image,+ allowedGroups: this.allowedGroups,+ closed: this.closed,+ customFields: this.customFields,+ };+ }++ #emitChange() {+ this.args.onChange?.(this.currentState);+ }++ #configSnapshot(overrides = {}) {+ return {+ startsAt: overrides.startsAt ?? this.startsAt,+ endsAt: overrides.endsAt ?? this.endsAt,+ allDay: overrides.allDay ?? this.allDay,+ };+ }++ get displayTime() {+ if (!this.startsAt) {+ return null;+ }+ return this.showLocalTime+ ? this.startsAt.clone()+ : this.startsAt.clone().tz(this.userTimezone);+ }++ get displayEndTime() {+ if (!this.endsAt) {+ return null;+ }+ return this.showLocalTime+ ? this.endsAt.clone()+ : this.endsAt.clone().tz(this.userTimezone);+ }++ get hasEndDate() {+ return !!this.endsAt;+ }++ get isMultiDay() {+ const start = this.formattedStartDate;+ const end = this.formattedEndDate;+ return !!start && !!end && start !== end;+ }++ get showInlineEndTime() {+ return !this.allDay && !this.isMultiDay;+ }++ get showEndDateRow() {+ return this.allDay || this.isMultiDay;+ }++ get formattedStartDisplay() {+ return this.displayTime+ ? this.displayTime.format(i18n("dates.long_no_year_no_time"))+ : "";+ }++ get formattedEndDisplay() {+ return this.displayEndTime+ ? this.displayEndTime.format(i18n("dates.long_no_year_no_time"))+ : i18n("discourse_post_event.composer.end_date_placeholder");+ }++ get startsAtMonth() {+ const m = this.displayTime || moment.tz(this.userTimezone);+ return m.format("MMM");+ }++ get startsAtDay() {+ const m = this.displayTime || moment.tz(this.userTimezone);+ return m.format("D");+ }++ get hasLocation() {+ return this.location && this.location.trim();+ }++ get isLocationUrl() {+ if (!this.hasLocation) {+ return false;+ }+ return this.args.urlTester?.(this.location) ?? false;+ }++ get locationIcon() {+ return this.isLocationUrl ? "link" : "location-pin";+ }++ get displayLocation() {+ if (!this.hasLocation) {+ return null;+ }+ if (this.isLocationUrl) {+ const location = this.location.trim();+ return location.includes("://") || location.includes("mailto:")+ ? location+ : `https://${location}`;+ }+ return this.location;+ }++ get statusText() {+ const status =+ this.status === "standalone" ? "public" : this.status || "public";+ return i18n(`discourse_post_event.models.event.status.${status}.title`);+ }++ get eventNamePlaceholder() {+ return (+ this.composer?.get("model.title") ||+ i18n("discourse_post_event.composer.name_placeholder")+ );+ }++ get userTimezone() {+ return this.currentUser?.user_option?.timezone || moment.tz.guess();+ }++ #formatDate(m) {+ if (!m || typeof m.isValid !== "function" || !m.isValid()) {+ return "";+ }+ return m.format("YYYY-MM-DD");+ }++ #formatTime(m) {+ if (!m || typeof m.isValid !== "function" || !m.isValid()) {+ return "";+ }+ return m.format("HH:mm");+ }++ get formattedStartDate() {+ return this.#formatDate(this.startsAt);+ }++ get formattedEndDate() {+ return this.#formatDate(this.endsAt);+ }++ get formattedStartTime() {+ return this.#formatTime(this.startsAt);+ }++ get formattedEndTime() {+ return this.#formatTime(this.endsAt);+ }++ #combineDateTime(dateStr, timeStr) {+ const date = (dateStr || "").trim();+ if (!date) {+ return null;+ }+ const time = (timeStr || "").trim();+ return moment.tz(time ? `${date} ${time}` : date, this.timezone);+ }++ #startTimeForDate() {+ return this.allDay ? "" : this.formattedStartTime || "00:00";+ }++ #endTimeForDate() {+ return this.allDay ? "" : this.formattedEndTime || "00:00";+ }++ #reconcileReminders(oldConfig, newConfig) {+ this.reminders = reconcileDefaultReminder(+ this.reminders,+ oldConfig,+ newConfig+ );+ }++ @action+ onNameInput(event) {+ event.target.value = event.target.value.replace(/\n/g, "");+ this.name = event.target.value;+ this.#emitChange();+ }++ @action+ onLocationInput(event) {+ const value = event.target.value;+ this.location = value === "" ? null : value;+ this.#emitChange();+ }++ @action+ onDescriptionInput(event) {+ this.description = event.target.value;+ this.#emitChange();+ }++ @action+ onStartDateChange(event) {+ const dateStr = event.target.value;+ const newStart = this.#combineDateTime(dateStr, this.#startTimeForDate());+ if (!newStart) {+ return;+ }+ const oldConfig = this.#configSnapshot();+ this.startsAt = newStart;++ if (this.showInlineEndTime) {+ this.endsAt = this.#combineDateTime(dateStr, this.#endTimeForDate());+ } else {+ const endDateStr = this.formattedEndDate;+ if (endDateStr && dateStr > endDateStr) {+ this.endsAt = this.#combineDateTime(dateStr, this.#endTimeForDate());+ }+ }++ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ }++ @action+ onStartTimeChange(event) {+ const newStart = this.#combineDateTime(+ this.formattedStartDate,+ event.target.value || "00:00"+ );+ if (!newStart) {+ return;+ }+ const oldConfig = this.#configSnapshot();+ this.startsAt = newStart;+ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ }++ @action+ onEndDateChange(event) {+ const oldConfig = this.#configSnapshot();+ if (!event.target.value) {+ this.endsAt = null;+ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ return;+ }+ const startDateStr = this.formattedStartDate;+ const dateStr =+ startDateStr && event.target.value < startDateStr+ ? startDateStr+ : event.target.value;+ if (this.allDay && dateStr === startDateStr) {+ this.endsAt = null;+ } else {+ this.endsAt = this.#combineDateTime(dateStr, this.#endTimeForDate());+ }+ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ }++ @action+ onEndTimeChange(event) {+ if (!this.formattedEndDate) {+ return;+ }+ const oldConfig = this.#configSnapshot();+ this.endsAt = this.#combineDateTime(+ this.formattedEndDate,+ event.target.value || "00:00"+ );+ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ }++ @action+ toggleAllDay() {+ const newAllDay = !this.allDay;+ const oldConfig = this.#configSnapshot();++ if (newAllDay) {+ const startDate = (this.startsAt || moment.tz(this.timezone)).format(+ "YYYY-MM-DD"+ );+ const existingEnd = this.endsAt;+ this.startsAt = moment.tz(startDate, this.timezone);++ if (existingEnd) {+ const endDate = existingEnd.format("YYYY-MM-DD");+ this.endsAt =+ endDate === startDate ? null : moment.tz(endDate, this.timezone);+ } else {+ this.endsAt = null;+ }+ } else if (this.startsAt) {+ const nowTime = moment.tz(this.timezone);+ const newStart = this.startsAt+ .clone()+ .hour(nowTime.hour())+ .minute(nowTime.minute())+ .second(0)+ .millisecond(0);+ this.startsAt = newStart;+ this.endsAt = newStart.clone().add(1, "hour");+ }+ this.allDay = newAllDay;+ this.#reconcileReminders(oldConfig, this.#configSnapshot());+ this.#emitChange();+ }++ get rsvpsDisabled() {+ return this.status === "standalone";+ }++ get maxAttendeesPlaceholder() {+ if (this.rsvpsDisabled) {+ return "";+ }+ return i18n("discourse_post_event.composer.max_attendees_placeholder");+ }++ get displayMaxAttendees() {+ if (this._maxAttendeesOverride !== undefined) {+ return this._maxAttendeesOverride;+ }+ return this.maxAttendees ?? "";+ }++ #applyMaxAttendees(value) {+ if (value === 0) {+ if (this.status && this.status !== "standalone") {+ this.#previousRsvpStatus = this.status;+ }+ this.status = "standalone";+ this.maxAttendees = null;+ this.reminders = this.reminders.map((r) =>+ r.type === "notification" ? { ...r, type: "bumpTopic" } : r+ );+ } else if (this.status === "standalone" && value > 0) {+ this.status = this.#previousRsvpStatus || "public";+ this.maxAttendees = value;+ this.reminders = this.reminders.map((r) =>+ r.type === "bumpTopic" ? { ...r, type: "notification" } : r+ );+ } else {+ this.maxAttendees = value;+ }+ this.#emitChange();+ }++ @action+ onMaxAttendeesInput(event) {+ const raw = event.target.value;+ this._maxAttendeesOverride = raw;++ if (raw === "") {+ this.#applyMaxAttendees(null);+ return;+ }+ const parsed = parseInt(raw, 10);+ if (!Number.isFinite(parsed) || parsed < 0) {+ this._maxAttendeesOverride = "";+ event.target.value = "";+ this.#applyMaxAttendees(null);+ return;+ }+ if (parsed === 0) {+ return;+ }+ this.#applyMaxAttendees(parsed);+ }++ @action+ onMaxAttendeesBlur(event) {+ const raw = event.target.value;+ this._maxAttendeesOverride = undefined;+ if (raw === "") {+ return;+ }+ const parsed = parseInt(raw, 10);+ if (parsed === 0) {+ this.#applyMaxAttendees(0);+ }+ }++ get visibleReminders() {+ return (this.reminders || []).map((reminder, index) => {+ const isBump = reminder.type === "bumpTopic";+ return {+ reminder,+ index,+ label: this.#unitLabel(reminder),+ icon: isBump ? "arrows-up-to-line" : "bell",+ iconTitle: isBump+ ? "discourse_post_event.composer.reminder.bump_topic_title"+ : "discourse_post_event.composer.reminder.notification_title",+ };+ });+ }++ #unitLabel(reminder) {+ const unit = reminder.unit || "minutes";+ const count = parseInt(reminder.value, 10) || 0;+ const unitLabel = i18n(+ `discourse_post_event.composer.reminder.units.${unit}`,+ { count }+ );+ return i18n(+ `discourse_post_event.composer.reminder.${reminder.period || "before"}`,+ { unit: unitLabel }+ );+ }++ @action+ onReminderValueInput(index, event) {+ const parsed = parseInt(event.target.value, 10);+ if (!Number.isFinite(parsed) || parsed <= 0) {+ return;+ }+ if (!this.reminders[index]) {+ return;+ }+ this.reminders = this.reminders.map((r, i) =>+ i === index ? { ...r, value: parsed } : r+ );+ this.#emitChange();+ }++ @action+ removeReminder(index) {+ if (!this.reminders[index]) {+ return;+ }+ this.reminders = this.reminders.filter((_, i) => i !== index);+ this.#emitChange();+ }++ @action+ focusDateInput(event) {+ next(() => event.target.showPicker?.());+ }++ @action+ handleTextInputFocus(event) {+ if (this.capabilities.isIOS) {+ setTimeout(() => {+ event.target.scrollIntoView({ block: "center", behavior: "smooth" });+ }, 400);+ }+ }++ @action+ openAdvanced() {+ const event = DiscoursePostEventEvent.create({+ name: this.name,+ location: this.location,+ description: this.description,+ timezone: this.timezone,+ status: this.status,+ max_attendees: this.maxAttendees,+ show_local_time: this.showLocalTime,+ chat_enabled: this.chatEnabled,+ minimal: this.minimal,+ all_day: this.allDay,+ reminders: this.reminders,+ raw_invitees: this.allowedGroups?.split(",") || [],+ custom_fields: { ...this.customFields },+ starts_at: this.startsAt,+ ends_at: this.endsAt,+ url: this.url,+ recurrence: this.recurrence,+ recurrence_until: this.recurrenceUntil,+ image_upload: this.image ? { url: this.image } : null,+ });++ this.modal.show(PostEventBuilder, {+ model: {+ event,+ initialScreen: "advanced",+ onDelete: () => {+ this.args.onDelete?.();+ return true;+ },+ onUpdate: (startsAt, endsAt, updatedEvent) => {+ this.startsAt = startsAt;+ this.endsAt = endsAt;+ this.name = updatedEvent.name || null;+ this.location = updatedEvent.location || null;+ this.description = updatedEvent.description || "";+ this.timezone = updatedEvent.timezone || this.timezone;+ this.status = updatedEvent.status || "public";+ this.maxAttendees = updatedEvent.maxAttendees ?? null;+ this.showLocalTime = !!updatedEvent.showLocalTime;+ this.chatEnabled = !!updatedEvent.chatEnabled;+ this.minimal = !!updatedEvent.minimal;+ this.allDay = !!updatedEvent.allDay;+ this.reminders = updatedEvent.reminders || [];+ this.recurrence = updatedEvent.recurrence || null;+ this.recurrenceUntil = updatedEvent.recurrenceUntil || null;+ this.url = updatedEvent.url || null;+ this.allowedGroups =+ (updatedEvent.rawInvitees || []).join(",") || null;+ this.image = updatedEvent.imageUpload?.short_url+ ? updatedEvent.imageUpload.short_url+ : updatedEvent.imageUpload?.url || null;+ this.customFields = { ...(updatedEvent.customFields || {}) };++ if (this.status && this.status !== "standalone") {+ this.#previousRsvpStatus = this.status;+ }++ this.#emitChange();+ // Modal-driven updates are discrete commits, not interim keystrokes.+ // Tell the wrapper to flush immediately rather than wait for blur,+ // since focus returns to the gear button (inside the wrapper).+ this.args.onCommit?.();+ },+ },+ });+ }++ <template>+ <header+ class="composer-event__header"+ {{didUpdate this.syncIfStateChanged @initialState}}+ >+ <div class="composer-event__date">+ <div class="composer-event__month">{{this.startsAtMonth}}</div>+ <div class="composer-event__day">{{this.startsAtDay}}</div>+ </div>++ <div class="composer-event__info">+ <DExpandingTextArea+ rows="1"+ value={{this.name}}+ class="composer-event__name-input"+ placeholder={{this.eventNamePlaceholder}}+ {{on "input" this.onNameInput}}+ {{on "focus" this.handleTextInputFocus}}+ />++ <div class="composer-event__status">+ {{this.statusText}}+ </div>+ </div>++ {{#unless @hideAdvanced}}+ <div class="composer-event__more-dropdown">+ <DButton+ @icon="gear"+ @action={{this.openAdvanced}}+ @title="discourse_post_event.edit_event"+ class="btn-flat"+ />+ </div>+ {{/unless}}+ </header>++ <section class="composer-event__dates">+ {{dIcon "clock"}}+ <div+ class={{dConcatClass+ "composer-event__date-range"+ (unless this.allDay "composer-event__date-range--has-time")+ }}+ >+ <div class="composer-event__all-day-toggle">+ <DToggleSwitch+ class="composer-event__all-day-switch"+ @state={{this.allDay}}+ @label="discourse_post_event.composer.all_day"+ {{on "click" this.toggleAllDay}}+ />+ </div>++ <div+ class={{dConcatClass+ "composer-event__date-row"+ (if this.showEndDateRow (unless this.allDay "--multi-day"))+ }}+ >+ <div class="composer-event__date-wrapper">+ <input+ type="date"+ value={{this.formattedStartDate}}+ class="composer-event__date-input"+ {{on "change" this.onStartDateChange}}+ {{on "focus" this.focusDateInput}}+ />+ <span class="composer-event__date-display">+ {{this.formattedStartDisplay}}+ </span>+ </div>+ {{#unless this.allDay}}+ <input+ type="time"+ value={{this.formattedStartTime}}+ class="composer-event__time-input"+ {{on "change" this.onStartTimeChange}}+ />+ {{/unless}}+ {{#if this.showInlineEndTime}}+ {{dIcon "arrow-right" class="composer-event__date-arrow"}}+ <input+ type="time"+ value={{this.formattedEndTime}}+ class="composer-event__time-input"+ {{on "change" this.onEndTimeChange}}+ />+ {{/if}}+ </div>++ {{#if this.showEndDateRow}}+ {{#if this.allDay}}+ {{dIcon "arrow-right" class="composer-event__date-arrow"}}+ {{/if}}+ <div+ class={{dConcatClass+ "composer-event__date-row"+ (unless this.allDay "--multi-day")+ }}+ >+ <div class="composer-event__date-wrapper">+ <input+ type="date"+ value={{this.formattedEndDate}}+ class="composer-event__date-input"+ {{on "change" this.onEndDateChange}}+ {{on "focus" this.focusDateInput}}+ />+ <span+ class={{dConcatClass+ "composer-event__date-display"+ (unless this.hasEndDate "--empty")+ }}+ >+ {{this.formattedEndDisplay}}+ </span>+ </div>+ {{#unless this.allDay}}+ <input+ type="time"+ value={{this.formattedEndTime}}+ class="composer-event__time-input"+ {{on "change" this.onEndTimeChange}}+ />+ {{/unless}}+ </div>+ {{/if}}+ </div>+ </section>++ <section class="composer-event__location">+ {{dIcon this.locationIcon}}+ <div class="composer-event__location-content">+ <input+ type="text"+ value={{this.location}}+ class="composer-event__location-input"+ placeholder={{i18n+ "discourse_post_event.composer.location_placeholder"+ }}+ {{on "input" this.onLocationInput}}+ {{on "focus" this.handleTextInputFocus}}+ />+ {{#if this.isLocationUrl}}+ <a+ class="composer-event__location-external-link"+ href={{this.displayLocation}}+ target="_blank"+ rel="noopener noreferrer"+ title="Visit {{this.location}}"+ >+ {{dIcon "up-right-from-square"}}+ </a>+ {{/if}}+ </div>+ </section>++ <section class="composer-event__attendees">+ {{dIcon "users"}}+ <input+ type="number"+ inputmode="numeric"+ min="0"+ step="1"+ value={{this.displayMaxAttendees}}+ placeholder={{this.maxAttendeesPlaceholder}}+ class="composer-event__max-attendees-input"+ {{on "input" this.onMaxAttendeesInput}}+ {{on "blur" this.onMaxAttendeesBlur}}+ />+ {{#if this.rsvpsDisabled}}+ <span class="composer-event__max-attendees-display">+ {{i18n "discourse_post_event.composer.no_rsvps_label"}}+ </span>+ {{else if this.maxAttendees}}+ <span class="composer-event__max-attendees-display">+ {{i18n+ "discourse_post_event.composer.max_attendees_display"+ count=this.maxAttendees+ }}+ </span>+ {{/if}}+ </section>++ {{#each this.visibleReminders as |entry|}}+ <section class="composer-event__reminder">+ <DTooltip class="composer-event__reminder-icon">+ <:trigger>{{dIcon entry.icon}}</:trigger>+ <:content>{{i18n entry.iconTitle}}</:content>+ </DTooltip>+ <input+ type="number"+ inputmode="numeric"+ min="1"+ step="1"+ value={{entry.reminder.value}}+ class="composer-event__reminder-value"+ {{on "input" (fn this.onReminderValueInput entry.index)}}+ />+ <span class="composer-event__reminder-unit">+ {{entry.label}}+ </span>+ <DButton+ @icon="xmark"+ @action={{fn this.removeReminder entry.index}}+ @title="discourse_post_event.composer.reminder.remove"+ class="btn-flat composer-event__reminder-remove"+ />+ </section>+ {{/each}}++ <section class="composer-event__description">+ <DExpandingTextArea+ class="composer-event__description-textarea"+ placeholder={{i18n+ "discourse_post_event.composer.description_placeholder"+ }}+ value={{this.description}}+ rows="1"+ {{on "input" this.onDescriptionInput}}+ {{on "focus" this.handleTextInputFocus}}+ />+ </section>+ </template>+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjsnew file mode 100644index 00000000000..c4664475f3b--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/composer-event-editor.gjs@@ -0,0 +1,131 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";+import { service } from "@ember/service";+import {+ buildEventBlock,+ buildParams,+ getCustomFieldNames,+ parseEventAttrs,+ parseEventBlock,+ stateToEventInput,+} from "discourse/plugins/discourse-calendar/discourse/lib/raw-event-helper";+import CompactEventEditor from "./compact-event-editor";++export default class ComposerEventEditor extends Component {+ @service appEvents;+ @service composer;+ @service currentUser;+ @service siteSettings;++ #pendingState = null;+ #wrapperElement = null;++ get initialState() {+ const raw = this.composer?.model?.reply || "";+ const parsed = parseEventBlock(raw);+ if (!parsed) {+ return null;+ }+ return {+ ...parseEventAttrs(parsed.attrs, {+ fallbackTimezone: this.currentUser?.user_option?.timezone,+ customFieldNames: getCustomFieldNames(this.siteSettings),+ }),+ description: parsed.description || "",+ };+ }++ @action+ urlTester(value) {+ return /^(https?:\/\/|www\.|mailto:)/i.test(value);+ }++ @action+ onChange(state) {+ this.#pendingState = state;+ }++ @action+ attachWrapper(element) {+ this.#wrapperElement = element;+ element.addEventListener("focusout", this.onFocusOut);+ }++ @action+ detachWrapper(element) {+ element.removeEventListener("focusout", this.onFocusOut);+ this.flush();+ }++ @action+ onFocusOut(event) {+ if (+ !this.#wrapperElement ||+ this.#wrapperElement.contains(event.relatedTarget)+ ) {+ return;+ }+ this.flush();+ }++ @action+ flush() {+ if (!this.#pendingState) {+ return;+ }+ const state = this.#pendingState;+ this.#pendingState = null;++ const raw = this.composer?.model?.reply || "";+ const parsed = parseEventBlock(raw);+ if (!parsed) {+ return;+ }++ const params = buildParams(+ state.startsAt,+ state.endsAt,+ stateToEventInput(state),+ this.siteSettings+ );+ delete params.description;++ const newBlock = buildEventBlock(params, state.description);+ if (newBlock === parsed.full) {+ return;+ }+ this.appEvents.trigger("composer:replace-text", parsed.full, newBlock, {+ skipNewSelection: true,+ });+ }++ @action+ onDelete() {+ this.#pendingState = null;+ const raw = this.composer?.model?.reply || "";+ const parsed = parseEventBlock(raw);+ if (parsed) {+ this.appEvents.trigger("composer:replace-text", parsed.full, "", {+ skipNewSelection: true,+ });+ }+ }++ <template>+ <div+ class="composer-event-node composer-event-editor"+ {{didInsert this.attachWrapper}}+ {{willDestroy this.detachWrapper}}+ >+ <CompactEventEditor+ @initialState={{this.initialState}}+ @urlTester={{this.urlTester}}+ @onChange={{this.onChange}}+ @onCommit={{this.flush}}+ @onDelete={{this.onDelete}}+ />+ </div>+ </template>+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjsindex 35a11ace101..75ef3b3b11c 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/event-node-view.gjs@@ -1,87 +1,48 @@import Component from "@glimmer/component";-import { on } from "@ember/modifier";+import { cached } from "@glimmer/tracking";import { action } from "@ember/object";import { next } from "@ember/runloop";import { service } from "@ember/service";-import DButton from "discourse/ui-kit/d-button";-import DExpandingTextArea from "discourse/ui-kit/d-expanding-text-area";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";-import dIcon from "discourse/ui-kit/helpers/d-icon";-import { i18n } from "discourse-i18n";-import PostEventBuilder from "discourse/plugins/discourse-calendar/discourse/components/modal/post-event-builder";-import guessDateFormat from "discourse/plugins/discourse-calendar/discourse/lib/guess-best-date-format";import {buildParams,camelCase,+ getCustomFieldNames,+ parseEventAttrs,+ stateToEventInput,} from "discourse/plugins/discourse-calendar/discourse/lib/raw-event-helper";-import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";+import CompactEventEditor from "./compact-event-editor";++const CLEARABLE_ATTRS = [+ "name",+ "location",+ "url",+ "end",+ "maxAttendees",+ "timezone",+ "recurrence",+ "recurrenceUntil",+ "showLocalTime",+ "minimal",+ "chatEnabled",+ "allDay",+ "allowedGroups",+ "reminders",+ "image",+ "closed",+];export default class EventNodeView extends Component {- @service composer;@service currentUser;- @service modal;@service siteSettings;- @service capabilities;constructor() {super(...arguments);this.args.onSetup?.(this);}- updateNodeAttribute(attributeName, value) {- if (!this.args.getPos || !this.args.view) {- return;- }-- // Schedule the update on the next runloop to avoid Ember tracking conflicts- next(() => {- const { view } = this.args;- const pos = this.args.getPos();- const node = view.state.doc.nodeAt(pos);-- if (!node) {- return;- }-- const newAttrs = { ...node.attrs, [attributeName]: value };- const tr = view.state.tr.setNodeMarkup(pos, null, newAttrs);- view.dispatch(tr);- });- }-- updateNodeContent(content) {- if (!this.args.getPos || !this.args.view) {- return;- }-- next(() => {- const { view } = this.args;- const pos = this.args.getPos();- const node = view.state.doc.nodeAt(pos);-- if (!node) {- return;- }-- const tr = view.state.tr;- const startPos = pos + 1; // Start inside the node- const endPos = pos + node.nodeSize - 1; // End inside the node-- // Replace the content- if (content.trim()) {- const textNode = view.state.schema.text(content);- tr.replaceWith(startPos, endPos, textNode);- } else {- // Clear content if empty- tr.delete(startPos, endPos);- }-- view.dispatch(tr);- });- }-- get eventData() {- return this.args.node.attrs;+ @action+ testLocationUrl(value) {+ return this.args.pluginParams.utils.getLinkify().test(value);}get eventDescription() {@@ -93,404 +54,96 @@ export default class EventNodeView extends Component {);}- get resolvedTimezone() {- return this.eventData.timezone || "UTC";- }-- get userTimezone() {- return this.currentUser?.user_option?.timezone || moment.tz.guess();- }-- parseDateWithTimezone(dateString) {- if (!dateString) {- return null;- }-- const date = moment.tz(dateString, this.resolvedTimezone);-- if (!date.isValid()) {- return moment.tz(this.userTimezone);- }-- return date;- }-- get startsAt() {- return this.parseDateWithTimezone(this.eventData.start);- }-- get endsAt() {- return this.parseDateWithTimezone(this.eventData.end);- }-- get displayTime() {- if (!this.startsAt) {- return null;- }-- if (this.eventData.showLocalTime) {- return this.startsAt;- } else {- return this.startsAt.tz(this.userTimezone);- }- }-- get displayEndTime() {- if (!this.endsAt) {- return null;- }-- if (this.eventData.showLocalTime) {- return this.endsAt;- } else {- return this.endsAt.tz(this.userTimezone);- }- }-- get dateFormat() {- return guessDateFormat(this.startsAt, this.endsAt);- }-- get formattedStartDate() {- return this.displayTime.format(this.dateFormat);- }-- get hasStartDate() {- return this.eventData.start && this.eventData.start.trim();- }-- get hasEndDate() {- return this.eventData.end && this.eventData.end.trim();- }-- get hasAnyDate() {- return this.hasStartDate || this.hasEndDate;- }-- get formattedEndDate() {- if (!this.displayEndTime) {- return "";- }- return this.displayEndTime.format(this.dateFormat);- }-- get formattedStartDisplay() {- return this.displayTime.format(i18n("dates.long_no_year"));- }-- get formattedEndDisplay() {- if (!this.displayEndTime) {- return i18n("discourse_post_event.composer.end_date_placeholder");- }- return this.displayEndTime.format(i18n("dates.long_no_year"));- }-- get startsAtMonth() {- if (!this.displayTime) {- // Show current month if no start date is set- const now = moment.tz(this.userTimezone);- return now.format("MMM");- }- return this.displayTime.format("MMM");- }-- get startsAtDay() {- if (!this.displayTime) {- // Show current day if no start date is set- const now = moment.tz(this.userTimezone);- return now.format("D");- }- return this.displayTime.format("D");- }-- get statusText() {- return i18n(- `discourse_post_event.models.event.status.${this.eventData.status || "public"}.title`- );- }-- get eventName() {- return this.eventData.name;- }-- get eventNamePlaceholder() {- return (- this.composer?.get("model.title") ||- i18n("discourse_post_event.composer.name_placeholder")- );- }-- get hasLocation() {- return this.eventData.location && this.eventData.location.trim();+ @cached+ get initialState() {+ return {+ ...parseEventAttrs(this.args.node.attrs, {+ fallbackTimezone: this.currentUser?.user_option?.timezone,+ customFieldNames: getCustomFieldNames(this.siteSettings),+ }),+ description: this.eventDescription,+ };}- get isLocationUrl() {- if (!this.hasLocation) {- return false;+ @action+ onChange(state) {+ if (!this.args.getPos || !this.args.view) {+ return;}- return this.args.pluginParams.utils- .getLinkify()- .test(this.eventData.location);- }-- get locationIcon() {- return this.isLocationUrl ? "link" : "location-pin";- }- get displayLocation() {- if (!this.hasLocation) {- return null;- }- if (this.isLocationUrl) {- const location = this.eventData.location.trim();- // Add protocol if missing for proper links- if (- location.startsWith("www.") ||- /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(location)- ) {- return location.includes("://") || location.includes("mailto:")- ? location- : `https://${location}`;+ next(() => {+ const { view } = this.args;+ const pos = this.args.getPos();+ const node = view.state.doc.nodeAt(pos);+ if (!node) {+ return;}- return location;- }- return this.eventData.location;- }-- get hasDescription() {- return this.eventDescription && this.eventDescription.length > 0;- }-- get formattedStartTime() {- if (!this.displayTime) {- const now = moment.tz(this.userTimezone);- return now.format("HH:mm");- }- return this.displayTime.format("HH:mm");- }-- get formattedEndTime() {- if (!this.displayEndTime) {- return "";- }- return this.displayEndTime.format("HH:mm");- }- formatDateTimeLocal(dateString) {- if (!dateString) {- return "";- }+ const params = buildParams(+ state.startsAt,+ state.endsAt,+ stateToEventInput(state),+ this.siteSettings+ );+ delete params.description;- const date = moment(dateString);- if (!date.isValid()) {- if (dateString.trim()) {- const today = moment.tz(this.userTimezone);- return today.format("YYYY-MM-DDTHH:mm");+ const customFieldAttrs = getCustomFieldNames(this.siteSettings).map((f) =>+ camelCase(f)+ );+ const newAttrs = { ...node.attrs };+ for (const attr of [+ ...CLEARABLE_ATTRS,+ "start",+ "status",+ ...customFieldAttrs,+ ]) {+ newAttrs[attr] = params[attr] ?? null;}- return "";- }- return date.format("YYYY-MM-DDTHH:mm");- }-- get formattedStartDateTime() {- return this.formatDateTimeLocal(this.eventData.start);- }-- get formattedEndDateTime() {- return this.formatDateTimeLocal(this.eventData.end);- }-- @action- updateEventName(event) {- event.target.value = event.target.value.replace(/\n/g, "");- const newName = event.target.value.trim();- this.updateNodeAttribute("name", newName);- }- @action- updateEventLocation(event) {- const newLocation = event.target.value.trim();- this.updateNodeAttribute("location", newLocation || null);- }-- @action- updateEventDescription(event) {- const newDescription = event.target.value.trim();- this.updateNodeContent(newDescription);- }-- @action- updateEventStartDate(event) {- const newDateTime = event.target.value;- const eventTz = this.eventData.timezone || "UTC";- if (newDateTime) {- const dt = moment.tz(newDateTime, eventTz);- this.updateNodeAttribute("start", dt.format("YYYY-MM-DD HH:mm"));- } else {- this.updateNodeAttribute(- "start",- moment().tz(eventTz).format("YYYY-MM-DD HH:mm")+ const noAttrChange = Object.keys(newAttrs).every(+ (key) => newAttrs[key] === node.attrs[key]);- }- }- @action- updateEventEndDate(event) {- const newDateTime = event.target.value;- const eventTz = this.eventData.timezone || "UTC";- if (newDateTime) {- const dt = moment.tz(newDateTime, eventTz);- this.updateNodeAttribute("end", dt.format("YYYY-MM-DD HH:mm"));- } else {- this.updateNodeAttribute("end", null);- }- }-- /**- * Parses reminder string back to array format for DiscoursePostEventEvent- * @param {string|Array} reminders - Either comma-separated string or array- * @returns {Array} Array of reminder objects- */- parseReminders(reminders) {- if (!reminders) {- return [];- }-- // If it's already an array, return as-is- if (Array.isArray(reminders)) {- return reminders;- }-- // Parse string format: "type.value.unit,type.value.unit"- return reminders.split(",").map((reminderStr) => {- const [type, value, unit] = reminderStr.split(".");- const numericValue = Math.abs(parseInt(value, 10));-- return {- type: type || "notification",- value: numericValue,- unit: unit || "hours",- period: parseInt(value, 10) < 0 ? "after" : "before",- };- });- }+ let tr = view.state.tr;+ if (!noAttrChange) {+ tr = tr.setNodeMarkup(pos, null, newAttrs);+ }- /**- * Reconstructs customFields object from individual node attributes- * @returns {Object} Custom fields object- */- parseCustomFields() {- const customFields = {};- const allowedCustomFields =- this.siteSettings.discourse_post_event_allowed_custom_fields- .split("|")- .filter(Boolean);+ const startPos = pos + 1;+ const endPos = pos + node.nodeSize - 1;+ const description = state.description || "";+ const currentDescription = this.eventDescription;+ if (description !== currentDescription) {+ if (description.trim()) {+ tr = tr.replaceWith(+ startPos,+ endPos,+ view.state.schema.text(description)+ );+ } else {+ tr = tr.delete(startPos, endPos);+ }+ }- // Convert each custom field back from camelCase to original name- allowedCustomFields.forEach((fieldName) => {- const camelCaseName = camelCase(fieldName);- if (typeof this.eventData[camelCaseName] !== "undefined") {- customFields[fieldName] = this.eventData[camelCaseName];+ if (tr.docChanged) {+ view.dispatch(tr);}});-- return customFields;- }-- @action- updateEventMaxAttendees(event) {- const newMax = parseInt(event.target.value, 10);- const validMax = Number.isFinite(newMax) && newMax > 0 ? newMax : null;- event.target.value = validMax || "";- this.updateNodeAttribute("maxAttendees", validMax);- }-- @action- focusDateInput(event) {- next(() => event.target.showPicker());}@action- handleTextInputFocus(event) {- if (this.capabilities.isIOS) {- setTimeout(() => {- event.target.scrollIntoView({ block: "center", behavior: "smooth" });- }, 400);+ onDelete() {+ if (!this.args.getPos || !this.args.view) {+ return;}- }-- convertNodeToEvent() {- const timezone = this.eventData.timezone || "UTC";-- return {- name: this.eventData.name,- location: this.eventData.location,- description: this.eventDescription,- timezone,- status: this.eventData.status || "public",- max_attendees: this.eventData.maxAttendees,- show_local_time: this.eventData.showLocalTime,- chat_enabled: this.eventData.chatEnabled,- minimal: this.eventData.minimal,- reminders: this.parseReminders(this.eventData.reminders) || [],- raw_invitees: this.eventData.allowedGroups?.split(",") || [],- custom_fields: this.parseCustomFields(),- starts_at: this.eventData.start- ? moment(this.eventData.start).tz(timezone)- : moment.tz(timezone),- ends_at: this.eventData.end- ? moment(this.eventData.end).tz(timezone)- : null,- image_upload: this.eventData.image ? { url: this.eventData.image } : null,- };- }-- @action- openEventBuilder() {- const eventData = this.convertNodeToEvent();-- this.modal.show(PostEventBuilder, {- model: {- event: DiscoursePostEventEvent.create(eventData),- onDelete: () => {- // Remove the event node from the document- if (!this.args.getPos || !this.args.view) {- return;- }-- const { view } = this.args;- const pos = this.args.getPos();- const node = view.state.doc.nodeAt(pos);-- if (!node) {- return;- }-- const tr = view.state.tr.delete(pos, pos + node.nodeSize);- view.dispatch(tr);-- return true;- },- onUpdate: (startsAt, endsAt, event) => {- // Use buildParams to get properly formatted parameters including reminders- const params = buildParams(- startsAt,- endsAt,- event,- this.siteSettings- );-- // Update node attributes with the built parameters- for (const [field, value] of Object.entries(params)) {- if (field === "description") {- this.updateNodeContent(value);- } else {- this.updateNodeAttribute(field, value);- }- }- },- },- });+ const { view } = this.args;+ const pos = this.args.getPos();+ const node = view.state.doc.nodeAt(pos);+ if (!node) {+ return;+ }+ const tr = view.state.tr.delete(pos, pos + node.nodeSize);+ view.dispatch(tr);}selectNode() {@@ -506,139 +159,11 @@ export default class EventNodeView extends Component {}<template>- <header class="composer-event__header">- <div class="composer-event__date">- <div class="composer-event__month">{{this.startsAtMonth}}</div>- <div class="composer-event__day">{{this.startsAtDay}}</div>- </div>-- <div class="composer-event__info">- <DExpandingTextArea- rows="1"- value={{this.eventName}}- class="composer-event__name-input"- placeholder={{this.eventNamePlaceholder}}- {{on "input" this.updateEventName}}- {{on "focus" this.handleTextInputFocus}}- />-- <div class="composer-event__status">- {{this.statusText}}- </div>- </div>-- <div class="composer-event__more-dropdown">- <DButton- @icon="gear"- @action={{this.openEventBuilder}}- @title="discourse_post_event.edit_event"- class="btn-flat"- />- </div>- </header>-- <section class="composer-event__dates">- {{dIcon "clock"}}- <div- class="composer-event__date-range{{if- this.hasAnyDate- ' composer-event__date-range--has-values'- }}"- >- <div class="composer-event__date-wrapper">- <input- type="datetime-local"- value={{this.formattedStartDateTime}}- class="composer-event__date-input"- {{on "change" this.updateEventStartDate}}- {{on "focus" this.focusDateInput}}- />- <span class="composer-event__date-display">- {{this.formattedStartDisplay}}- </span>- </div>- <span class="composer-event__date-separator">-</span>- <div class="composer-event__date-wrapper">- <input- type="datetime-local"- value={{this.formattedEndDateTime}}- class="composer-event__date-input"- {{on "change" this.updateEventEndDate}}- {{on "focus" this.focusDateInput}}- />- <span- class={{dConcatClass- "composer-event__date-display"- (unless this.hasEndDate "--empty")- }}- >- {{this.formattedEndDisplay}}- </span>- </div>- </div>- </section>-- <section class="composer-event__location">- {{dIcon this.locationIcon}}- <div class="composer-event__location-content">- <input- type="text"- value={{this.eventData.location}}- class="composer-event__location-input"- placeholder={{i18n- "discourse_post_event.composer.location_placeholder"- }}- {{on "input" this.updateEventLocation}}- {{on "focus" this.handleTextInputFocus}}- />- {{#if this.isLocationUrl}}- <a- class="composer-event__location-external-link"- href={{this.displayLocation}}- target="_blank"- rel="noopener noreferrer"- title="Visit {{this.eventData.location}}"- >- {{dIcon "up-right-from-square"}}- </a>- {{/if}}- </div>- </section>-- <section class="composer-event__attendees">- {{dIcon "users"}}- <input- type="number"- inputmode="numeric"- min="1"- step="1"- value={{this.eventData.maxAttendees}}- placeholder={{i18n- "discourse_post_event.composer.max_attendees_placeholder"- }}- class="composer-event__max-attendees-input"- {{on "input" this.updateEventMaxAttendees}}- />- {{#if this.eventData.maxAttendees}}- <span class="composer-event__max-attendees-display">- Max- {{this.eventData.maxAttendees}}- attendees- </span>- {{/if}}- </section>-- <section class="composer-event__description">- <DExpandingTextArea- class="composer-event__description-textarea"- placeholder={{i18n- "discourse_post_event.composer.description_placeholder"- }}- value={{this.eventDescription}}- rows="1"- {{on "input" this.updateEventDescription}}- {{on "focus" this.handleTextInputFocus}}- />- </section>+ <CompactEventEditor+ @initialState={{this.initialState}}+ @urlTester={{this.testLocationUrl}}+ @onChange={{this.onChange}}+ @onDelete={{this.onDelete}}+ /></template>}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjsindex ab18b98fac1..1a15ea0b36c 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/modal/post-event-builder.gjs@@ -1,28 +1,32 @@-/* eslint-disable ember/no-tracked-properties-from-args */import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { concat, fn, get } from "@ember/helper";import { on } from "@ember/modifier";-import { action } from "@ember/object";+import EmberObject, { action } from "@ember/object";import { service } from "@ember/service";+import Form from "discourse/components/form";import GroupSelector from "discourse/components/group-selector";import PluginOutlet from "discourse/components/plugin-outlet";-import UppyImageUploader from "discourse/components/uppy-image-uploader";import lazyHash from "discourse/helpers/lazy-hash";import { extractError } from "discourse/lib/ajax-error";import Group from "discourse/models/group";-import ComboBox from "discourse/select-kit/components/combo-box";import TimezoneInput from "discourse/select-kit/components/timezone-input";-import { eq } from "discourse/truth-helpers";+import { eq, not } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DConditionalLoadingSection from "discourse/ui-kit/d-conditional-loading-section";import DDateInput from "discourse/ui-kit/d-date-input";-import DDateTimeInputRange from "discourse/ui-kit/d-date-time-input-range";+import DDateTimeInput from "discourse/ui-kit/d-date-time-input";import DModal from "discourse/ui-kit/d-modal";-import DRadioButton from "discourse/ui-kit/d-radio-button";import { i18n } from "discourse-i18n";-import { buildParams } from "../../lib/raw-event-helper";-import EventField from "../event-field";+import {+ attendanceTransition,+ buildParams,+ defaultEventState,+ defaultReminderFor,+ getCustomFieldNames,+ reconcileDefaultReminder,+} from "../../lib/raw-event-helper";+import CompactEventEditor from "../compact-event-editor";export default class PostEventBuilder extends Component {@service dialog;@@ -31,11 +35,30 @@ export default class PostEventBuilder extends Component {@tracked flash = null;@tracked isSaving = false;- @tracked maxAttendeesInput = this.args.model.event.maxAttendees;+ @tracked screen = this.args.model.initialScreen || "compact";@tracked allDay = this.event.allDay || false;@tracked startsAt = this.#initStartsAt();@tracked endsAt = this.#initEndsAt();+ @tracked+ previousRsvpStatus =+ this.event.status === "standalone" ? "public" : this.event.status;+ @tracked previousMaxAttendees = this.event.maxAttendees || null;+ @tracked attendanceMode = this.#initAttendanceMode();++ // FormKit clones @data once on mount and treats it as immutable. Reading+ // tracked event properties from a getter would invalidate this on every+ // mirror-write and reinitialize the form (losing focus mid-keystroke).+ // Snapshot once at construction; refresh only when toggleAdvanced enters+ // the advanced screen.+ formData = this.#snapshotFormData();++ #initAttendanceMode() {+ if (this.event.status === "standalone") {+ return "none";+ }+ return this.event.maxAttendees ? "upTo" : "unlimited";+ }#initStartsAt() {if (this.event.allDay) {@@ -73,8 +96,169 @@ export default class PostEventBuilder extends Component {return this.args.model.event;}+ #snapshotFormData() {+ return {+ name: this.event.name ?? "",+ location: this.event.location ?? "",+ url: this.event.url ?? "",+ description: this.event.description ?? "",+ startsAt: this.startsAt ?? null,+ endsAt: this.endsAt ?? null,+ allDay: !!this.event.allDay,+ showLocalTime: !!this.event.showLocalTime,+ chatEnabled: !!this.event.chatEnabled,+ attendanceMode: this.attendanceMode,+ maxAttendees: this.event.maxAttendees ?? null,+ eventType:+ this.event.status === "standalone"+ ? this.previousRsvpStatus || "public"+ : this.event.status || "public",+ rawInvitees: this.event.rawInvitees ?? [],+ recurrence: this.event.recurrence ?? null,+ imageUpload: this.event.imageUpload ?? null,+ timezone: this.event.timezone ?? null,+ // clone so the form draft owns its own reminders+ reminders: (this.event.reminders ?? []).map((r) => ({ ...r })),+ };+ }++ @action+ registerForm(api) {+ this.formApi = api;+ }++ // mirror and change back to event model to keep compact view synced+ @action+ syncFieldToEvent(field, value, { set }) {+ set(field, value);+ this.event[field] = value;+ }++ @action+ handleAllDayChange(value, { set }) {+ set("allDay", value);+ this.updateAllDay(value);+ }++ @action+ handleAttendanceModeChange(value, { set }) {+ set("attendanceMode", value);+ // setAttendanceMode mirrors the resulting state back to the form+ this.setAttendanceMode(value);+ }++ @action+ handleMaxAttendeesChange(value, { set }) {+ set("maxAttendees", value);+ if (value === 0) {+ this.setAttendanceMode("none");+ return;+ }+ if (value > 0) {+ this.#applyUpToValue(value);+ return;+ }+ // just clear the data+ this.event.maxAttendees = null;+ }++ #applyUpToValue(value) {+ if (this.event.status === "standalone") {+ this.event.status = this.previousRsvpStatus || "public";+ this.event.reminders = (this.event.reminders || []).map((r) =>+ r.type === "bumpTopic" ? { ...r, type: "notification" } : r+ );+ this.#syncRemindersToForm();+ }+ this.attendanceMode = "upTo";+ this.event.maxAttendees = value;+ this.previousMaxAttendees = value;+ this.formApi?.setProperties({+ attendanceMode: "upTo",+ maxAttendees: value,+ eventType: this.event.status,+ });+ }++ @action+ handleEventTypeChange(value, { set }) {+ set("eventType", value);+ this.onChangeStatus(value);+ }++ // GroupSelector uses (_, newGroups). Adapt to the form's field setter and+ // mirror onto event so the BBCode build picks it up.+ @action+ handleInviteesChange(_, newInvitees) {+ this.formApi?.set("rawInvitees", newInvitees);+ this.event.rawInvitees = newInvitees;+ }++ @action+ handleRecurrenceChange(value, { set }) {+ set("recurrence", value);+ this.setRecurrence(value);+ }++ @action+ handleImageChange(value, { set }) {+ set("imageUpload", value);+ this.event.imageUpload = value;+ }++ @action+ handleTimezoneChange(value, { set }) {+ set("timezone", value);+ // setNewTimezone re-anchors startsAt/endsAt in the new zone.+ this.setNewTimezone(value);+ }++ @action+ handleReminderFieldChange(field, index, value, { set }) {+ set(field, value);+ if (!this.event.reminders?.[index]) {+ return;+ }+ this.event.reminders = this.event.reminders.map((r, i) =>+ i === index ? { ...r, [field]: value } : r+ );+ }++ @action+ handleAddReminder(addItemToCollection) {+ const def = defaultReminderFor({+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ allDay: this.allDay,+ });+ const reminder = {+ type: this.allowsRsvps ? def.type : "bumpTopic",+ value: def.value,+ unit: def.unit,+ period: def.period,+ };+ this.event.addReminder(reminder);+ addItemToCollection("reminders", { ...reminder });+ }++ @action+ handleRemoveReminder(index, collectionRemove) {+ this.event.reminders.splice(index, 1);+ collectionRemove(index);+ }++ #syncRemindersToForm() {+ if (!this.formApi) {+ return;+ }+ this.formApi.set(+ "reminders",+ (this.event.reminders ?? []).map((r) => ({ ...r }))+ );+ }+get reminderTypes() {- return [+ const types = [{value: "notification",name: i18n(@@ -88,6 +272,9 @@ export default class PostEventBuilder extends Component {),},];+ return this.allowsRsvps+ ? types+ : types.filter((t) => t.value !== "notification");}get reminderUnits() {@@ -113,37 +300,27 @@ export default class PostEventBuilder extends Component {];}- get reminderPeriods() {- return [- {- value: "before",- name: i18n(- "discourse_post_event.builder_modal.reminders.periods.before"- ),- },- {- value: "after",- name: i18n(- "discourse_post_event.builder_modal.reminders.periods.after"- ),- },- ];- }-get shouldRenderUrl() {return this.args.model.event.url !== undefined;}get availableRecurrences() {+ const ref = this.startsAt || moment();+ const weekday = ref.format("dddd");+ const dayOfMonth = ref.date();+ const isLast = dayOfMonth + 7 > ref.daysInMonth();+ const ordinalKey = isLast+ ? "last"+ : ["first", "second", "third", "fourth"][Math.ceil(dayOfMonth / 7) - 1];+ const ordinal = i18n(+ `discourse_post_event.builder_modal.recurrence.ordinals.${ordinalKey}`+ );+return [{id: "every_day",name: i18n("discourse_post_event.builder_modal.recurrence.every_day"),},- {- id: "every_month",- name: i18n("discourse_post_event.builder_modal.recurrence.every_month"),- },{id: "every_weekday",name: i18n(@@ -152,27 +329,36 @@ export default class PostEventBuilder extends Component {},{id: "every_week",- name: i18n("discourse_post_event.builder_modal.recurrence.every_week"),+ name: i18n("discourse_post_event.builder_modal.recurrence.every_week", {+ weekday,+ }),},{id: "every_two_weeks",name: i18n(- "discourse_post_event.builder_modal.recurrence.every_two_weeks"+ "discourse_post_event.builder_modal.recurrence.every_two_weeks",+ { weekday }),},{id: "every_four_weeks",name: i18n(- "discourse_post_event.builder_modal.recurrence.every_four_weeks"+ "discourse_post_event.builder_modal.recurrence.every_four_weeks",+ { weekday }+ ),+ },+ {+ id: "every_month",+ name: i18n(+ "discourse_post_event.builder_modal.recurrence.every_month",+ { ordinal, weekday }),},];}get allowedCustomFields() {- return this.siteSettings.discourse_post_event_allowed_custom_fields- .split("|")- .filter(Boolean);+ return getCustomFieldNames(this.siteSettings);}get addReminderDisabled() {@@ -187,6 +373,181 @@ export default class PostEventBuilder extends Component {);}+ get isAdvancedScreen() {+ return this.screen === "advanced";+ }++ get showScreenToggle() {+ return this.args.model.initialScreen !== "advanced";+ }++ get userTimezone() {+ return this.currentUser?.user_option?.timezone || moment.tz.guess();+ }++ get statusText() {+ const status =+ this.event.status === "standalone"+ ? "public"+ : this.event.status || "public";+ return i18n(`discourse_post_event.models.event.status.${status}.title`);+ }++ get eventNamePlaceholder() {+ return i18n("discourse_post_event.composer.name_placeholder");+ }++ get compactInitialState() {+ return {+ ...defaultEventState(),+ name: this.event.name ?? null,+ location: this.event.location ?? null,+ description: this.event.description ?? "",+ timezone: this.event.timezone ?? "UTC",+ status: this.event.status ?? "public",+ maxAttendees: this.event.maxAttendees ?? null,+ allDay: !!this.allDay,+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ reminders: this.event.reminders ?? [],+ recurrence: this.event.recurrence ?? null,+ recurrenceUntil: this.event.recurrenceUntil ?? null,+ showLocalTime: !!this.event.showLocalTime,+ chatEnabled: !!this.event.chatEnabled,+ minimal: !!this.event.minimal,+ url: this.event.url ?? null,+ image:+ this.event.imageUpload?.short_url ??+ this.event.imageUpload?.url ??+ null,+ allowedGroups: (this.event.rawInvitees || []).join(",") || null,+ closed: !!this.event.isClosed,+ customFields: { ...(this.event.customFields || {}) },+ };+ }++ @action+ urlTester(value) {+ return /^(https?:\/\/|www\.|mailto:)/i.test(value);+ }++ @action+ onCompactChange(state) {+ this.event.name = state.name;+ this.event.location = state.location || "";+ this.event.description = state.description;+ this.event.timezone = state.timezone;+ this.event.status = state.status;+ this.event.maxAttendees = state.maxAttendees;+ this.event.showLocalTime = state.showLocalTime;+ this.event.chatEnabled = state.chatEnabled;+ this.event.minimal = state.minimal;+ this.event.url = state.url;+ this.event.recurrence = state.recurrence;+ this.event.recurrenceUntil = state.recurrenceUntil;+ this.event.reminders = state.reminders;+ this.event.rawInvitees = state.allowedGroups+ ? state.allowedGroups.split(",")+ : [];+ this.event.allDay = state.allDay;+ this.event.startsAt = state.startsAt;+ this.event.endsAt = state.endsAt;+ this.event.isClosed = state.closed;+ this.event.imageUpload = state.image ? { url: state.image } : null;+ this.event.customFields = EmberObject.create({+ ...(state.customFields || {}),+ });+ this.allDay = state.allDay;+ this.startsAt = state.startsAt;+ this.endsAt = state.endsAt;++ if (state.status === "standalone") {+ this.attendanceMode = "none";+ } else if (state.maxAttendees) {+ this.attendanceMode = "upTo";+ this.previousMaxAttendees = state.maxAttendees;+ } else {+ this.attendanceMode = "unlimited";+ }+ if (state.status && state.status !== "standalone") {+ this.previousRsvpStatus = state.status;+ }+ }++ @action+ toggleAdvanced() {+ if (this.isAdvancedScreen) {+ // Leaving advanced — drop the stale form API reference.+ this.formApi = null;+ this.screen = "compact";+ } else {+ // Entering advanced — re-snapshot from the (possibly compact-edited)+ // event before the form mounts.+ this.formData = this.#snapshotFormData();+ this.screen = "advanced";+ }+ }++ #captureConfig() {+ return {+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ allDay: this.allDay,+ };+ }++ #reconcileReminder(prevConfig) {+ const next = reconcileDefaultReminder(+ this.event.reminders,+ prevConfig,+ this.#captureConfig()+ );+ if (next !== this.event.reminders) {+ this.event.reminders = next;+ }+ }++ @action+ updateAllDay(allDay) {+ const prev = this.#captureConfig();+ this.allDay = allDay;+ this.event.allDay = allDay;+ if (allDay) {+ const tz = this.event.timezone || "UTC";+ const snapped = (this.startsAt ?? moment.tz(tz)).clone().startOf("day");+ this.startsAt = snapped;+ this.event.startsAt = snapped;++ const existingEnd = this.endsAt;+ let newEnd = null;+ if (existingEnd) {+ const startDate = snapped.format("YYYY-MM-DD");+ const endDate = existingEnd.format("YYYY-MM-DD");+ if (endDate !== startDate) {+ newEnd = existingEnd.clone().startOf("day");+ }+ }+ this.endsAt = newEnd;+ this.event.endsAt = newEnd;+ } else if (this.startsAt) {+ const tz = this.event.timezone || "UTC";+ const nowTime = moment.tz(tz);+ const newStart = this.startsAt+ .clone()+ .hour(nowTime.hour())+ .minute(nowTime.minute())+ .second(0)+ .millisecond(0);+ this.startsAt = newStart;+ this.event.startsAt = newStart;++ const newEnd = newStart.clone().add(1, "hour");+ this.endsAt = newEnd;+ this.event.endsAt = newEnd;+ }+ this.#reconcileReminder(prev);+ }+@actiongroupFinder(term) {return Group.findAll({ term, ignore_automatic: true });@@ -197,42 +558,72 @@ export default class PostEventBuilder extends Component {this.event.customFields[field] = e.target.value;}- @action- setMaxAttendees(e) {- const raw = e.target.value;- const value = parseInt(raw, 10);- this.event.maxAttendees =- Number.isFinite(value) && value > 0 ? value : null;- this.maxAttendeesInput = raw;- }-@actiononChangeDates(dates) {+ const prev = this.#captureConfig();this.event.startsAt = dates.from;this.event.endsAt = dates.to;this.startsAt = dates.from;this.endsAt = dates.to;+ this.#reconcileReminder(prev);}@action- setAllDay(e) {- this.allDay = e.target.checked;- this.event.allDay = e.target.checked;- if (e.target.checked) {- // snap times to start/end of day in the event's timezone- if (this.startsAt) {- this.startsAt = this.startsAt.clone().startOf("day");- }- if (this.endsAt) {- this.endsAt = this.endsAt.clone().endOf("day");- }- }+ onChangeStartsAt(set, value) {+ const to =+ value && this.endsAt && value.isAfter(this.endsAt)+ ? value.clone().add(1, "hour")+ : this.endsAt;+ this.onChangeDates({ from: value, to });+ set(value);+ }++ @action+ onChangeEndsAt(set, value) {+ const to =+ value && this.startsAt && value.isBefore(this.startsAt)+ ? this.startsAt.clone().add(1, "hour")+ : value;+ this.onChangeDates({ from: this.startsAt, to });+ set(to);+ }++ get allowsRsvps() {+ return this.event.status !== "standalone";+ }++ @action+ setAttendanceMode(mode) {+ this.attendanceMode = mode;+ const next = attendanceTransition({+ mode,+ status: this.event.status,+ maxAttendees: this.event.maxAttendees,+ reminders: this.event.reminders,+ previousRsvpStatus: this.previousRsvpStatus,+ previousMaxAttendees: this.previousMaxAttendees,+ });+ this.event.status = next.status;+ this.event.maxAttendees = next.maxAttendees;+ this.event.reminders = next.reminders;+ this.previousRsvpStatus = next.previousRsvpStatus;+ this.previousMaxAttendees = next.previousMaxAttendees;+ this.formApi?.setProperties({+ attendanceMode: mode,+ maxAttendees: next.maxAttendees,+ eventType:+ next.status === "standalone"+ ? this.previousRsvpStatus || "public"+ : next.status,+ });+ this.#syncRemindersToForm();}@actiononChangeStatus(newStatus) {this.event.rawInvitees = [];this.event.status = newStatus;+ this.formApi?.set("rawInvitees", []);}@action@@ -255,11 +646,6 @@ export default class PostEventBuilder extends Component {}}- @action- setRawInvitees(_, newInvitees) {- this.event.rawInvitees = newInvitees;- }-@actionsetNewTimezone(newTz) {this.event.timezone = newTz;@@ -276,60 +662,6 @@ export default class PostEventBuilder extends Component {: null;}- // Native input handlers- @action- setName(e) {- this.event.name = e.target.value;- }-- @action- setLocation(e) {- this.event.location = e.target.value;- }-- @action- setUrl(e) {- this.event.url = e.target.value;- }-- @action- setDescription(e) {- this.event.description = e.target.value;- }-- @action- setShowLocalTime(e) {- this.event.showLocalTime = e.target.checked;- }-- @action- setImage(upload) {- this.event.imageUpload = upload;- }-- @action- removeImage() {- this.event.imageUpload = null;- }-- @action- setMinimal(e) {- this.event.minimal = e.target.checked;- }-- @action- setChatEnabled(e) {- this.event.chatEnabled = e.target.checked;- }-- @action- setReminderValue(reminder, e) {- const val = e.target.value;- // keep numeric when possible- const parsed = val === "" ? null : Number(val);- reminder.value = Number.isFinite(parsed) ? parsed : val;- }-@actionasync destroyPostEvent() {try {@@ -406,397 +738,538 @@ export default class PostEventBuilder extends Component {@title={{i18n(concat"discourse_post_event.builder_modal."- (if this.isEditing "update_event_title" "create_event_title")+ (if+ this.isAdvancedScreen+ "advanced_settings_title"+ (if this.isEditing "update_event_title" "create_event_title")+ ))}}@closeModal={{@closeModal}}@flash={{this.flash}}- class="post-event-builder-modal"+ class="post-event-builder-modal+ {{if this.isAdvancedScreen 'is-advanced' 'is-compact'}}"><:body><DConditionalLoadingSection @isLoading={{this.isSaving}}>- <form>- <PluginOutlet- @name="post-event-builder-form"- @outletArgs={{lazyHash [email protected]}}- @connectorTagName="div"+ {{#if this.isAdvancedScreen}}+ <Form+ @data={{this.formData}}+ @onRegisterApi={{this.registerForm}}+ as |form|>- <EventField>- <DDateTimeInputRange- @from={{this.startsAt}}- @to={{this.endsAt}}- @timezone={{@model.event.timezone}}- @onChange={{this.onChangeDates}}- @showFromTime={{this.showTime}}- @showToTime={{this.showTime}}- />- </EventField>-- <EventField- @label="discourse_post_event.builder_modal.all_day.label"- class="all-day"+ <PluginOutlet+ @name="post-event-builder-form"+ @outletArgs={{lazyHash [email protected] form=form}}+ @connectorTagName="div">- <label class="checkbox-label">- <input- type="checkbox"- checked={{this.allDay}}- {{on "input" this.setAllDay}}- />- <span class="message">+ <form.Field+ @name="startsAt"+ @type="custom"+ @format="full"+ @title={{i18n+ "discourse_post_event.builder_modal.starts_at.label"+ }}+ @validation="required"+ as |field|+ >+ <field.Control>+ <DDateTimeInput+ @date={{this.startsAt}}+ @onChange={{fn this.onChangeStartsAt field.set}}+ @showTime={{this.showTime}}+ @timezone={{@model.event.timezone}}+ @placeholder={{i18n "dates.from_placeholder"}}+ class="from"+ />+ </field.Control>+ </form.Field>++ <form.Field+ @name="endsAt"+ @type="custom"+ @format="full"+ @title={{i18n+ "discourse_post_event.builder_modal.ends_at.label"+ }}+ @validation="required"+ as |field|+ >+ <field.Control>+ <DDateTimeInput+ @date={{this.endsAt}}+ @relativeDate={{this.startsAt}}+ @onChange={{fn this.onChangeEndsAt field.set}}+ @showTime={{this.showTime}}+ @timezone={{@model.event.timezone}}+ @placeholder={{i18n "dates.to_placeholder"}}+ class="to"+ />+ </field.Control>+ </form.Field>++ <form.Field+ @name="allDay"+ @title={{i18n+ "discourse_post_event.builder_modal.all_day.label"+ }}+ @type="checkbox"+ @format="full"+ @onSet={{this.handleAllDayChange}}+ as |field|+ >+ <field.Control>{{i18n"discourse_post_event.builder_modal.all_day.description"}}- </span>- </label>- </EventField>+ </field.Control>+ </form.Field>- <EventField- @label="discourse_post_event.builder_modal.name.label"- class="name"- >- <input- type="text"- value={{@model.event.name}}- {{on "input" this.setName}}- placeholder={{i18n- "discourse_post_event.builder_modal.name.placeholder"+ <form.Field+ @name="name"+ @title={{i18n+ "discourse_post_event.builder_modal.name.label"}}- />- </EventField>+ @type="input"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "name"}}+ as |field|+ >+ <field.Control+ placeholder={{i18n+ "discourse_post_event.builder_modal.name.placeholder"+ }}+ />+ </form.Field>- <EventField- @label="discourse_post_event.builder_modal.location.label"- class="location"- >- <input- type="text"- value={{@model.event.location}}- {{on "input" this.setLocation}}- placeholder={{i18n- "discourse_post_event.builder_modal.location.placeholder"+ <form.Field+ @name="location"+ @title={{i18n+ "discourse_post_event.builder_modal.location.label"}}- />- </EventField>-- {{#if this.shouldRenderUrl}}- <EventField- @label="discourse_post_event.builder_modal.url.label"- class="url"+ @type="input"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "location"}}+ as |field|>- <input- type="url"- value={{@model.event.url}}- {{on "input" this.setUrl}}+ <field.Controlplaceholder={{i18n- "discourse_post_event.builder_modal.url.placeholder"+ "discourse_post_event.builder_modal.location.placeholder"}}/>- </EventField>- {{/if}}+ </form.Field>- <EventField- @label="discourse_post_event.builder_modal.description.label"- class="description"- >- <textarea- value={{@model.event.description}}- {{on "input" this.setDescription}}- placeholder={{i18n- "discourse_post_event.builder_modal.description.placeholder"+ {{#if this.shouldRenderUrl}}+ <form.Field+ @name="url"+ @title={{i18n+ "discourse_post_event.builder_modal.url.label"+ }}+ @type="input-url"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "url"}}+ as |field|+ >+ <field.Control+ placeholder={{i18n+ "discourse_post_event.builder_modal.url.placeholder"+ }}+ />+ </form.Field>+ {{/if}}++ <form.Field+ @name="description"+ @title={{i18n+ "discourse_post_event.builder_modal.description.label"}}- ></textarea>- </EventField>+ @type="textarea"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "description"}}+ as |field|+ >+ <field.Control+ @autoResize={{true}}+ placeholder={{i18n+ "discourse_post_event.builder_modal.description.placeholder"+ }}+ />+ </form.Field>- <EventField- class="max-attendees"- @label="discourse_post_event.builder_modal.max_attendees.label"- >- <input- type="number"- min="1"- step="1"- value={{this.maxAttendeesInput}}- {{on "input" this.setMaxAttendees}}- placeholder={{i18n- "discourse_post_event.builder_modal.max_attendees.placeholder"+ <form.Field+ @name="attendanceMode"+ @title={{i18n+ "discourse_post_event.builder_modal.attendance.label"}}- />- </EventField>+ @type="radio-group"+ @format="full"+ @validation="required"+ @onSet={{this.handleAttendanceModeChange}}+ as |field|+ >+ <field.Control as |radioGroup|>+ <radioGroup.Radio @value="unlimited" as |radio|>+ <radio.Title>+ {{i18n+ "discourse_post_event.builder_modal.attendance.unlimited"+ }}+ </radio.Title>+ </radioGroup.Radio>+ <radioGroup.Radio @value="upTo" as |radio|>+ <radio.Title>+ {{i18n+ "discourse_post_event.builder_modal.attendance.up_to"+ }}+ </radio.Title>+ <radio.Description>+ <form.Field+ @name="maxAttendees"+ @title={{i18n+ "discourse_post_event.builder_modal.max_attendees.label"+ }}+ @showTitle={{false}}+ @type="input-number"+ @disabled={{not (eq field.value "upTo")}}+ @onSet={{this.handleMaxAttendeesChange}}+ as |maxField|+ >+ <maxField.Control min="0" />+ </form.Field>+ </radio.Description>+ </radioGroup.Radio>+ <radioGroup.Radio @value="none" as |radio|>+ <radio.Title>+ {{i18n+ "discourse_post_event.builder_modal.attendance.none"+ }}+ </radio.Title>+ </radioGroup.Radio>+ </field.Control>+ </form.Field>++ {{#if this.allowsRsvps}}+ <form.Field+ @name="eventType"+ @title={{i18n+ "discourse_post_event.builder_modal.event_type.label"+ }}+ @type="radio-group"+ @format="full"+ @validation="required"+ @onSet={{this.handleEventTypeChange}}+ as |field|+ >+ <field.Control as |radioGroup|>+ <radioGroup.Radio @value="public" as |radio|>+ <radio.Title>+ {{i18n+ "discourse_post_event.builder_modal.event_type.public.title"+ }}+ </radio.Title>+ <radio.Description>+ {{i18n+ "discourse_post_event.builder_modal.event_type.public.description"+ }}+ </radio.Description>+ </radioGroup.Radio>+ <radioGroup.Radio @value="private" as |radio|>+ <radio.Title>+ {{i18n+ "discourse_post_event.builder_modal.event_type.private.title"+ }}+ </radio.Title>+ <radio.Description>+ {{i18n+ "discourse_post_event.builder_modal.event_type.private.description"+ }}+ </radio.Description>+ </radioGroup.Radio>+ </field.Control>+ </form.Field>++ {{#if (eq @model.event.status "private")}}+ <form.Field+ @name="rawInvitees"+ @title={{i18n+ "discourse_post_event.builder_modal.invitees.label"+ }}+ @type="custom"+ @format="full"+ as |field|+ >+ <field.Control>+ <GroupSelector+ @groupFinder={{this.groupFinder}}+ @groupNames={{field.value}}+ @onChangeCallback={{this.handleInviteesChange}}+ @placeholderKey="topic.invite_private.group_name"+ />+ </field.Control>+ </form.Field>+ {{/if}}+ {{/if}}++ <form.Field+ @name="timezone"+ @title={{i18n+ "discourse_post_event.builder_modal.timezone.label"+ }}+ @type="custom"+ @format="full"+ @validation="required"+ @onSet={{this.handleTimezoneChange}}+ as |field|+ >+ <field.Control>+ <TimezoneInput+ @value={{field.value}}+ @onChange={{field.set}}+ @none="discourse_post_event.builder_modal.timezone.remove_timezone"+ />+ </field.Control>+ </form.Field>- <EventField- class="timezone"- @label="discourse_post_event.builder_modal.timezone.label"- >- <TimezoneInput- @value={{@model.event.timezone}}- @onChange={{this.setNewTimezone}}- @none="discourse_post_event.builder_modal.timezone.remove_timezone"- />- </EventField>-- <EventField- class="show-local-time"- @label="discourse_post_event.builder_modal.show_local_time.label"- >- <label class="checkbox-label">- <input- type="checkbox"- checked={{@model.event.showLocalTime}}- {{on "input" this.setShowLocalTime}}- />- <span class="message">+ <form.Field+ @name="showLocalTime"+ @title={{i18n+ "discourse_post_event.builder_modal.show_local_time.label"+ }}+ @type="checkbox"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "showLocalTime"}}+ as |field|+ >+ <field.Control>{{i18n"discourse_post_event.builder_modal.show_local_time.description"}}- </span>- </label>- </EventField>+ </field.Control>+ </form.Field>- <EventField- @label="discourse_post_event.builder_modal.status.label"- >- <label class="radio-label">- <DRadioButton- @name="status"- @value="public"- @selection={{@model.event.status}}- @onChange={{this.onChangeStatus}}- />- <span class="message">- <span class="title">- {{i18n- "discourse_post_event.models.event.status.public.title"- }}- </span>- <span class="description">- {{i18n- "discourse_post_event.models.event.status.public.description"- }}- </span>- </span>- </label>- <label class="radio-label">- <DRadioButton- @name="status"- @value="private"- @selection={{@model.event.status}}- @onChange={{this.onChangeStatus}}- />- <span class="message">- <span class="title">- {{i18n- "discourse_post_event.models.event.status.private.title"- }}- </span>- <span class="description">- {{i18n- "discourse_post_event.models.event.status.private.description"- }}- </span>- </span>- </label>- <label class="radio-label">- <DRadioButton- @name="status"- @value="standalone"- @selection={{@model.event.status}}- @onChange={{this.onChangeStatus}}- />- <span class="message">- <span class="title">- {{i18n- "discourse_post_event.models.event.status.standalone.title"- }}- </span>- <span class="description">- {{i18n- "discourse_post_event.models.event.status.standalone.description"- }}- </span>- </span>- </label>- </EventField>-- <EventField- @enabled={{eq @model.event.status "private"}}- @label="discourse_post_event.builder_modal.invitees.label"- >- <GroupSelector- @groupFinder={{this.groupFinder}}- @groupNames={{@model.event.rawInvitees}}- @onChangeCallback={{this.setRawInvitees}}- @placeholderKey="topic.invite_private.group_name"- />- </EventField>-- <EventField- @label="discourse_post_event.builder_modal.image.label"- class="image"- >- <UppyImageUploader- @id="post-event-image-uploader"- @imageUrl={{this.event.imageUrl}}- @onUploadDone={{this.setImage}}- @onUploadDeleted={{this.removeImage}}- @type="event_image"- />- </EventField>-- <EventField- class="reminders"- @label="discourse_post_event.builder_modal.reminders.label"- >- <div class="reminders-list">- {{#each @model.event.reminders as |reminder|}}+ <form.Container+ class="reminders"+ @title={{i18n+ "discourse_post_event.builder_modal.reminders.label"+ }}+ @format="full"+ @optional={{true}}+ >+ <form.Collection+ @name="reminders"+ class="reminders-list"+ as |collection index|+ ><div class="reminder-item">- <ComboBox- @value={{reminder.type}}- @nameProperty="name"- @valueProperty="value"- @content={{this.reminderTypes}}+ <collection.Field+ @name="type"+ @title={{i18n+ "discourse_post_event.builder_modal.reminders.types.notification"+ }}+ @showTitle={{false}}+ @type="select"+ @validation="required"+ @onSet={{fn+ this.handleReminderFieldChange+ "type"+ index+ }}class="reminder-type"- />-- <input- type="number"+ as |field|+ >+ <field.Control as |select|>+ {{#each this.reminderTypes as |opt|}}+ <select.Option+ @value={{opt.value}}+ >{{opt.name}}</select.Option>+ {{/each}}+ </field.Control>+ </collection.Field>++ <collection.Field+ @name="value"+ @title={{i18n+ "discourse_post_event.builder_modal.reminders.label"+ }}+ @showTitle={{false}}+ @type="input-number"+ @onSet={{fn+ this.handleReminderFieldChange+ "value"+ index+ }}class="reminder-value"- min="0"- step="1"- value={{reminder.value}}- {{on "input" (fn this.setReminderValue reminder)}}- placeholder={{i18n- "discourse_post_event.builder_modal.name.placeholder"+ as |field|+ >+ <field.Control min="0" />+ </collection.Field>++ <collection.Field+ @name="unit"+ @title={{i18n+ "discourse_post_event.builder_modal.reminders.units.minutes"+ }}+ @showTitle={{false}}+ @type="select"+ @validation="required"+ @onSet={{fn+ this.handleReminderFieldChange+ "unit"+ index}}- />-- <ComboBox- @value={{reminder.unit}}- @nameProperty="name"- @valueProperty="value"- @content={{this.reminderUnits}}class="reminder-unit"- />-- <ComboBox- @value={{reminder.period}}- @nameProperty="name"- @valueProperty="value"- @content={{this.reminderPeriods}}- class="reminder-period"- />+ as |field|+ >+ <field.Control as |select|>+ {{#each this.reminderUnits as |opt|}}+ <select.Option+ @value={{opt.value}}+ >{{opt.name}}</select.Option>+ {{/each}}+ </field.Control>+ </collection.Field>++ <div class="reminder-period">+ {{i18n+ "discourse_post_event.builder_modal.reminders.periods.before"+ }}- <DButton- @action={{fn @model.event.removeReminder reminder}}- @icon="xmark"- class="btn-default remove-reminder"- />+ <DButton+ @action={{fn+ this.handleRemoveReminder+ index+ collection.remove+ }}+ @icon="xmark"+ class="btn-default remove-reminder"+ />+ </div></div>- {{/each}}- </div>-- <DButton- @disabled={{this.addReminderDisabled}}- @icon="plus"- @label="discourse_post_event.builder_modal.add_reminder"- @action={{@model.event.addReminder}}- class="btn-default add-reminder"- />- </EventField>-- <EventField- class="recurrence"- @label="discourse_post_event.builder_modal.recurrence.label"- >- <ComboBox- class="available-recurrences"- @value={{@model.event.recurrence}}- @content={{this.availableRecurrences}}- @onChange={{this.setRecurrence}}- @options={{lazyHash- none="discourse_post_event.builder_modal.recurrence.none"- }}- />- </EventField>-- {{#if @model.event.recurrence}}- <EventField- @label="discourse_post_event.builder_modal.recurrence_until.label"- class="recurrence-until"- >- <DDateInput- @date={{this.recurrenceUntil}}- @onChange={{this.setRecurrenceUntil}}- @timezone={{@model.event.timezone}}+ </form.Collection>++ <DButton+ @disabled={{this.addReminderDisabled}}+ @icon="plus"+ @label="discourse_post_event.builder_modal.add_reminder"+ @action={{fn+ this.handleAddReminder+ form.addItemToCollection+ }}+ class="btn-default add-reminder"/>- </EventField>- {{/if}}+ </form.Container>- <EventField- class="minimal-event"- @label="discourse_post_event.builder_modal.minimal.label"- >- <label class="checkbox-label">- <input- type="checkbox"- checked={{@model.event.minimal}}- {{on "input" this.setMinimal}}- />- <span class="message">- {{i18n- "discourse_post_event.builder_modal.minimal.checkbox_label"- }}- </span>- </label>- </EventField>-- {{#if this.showChat}}- <EventField- class="allow-chat"- @label="discourse_post_event.builder_modal.allow_chat.label"+ <form.Field+ @name="recurrence"+ @title={{i18n+ "discourse_post_event.builder_modal.recurrence.label"+ }}+ @type="select"+ @format="full"+ @onSet={{this.handleRecurrenceChange}}+ as |field|>- <label class="checkbox-label">- <input- type="checkbox"- checked={{@model.event.chatEnabled}}- {{on "input" this.setChatEnabled}}+ <field.Control as |select|>+ {{#each this.availableRecurrences as |rec|}}+ <select.Option+ @value={{rec.id}}+ >{{rec.name}}</select.Option>+ {{/each}}+ </field.Control>+ </form.Field>++ {{#if @model.event.recurrence}}+ <form.Container+ @title={{i18n+ "discourse_post_event.builder_modal.recurrence_until.label"+ }}+ @format="full"+ class="recurrence-until"+ >+ <DDateInput+ @date={{this.recurrenceUntil}}+ @onChange={{this.setRecurrenceUntil}}+ @timezone={{@model.event.timezone}}/>- <span class="message">+ </form.Container>+ {{/if}}++ {{#if this.showChat}}+ <form.Field+ @name="chatEnabled"+ @title={{i18n+ "discourse_post_event.builder_modal.allow_chat.label"+ }}+ @type="checkbox"+ @format="full"+ @onSet={{fn this.syncFieldToEvent "chatEnabled"}}+ as |field|+ >+ <field.Control>{{i18n"discourse_post_event.builder_modal.allow_chat.checkbox_label"}}- </span>- </label>- </EventField>- {{/if}}-- {{#if this.allowedCustomFields.length}}- <EventField- @label="discourse_post_event.builder_modal.custom_fields.label"- >- <p class="event-field-description">- {{i18n+ </field.Control>+ </form.Field>+ {{/if}}++ {{#if this.allowedCustomFields.length}}+ <form.Container+ @title={{i18n+ "discourse_post_event.builder_modal.custom_fields.label"+ }}+ @subtitle={{i18n"discourse_post_event.builder_modal.custom_fields.description"}}- </p>- {{#each this.allowedCustomFields as |allowedCustomField|}}- <span class="label custom-field-label">- {{allowedCustomField}}- </span>- <input- type="text"- class="custom-field-input"- value={{get @model.event.customFields allowedCustomField}}- {{on "input" (fn this.setCustomField allowedCustomField)}}- placeholder={{i18n- "discourse_post_event.builder_modal.custom_fields.placeholder"- }}- />- {{/each}}- </EventField>- {{/if}}- </PluginOutlet>- </form>+ @format="full"+ >+ {{#each this.allowedCustomFields as |allowedCustomField|}}+ <span class="label custom-field-label">+ {{allowedCustomField}}+ </span>+ <input+ type="text"+ class="custom-field-input"+ value={{get+ @model.event.customFields+ allowedCustomField+ }}+ {{on+ "input"+ (fn this.setCustomField allowedCustomField)+ }}+ placeholder={{i18n+ "discourse_post_event.builder_modal.custom_fields.placeholder"+ }}+ />+ {{/each}}+ </form.Container>+ {{/if}}++ <form.Field+ @name="imageUpload"+ @title={{i18n+ "discourse_post_event.builder_modal.image.label"+ }}+ @type="image"+ @format="full"+ @onSet={{this.handleImageChange}}+ as |field|+ >+ <field.Control @type="event_image" />+ </form.Field>+ </PluginOutlet>+ </Form>+ {{else}}+ <div class="composer-event-node">+ <CompactEventEditor+ @initialState={{this.compactInitialState}}+ @urlTester={{this.urlTester}}+ @onChange={{this.onCompactChange}}+ @hideAdvanced={{true}}+ />+ </div>+ {{/if}}</DConditionalLoadingSection></:body><:footer>@@ -821,6 +1294,16 @@ export default class PostEventBuilder extends Component {@action={{this.createEvent}}/>{{/if}}++ {{#if this.showScreenToggle}}+ <DButton+ class="btn-default advanced-settings+ {{if this.isAdvancedScreen 'is-active'}}"+ @icon="gear"+ @label="discourse_post_event.builder_modal.advanced_settings"+ @action={{this.toggleAdvanced}}+ />+ {{/if}}</:footer></DModal></template>diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-event-ui-builder.js b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-event-ui-builder.jsindex fb1b338aeb5..926fa825677 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-event-ui-builder.js+++ b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-event-ui-builder.js@@ -1,21 +1,47 @@import { withPluginApi } from "discourse/lib/plugin-api";import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";import PostEventBuilder from "../components/modal/post-event-builder";+import { defaultReminderFor, reminderToBBCode } from "../lib/raw-event-helper";function initializeEventBuilder(api) {const currentUser = api.getCurrentUser();const modal = api.container.lookup("service:modal");+ const composer = api.container.lookup("service:composer");+ const siteSettings = api.container.lookup("service:site-settings");api.addComposerToolbarPopupMenuOption({action: (toolbarEvent) => {const userTz = currentUser?.user_option?.timezone;const timezone = userTz || moment.tz.guess();- const now = moment.tz(moment(), timezone);+ const start = moment+ .tz(moment(), timezone)+ .startOf("hour")+ .add(1, "hour");+ const end = start.clone().add(1, "hour");+ const reminder = defaultReminderFor({+ startsAt: start,+ endsAt: end,+ allDay: false,+ });++ // Insert inline whenever the user will see the editor immediately —+ // either the ProseMirror node view (rich-text) or the markdown preview+ // pane. Fall back to the modal when there's no visible surface (preview+ // toggled off, or mobile where it's behind a tap).+ const richTextMode =+ siteSettings.rich_editor && currentUser.useRichEditor;+ if (richTextMode || composer.isPreviewVisible) {+ const params = `start="${start.format("YYYY-MM-DD HH:mm")}" end="${end.format("YYYY-MM-DD HH:mm")}" status="public" timezone="${timezone}" reminders="${reminderToBBCode(reminder)}"`;+ toolbarEvent.addText(`[event ${params}]\n[/event]`);+ return;+ }const event = DiscoursePostEventEvent.create({status: "public",- starts_at: now,+ starts_at: start,+ ends_at: end,timezone,+ reminders: [reminder],});modal.show(PostEventBuilder, {@@ -25,12 +51,12 @@ function initializeEventBuilder(api) {group: "insertions",icon: "calendar-day",label: "discourse_post_event.builder_modal.attach",- condition: (composer) => {+ condition: (composerArg) => {if (!currentUser || !currentUser.can_create_discourse_post_event) {return false;}- const composerModel = composer.model;+ const composerModel = composerArg.model;return (composerModel &&!composerModel.replyingToTopic &&diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjsindex 9e6f3aca0a8..7a7db1d6ab5 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs@@ -1,54 +1,12 @@-import { isTesting } from "discourse/lib/environment";import { withPluginApi } from "discourse/lib/plugin-api";-import I18n, { i18n } from "discourse-i18n";+import { i18n } from "discourse-i18n";+import ComposerEventEditor from "discourse/plugins/discourse-calendar/discourse/components/composer-event-editor";import DiscoursePostEvent from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event";import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";-import guessDateFormat from "../lib/guess-best-date-format";--export function buildEventPreview(eventContainer) {- eventContainer.innerHTML = "";- eventContainer.classList.add("discourse-post-event-preview");-- const statusLocaleKey = `discourse_post_event.models.event.status.${- eventContainer.dataset.status || "public"- }.title`;- if (I18n.lookup(statusLocaleKey, { locale: "en" })) {- const statusContainer = document.createElement("div");- statusContainer.classList.add("event-preview-status");- statusContainer.innerText = i18n(statusLocaleKey);- eventContainer.appendChild(statusContainer);- }-- const datesContainer = document.createElement("div");- datesContainer.classList.add("event-preview-dates");-- const startsAt = moment.tz(- eventContainer.dataset.start,- eventContainer.dataset.timezone || "UTC"- );- const endsAt =- eventContainer.dataset.end &&- moment.tz(- eventContainer.dataset.end,- eventContainer.dataset.timezone || "UTC"- );-- const format = guessDateFormat(startsAt, endsAt);- const guessedTz = isTesting() ? "UTC" : moment.tz.guess();-- let datesString = `<span class='start'>${startsAt- .tz(guessedTz)- .format(format)}</span>`;- if (endsAt) {- datesString += ` → <span class='end'>${endsAt- .tz(guessedTz)- .format(format)}</span>`;- }- datesContainer.innerHTML = datesString;-- eventContainer.appendChild(datesContainer);-}+const ComposerEventEditorTemplate = <template>+ <ComposerEventEditor />+</template>;function _invalidEventPreview(eventContainer) {eventContainer.classList.add(@@ -62,15 +20,17 @@ function _invalidEventPreview(eventContainer) {);}-function _decorateEventPreview(api, cooked) {+function _decorateEventPreview(api, cooked, helper) {const eventContainers = cooked.querySelectorAll(".discourse-post-event");eventContainers.forEach((eventContainer, index) => {if (index > 0) {_invalidEventPreview(eventContainer);- } else {- buildEventPreview(eventContainer);+ return;}++ eventContainer.innerHTML = "";+ helper.renderGlimmer(eventContainer, ComposerEventEditorTemplate);});}@@ -78,7 +38,7 @@ function initializeDiscoursePostEventDecorator(api) {api.decorateCookedElement((cooked, helper) => {if (cooked.classList.contains("d-editor-preview")) {- _decorateEventPreview(api, cooked);+ _decorateEventPreview(api, cooked, helper);return;}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/event-preview.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/event-preview.jsnew file mode 100644index 00000000000..e6f170c2a47--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/event-preview.js@@ -0,0 +1,48 @@+import { isTesting } from "discourse/lib/environment";+import I18n, { i18n } from "discourse-i18n";+import guessDateFormat from "./guess-best-date-format";++export function buildEventPreview(eventContainer) {+ eventContainer.innerHTML = "";+ eventContainer.classList.add("discourse-post-event-preview");++ const statusLocaleKey = `discourse_post_event.models.event.status.${+ eventContainer.dataset.status || "public"+ }.title`;+ if (I18n.lookup(statusLocaleKey, { locale: "en" })) {+ const statusContainer = document.createElement("div");+ statusContainer.classList.add("event-preview-status");+ statusContainer.innerText = i18n(statusLocaleKey);+ eventContainer.appendChild(statusContainer);+ }++ const datesContainer = document.createElement("div");+ datesContainer.classList.add("event-preview-dates");++ const startsAt = moment.tz(+ eventContainer.dataset.start,+ eventContainer.dataset.timezone || "UTC"+ );++ const endsAt =+ eventContainer.dataset.end &&+ moment.tz(+ eventContainer.dataset.end,+ eventContainer.dataset.timezone || "UTC"+ );++ const format = guessDateFormat(startsAt, endsAt);+ const guessedTz = isTesting() ? "UTC" : moment.tz.guess();++ let datesString = `<span class='start'>${startsAt+ .tz(guessedTz)+ .format(format)}</span>`;+ if (endsAt) {+ datesString += ` → <span class='end'>${endsAt+ .tz(guessedTz)+ .format(format)}</span>`;+ }+ datesContainer.innerHTML = datesString;++ eventContainer.appendChild(datesContainer);+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.jsindex 58b11e5b1b9..a3c9e1373d9 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js@@ -1,3 +1,107 @@+export function defaultReminderFor({ startsAt, endsAt, allDay } = {}) {+ const start = startsAt ? moment(startsAt) : null;+ const end = endsAt ? moment(endsAt) : null;+ const isMultiDay = !!(start && end && !start.isSame(end, "day"));++ if (allDay || isMultiDay) {+ return { type: "notification", value: 1, unit: "days", period: "before" };+ }++ return { type: "notification", value: 15, unit: "minutes", period: "before" };+}++export function reminderToBBCode(reminder) {+ const raw = parseInt(reminder.value, 10);+ const magnitude = Math.abs(Number.isFinite(raw) ? raw : 0);+ const value = reminder.period === "after" ? -magnitude : magnitude;+ return `${reminder.type}.${value}.${reminder.unit}`;+}++function matchesDefault(reminder, def) {+ return (+ reminder &&+ reminder.value === def.value &&+ reminder.unit === def.unit &&+ reminder.period === def.period+ );+}++// compute the next state when transitioning between attendance modes+export function attendanceTransition({+ mode,+ status,+ maxAttendees,+ reminders,+ previousRsvpStatus,+ previousMaxAttendees,+}) {+ let nextStatus = status;+ let nextMax = maxAttendees;+ let nextReminders = reminders || [];+ let nextPrevRsvp = previousRsvpStatus;+ let nextPrevMax = previousMaxAttendees;++ if (mode === "none") {+ if (status && status !== "standalone") {+ nextPrevRsvp = status;+ }+ if (maxAttendees) {+ nextPrevMax = maxAttendees;+ }+ nextStatus = "standalone";+ nextMax = null;+ nextReminders = nextReminders.map((r) =>+ r.type === "notification" ? { ...r, type: "bumpTopic" } : r+ );+ } else {+ if (status === "standalone") {+ nextStatus = previousRsvpStatus || "public";+ nextReminders = nextReminders.map((r) =>+ r.type === "bumpTopic" ? { ...r, type: "notification" } : r+ );+ }+ if (mode === "unlimited") {+ if (maxAttendees) {+ nextPrevMax = maxAttendees;+ }+ nextMax = null;+ } else if (mode === "upTo") {+ nextMax = previousMaxAttendees || null;+ }+ }++ return {+ status: nextStatus,+ maxAttendees: nextMax,+ reminders: nextReminders,+ previousRsvpStatus: nextPrevRsvp,+ previousMaxAttendees: nextPrevMax,+ };+}++// if the default is unchanged, swap it out based on the new config+export function reconcileDefaultReminder(reminders, oldConfig, newConfig) {+ if (!reminders || reminders.length !== 1) {+ return reminders;+ }+ const oldDefault = defaultReminderFor(oldConfig);+ const newDefault = defaultReminderFor(newConfig);+ if (matchesDefault(oldDefault, newDefault)) {+ return reminders;+ }+ if (!matchesDefault(reminders[0], oldDefault)) {+ return reminders;+ }+ return [+ {+ ...reminders[0],+ value: newDefault.value,+ unit: newDefault.unit,+ period: newDefault.period,+ },+ ];+}+export function buildParams(startsAt, endsAt, event, siteSettings) {const params = {};@@ -113,31 +217,156 @@ export function buildParams(startsAt, endsAt, event, siteSettings) {return params;}-export function replaceRaw(params, raw) {- const eventRegex = /\[event (.*?)\](.*?)\[\/event\]/s;- const eventMatches = raw.match(eventRegex);+const EVENT_BBCODE_REGEX = /\[event (.*?)\](.*?)\[\/event\]/s;+const EVENT_BLOCK_REGEX = /\[event\b([^\]]*)\](.*?)\[\/event\]/s;+const ATTR_REGEX = /([-\w]+)=(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/g;- if (eventMatches && eventMatches[1]) {- const markdownParams = [];+function dashedToCamel(key) {+ return key.replace(/-([a-zA-Z0-9])/g, (_, c) => c.toUpperCase());+}- let description = params.description;- description = description ? `${description}\n` : "";- delete params.description;+export function parseEventBlock(raw) {+ if (!raw) {+ return null;+ }+ const match = raw.match(EVENT_BLOCK_REGEX);+ if (!match) {+ return null;+ }+ const attrs = {};+ for (const m of match[1].matchAll(ATTR_REGEX)) {+ const [, key, dq, sq, unq] = m;+ const value = dq ?? sq ?? unq ?? "";+ attrs[dashedToCamel(key)] = value;+ }+ const description = (match[2] || "").replace(/^\n/, "").replace(/\n$/, "");+ return { full: match[0], attrs, description };+}- Object.keys(params).forEach((param) => {- const value = params[param];- if (value != null && value !== "" && String(value).trim() !== "") {- markdownParams.push(`${param}="${value.replace(/"/g, "")}"`);- }- });+export function buildEventBlock(params, description) {+ const parts = Object.entries(params)+ .filter(([, v]) => v != null && v !== "" && String(v).trim() !== "")+ .map(([k, v]) => `${k}="${String(v).replace(/"/g, "")}"`);+ const desc = description ? `${description}\n` : "";+ return `[event ${parts.join(" ")}]\n${desc}[/event]`;+}- return raw.replace(- eventRegex,- `[event ${markdownParams.join(" ")}]\n${description}[/event]`- );+export function getCustomFieldNames(siteSettings) {+ return siteSettings.discourse_post_event_allowed_custom_fields+ .split("|")+ .filter(Boolean);+}++// anywhere that builds an event state should use this as the single source of truth for defaults+export function defaultEventState() {+ return {+ name: null,+ location: null,+ description: "",+ timezone: "UTC",+ status: "public",+ maxAttendees: null,+ allDay: false,+ startsAt: null,+ endsAt: null,+ reminders: [],+ recurrence: null,+ recurrenceUntil: null,+ showLocalTime: false,+ chatEnabled: false,+ minimal: false,+ url: null,+ image: null,+ allowedGroups: null,+ closed: false,+ customFields: {},+ };+}++export function parseEventAttrs(+ attrs,+ { fallbackTimezone, customFieldNames } = {}+) {+ const tz = attrs.timezone || fallbackTimezone || "UTC";+ const customFields = {};+ (customFieldNames || []).forEach((field) => {+ const param = camelCase(field);+ if (typeof attrs[param] !== "undefined") {+ customFields[field] = attrs[param];+ }+ });++ return {+ ...defaultEventState(),+ name: attrs.name || null,+ location: attrs.location || null,+ timezone: tz,+ status: attrs.status || "public",+ maxAttendees: attrs.maxAttendees ? parseInt(attrs.maxAttendees, 10) : null,+ allDay: attrs.allDay === "true",+ startsAt: attrs.start ? moment.tz(attrs.start, tz) : null,+ endsAt: attrs.end ? moment.tz(attrs.end, tz) : null,+ reminders: parseReminders(attrs.reminders),+ recurrence: attrs.recurrence || null,+ recurrenceUntil: attrs.recurrenceUntil || null,+ showLocalTime: attrs.showLocalTime === "true",+ chatEnabled: attrs.chatEnabled === "true",+ minimal: attrs.minimal === "true",+ url: attrs.url || null,+ image: attrs.image || null,+ allowedGroups: attrs.allowedGroups || null,+ closed: attrs.closed === "true",+ customFields,+ };+}++export function stateToEventInput(state) {+ return {+ timezone: state.timezone,+ allDay: state.allDay,+ isClosed: state.closed,+ status: state.status,+ name: state.name,+ location: state.location,+ url: state.url,+ recurrence: state.recurrence,+ recurrenceUntil: state.recurrenceUntil,+ showLocalTime: state.showLocalTime,+ minimal: state.minimal,+ chatEnabled: state.chatEnabled,+ maxAttendees: state.maxAttendees,+ rawInvitees: state.allowedGroups ? state.allowedGroups.split(",") : [],+ reminders: state.reminders,+ imageUpload: state.image ? { url: state.image } : null,+ customFields: state.customFields,+ };+}++export function parseReminders(reminders) {+ if (!reminders) {+ return [];+ }+ if (Array.isArray(reminders)) {+ return reminders;}+ return reminders.split(",").map((reminderStr) => {+ const [type, value, unit] = reminderStr.split(".");+ const numericValue = Math.abs(parseInt(value, 10));+ return {+ type: type || "notification",+ value: numericValue,+ unit: unit || "hours",+ period: parseInt(value, 10) < 0 ? "after" : "before",+ };+ });+}- return false;+export function replaceRaw(params, raw) {+ if (!EVENT_BBCODE_REGEX.test(raw)) {+ return false;+ }+ const { description, ...attrs } = params;+ return raw.replace(EVENT_BBCODE_REGEX, buildEventBlock(attrs, description));}export function camelCase(input) {diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.jsindex 9082a01eb4a..65aaa9497cb 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js+++ b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js@@ -2,7 +2,8 @@ import { camelize } from "@ember/string";import { withPluginApi } from "discourse/lib/plugin-api";import { buildBBCodeAttrs } from "discourse/lib/text";import EventNodeView from "../components/event-node-view";-import { buildEventPreview } from "../initializers/discourse-post-event-decorator";+import { buildEventPreview } from "../lib/event-preview";+import { defaultReminderFor, reminderToBBCode } from "../lib/raw-event-helper";export const EVENT_ATTRIBUTES = {name: { default: null },@@ -114,8 +115,17 @@ const extension = {if (userInput) {eventMarkdown = `[event ${userInput}]\n[/event]`;} else {- const now = moment.tz(moment(), timezone);- const defaults = `start="${now.format("YYYY-MM-DD HH:mm")}" status="public" timezone="${timezone}"`;+ const now = moment+ .tz(moment(), timezone)+ .startOf("hour")+ .add(1, "hour");+ const endsAt = now.clone().add(1, "hour");+ const reminder = defaultReminderFor({+ startsAt: now,+ endsAt,+ allDay: false,+ });+ const defaults = `start="${now.format("YYYY-MM-DD HH:mm")}" end="${endsAt.format("YYYY-MM-DD HH:mm")}" status="public" timezone="${timezone}" reminders="${reminderToBBCode(reminder)}"`;eventMarkdown = `[event ${defaults}]\n[/event]`;}diff --git a/plugins/discourse-calendar/assets/stylesheets/common/composer-event-node-view.scss b/plugins/discourse-calendar/assets/stylesheets/common/composer-event-node-view.scssindex 904454952c0..a0921462caa 100644--- a/plugins/discourse-calendar/assets/stylesheets/common/composer-event-node-view.scss+++ b/plugins/discourse-calendar/assets/stylesheets/common/composer-event-node-view.scss@@ -127,7 +127,8 @@.composer-event__dates,.composer-event__location,- .composer-event__attendees {+ .composer-event__attendees,+ .composer-event__reminder {position: relative;display: grid;grid-template-columns: 3em 1fr;@@ -139,27 +140,122 @@border-top: 1px solid var(--primary-low);}- > .d-icon {+ > .d-icon,+ > .composer-event__reminder-icon {color: var(--primary-high);margin: 0 auto;padding: 0;}}+ .composer-event__reminder {+ grid-template-columns: 3em auto auto 1fr;+ justify-items: start;++ .composer-event__reminder-icon .d-icon {+ color: var(--primary-high);+ }++ .composer-event__reminder-value {+ width: 4em;+ text-align: left;+ }++ .composer-event__reminder-unit {+ color: var(--primary-medium);+ line-height: var(--line-height-small);+ }+ }++ .composer-event__dates {+ .d-icon-clock {+ align-self: baseline;+ margin-top: var(--space-1);+ }+ }+.composer-event__description {display: grid;grid-template-columns: 1fr;}.composer-event__date-range {- display: flex;+ display: grid;+ grid-template-columns: 1fr;align-items: center;- flex-wrap: wrap;margin-right: calc(-1 * var(--space-6));gap: var(--space-half);+ width: 100%;- .composer-event__date-separator {- color: var(--primary-medium);+ &:not(.composer-event__date-range--has-time) {+ grid-template-columns: auto auto;++ @include viewport.until(sm) {+ .composer-event__date-arrow {+ display: none;+ }+ }++ @include viewport.from(sm) {+ grid-template-columns: auto auto 1fr;+ }+ }+ }++ .composer-event__all-day-toggle {+ display: flex;+ margin-bottom: var(--space-1);+ grid-column: 1 / -1;++ @include viewport.from(sm) {+ padding-left: 0.5em;+ }+ }++ .composer-event__date-row {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ min-width: 0;++ @include viewport.until(sm) {+ display: grid;+ grid-template-columns: 1fr auto 1fr;++ .composer-event__time-input {+ max-width: unset;+ }++ .composer-event__date-arrow {+ margin: 0 auto;+ }++ &:not(.--multi-day) {+ .composer-event__date-wrapper {+ grid-column: 1 / -1;+ }+ }++ &.--multi-day {+ grid-template-columns: 1fr 1fr;+ }+ }+ }++ .composer-event__date-arrow {+ color: var(--primary-low-mid);+ justify-self: start;+ margin-inline: var(--space-2);+ }++ .d-modal__body & {+ padding: 0;+ border: none;+ box-shadow: none;++ textarea,+ input {+ background: var(--primary-very-low);}}}@@ -182,6 +278,7 @@.composer-event__date-wrapper {position: relative;display: flex;+ min-width: 0;}.composer-event__date-display {@@ -199,32 +296,72 @@}}-.composer-event__date-input {+.composer-event__date-wrapper .composer-event__date-input {padding: var(--space-half) var(--space-1);- min-height: 2.25rem;+ height: 2.25rem;+ min-height: 2.5em; // avoids shift on focus in Chromecursor: pointer;color: transparent !important;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;flex: 1;- min-width: 0;- width: 9rem;+ width: 100%;++ @include viewport.from(sm) {+ min-width: 10em; // avoids shift on focus in webkit+ width: 9rem;+ }&:focus {+ color: inherit !important;+@include viewport.from(sm) {- color: inherit !important;width: auto;}}}-@include viewport.from(sm) {- .composer-event__date-input:focus + .composer-event__date-display {- display: none;+input.composer-event__time-input[type="time"] {+ padding-block: var(--space-2);+ cursor: pointer;+ flex: 1 1 auto;+ align-self: stretch;+ min-height: 2.5em;++ @include viewport.from(sm) {+ width: 6rem;}}+.composer-event__date-input,+.composer-event__time-input {+ appearance: none;+ display: inline-flex;+ align-items: center;+ line-height: normal;+}++// webkit needs special handling to center content vertically in date and time inputs+.composer-event__date-input::-webkit-datetime-edit,+.composer-event__time-input::-webkit-datetime-edit {+ display: flex;+ align-items: center;+ height: 100%;+ padding: 0;+}++.composer-event__date-input::-webkit-date-and-time-value,+.composer-event__time-input::-webkit-date-and-time-value {+ margin: auto 0;+ text-align: left;+ width: 100%;+}++.composer-event__date-input:focus + .composer-event__date-display {+ display: none;+}+.composer-event__location-input {width: 100%;cursor: text;diff --git a/plugins/discourse-calendar/assets/stylesheets/common/post-event-builder.scss b/plugins/discourse-calendar/assets/stylesheets/common/post-event-builder.scssindex 5f3a46bfd3e..1be5d490858 100644--- a/plugins/discourse-calendar/assets/stylesheets/common/post-event-builder.scss+++ b/plugins/discourse-calendar/assets/stylesheets/common/post-event-builder.scss@@ -1,143 +1,111 @@+@use "lib/viewport";+.post-event-builder-modal {- .conditional-loading-section {- background: transparent;+ [name="attendanceMode"] {+ .form-kit__control-radio-description {+ margin-top: var(--space-2);+ }}- .event-field {+ .reminder-item {display: flex;- margin-bottom: 2em;- flex-direction: column;+ gap: var(--space-half);- &.description {- textarea {- border-radius: var(--d-input-border-radius);- margin: 0;- }+ .form-kit__container {+ flex: 1 1 auto;}- &.name,- &.url {+ .d-select {+ text-overflow: ellipsis;+ }++ .form-kit__field-input-number {+ flex: 0;++ @include viewport.until(md) {+ min-width: 4em !important; // overrides another important+ }+input {- width: 100%;+ width: inherit;}}+ }- .event-field-description {- margin: 0 0 0.5em 0;+ .conditional-loading-section {+ background: transparent;+ }++ .d-modal__footer .advanced-settings {+ margin-left: auto;+ }++ .reminders {+ .form-kit__container-content {+ flex-wrap: wrap;}- .event-field-label {+ .reminder-item {display: flex;- min-height: 1px;- padding-top: 0;- top: 0;- vertical-align: middle;align-items: center;+ flex: 1 0 auto;+ padding: 0.25em 0;+ gap: var(--space-1);+ margin-bottom: var(--space-2);++ @include viewport.until(sm) {+ display: grid;+ grid-template-columns: 1fr 1fr;+ }- .label {- font-weight: 700;- margin-bottom: 0.5em;+ input {+ margin-bottom: 0;}- }- .event-field-control {- display: flex;- flex: 1;- flex-direction: column;+ .select-kit-header {+ height: 100%;+ }- .select-kit.available-recurrences {- width: 100%;+ .reminder-type {+ width: 320px;}- .custom-field-label {- font-weight: 500;- margin: 0.5em 0 0.25em 0;+ .reminder-value {+ width: 60px;}- .custom-field-input {- width: 100%;+ .reminder-unit {+ width: 140px;}- .radio-label,- .checkbox-label {+ .reminder-period {display: flex;align-items: center;- margin-bottom: 1em;-- &:last-child {- margin-bottom: 0;- }-- input[type="radio"] {- width: auto;- }-- .message {- margin: 0 0 0 1em;- padding: 0;- display: flex;- flex-direction: column;-- .description {- font-weight: normal;- }- }+ justify-content: space-between;+ gap: var(--space-2);}- .ac-wrap {- max-width: 100%;+ .remove-reminder {+ margin-left: auto;}+ }- input {- margin: 0;- }+ .form-kit__collection + .add-reminder {+ align-self: flex-start;+ margin-top: var(--form-kit-gutter-y);}}- .event-field.reminders {- display: flex;-- .reminders-list {- display: flex;- flex-direction: column;+ .custom-field-label {+ font-weight: 500;+ margin: 0.5em 0 0.25em 0;+ }- .reminder-item {- display: flex;- flex: 1 0 auto;- padding: 0.25em 0;- margin-bottom: var(--space-2);-- .select-kit-header {- height: 100%;- }-- .reminder-type {- width: 320px;- margin-right: 0.5em;- }-- .reminder-value {- width: 60px;- margin-right: 0.5em;- }-- .reminder-unit {- width: 140px;- margin-right: 0.5em;- }-- .reminder-period {- margin-right: 0.5em;- }-- .remove-reminder {- margin-left: auto;- }- }- }+ .custom-field-input {+ width: 100%;+ }- .add-reminder {- align-self: flex-start;- }+ .d-date-time-input {+ width: 100%;}}diff --git a/plugins/discourse-calendar/config/locales/client.en.yml b/plugins/discourse-calendar/config/locales/client.en.ymlindex aa82b01b5d4..513961a5700 100644--- a/plugins/discourse-calendar/config/locales/client.en.yml+++ b/plugins/discourse-calendar/config/locales/client.en.yml@@ -441,11 +441,35 @@ en:title: "Private"description: "A private event can only be joined by invited users."composer:- name_placeholder: "Event"- end_date_placeholder: "Set end date"+ name_placeholder: "Event name"+ end_date_placeholder: "End date"location_placeholder: "Add location or URL"- max_attendees_placeholder: "Set max attendees"+ max_attendees_placeholder: "Unlimited attendees"+ max_attendees_display:+ one: "Max %{count} attendee"+ other: "Max %{count} attendees"+ no_rsvps_label: "Not collecting attendance"description_placeholder: "Add event description"+ all_day: "All day"+ reminder:+ units:+ minutes:+ one: "minute"+ other: "minutes"+ hours:+ one: "hour"+ other: "hours"+ days:+ one: "day"+ other: "days"+ weeks:+ one: "week"+ other: "weeks"+ before: "%{unit} before"+ after: "%{unit} after"+ notification_title: "Notify attendees"+ bump_topic_title: "Auto-bump topic"+ remove: "Remove reminder"builder_modal:custom_fields:@@ -454,6 +478,8 @@ en:description: "Allowed custom fields are defined in site settings. Custom fields are used to transmit data to other plugins."create_event_title: "Create Event"update_event_title: "Edit Event"+ advanced_settings_title: "Advanced settings"+ advanced_settings: "Advanced settings"confirm_delete: "Are you sure you want to delete this event?"confirm_close: "Are you sure you want to close this event?"confirm_open: "Are you sure you want to open this event?"@@ -467,14 +493,18 @@ en:timezone:label: Timezoneremove_timezone: No timezone (UTC)+ starts_at:+ label: "Start date"+ ends_at:+ label: "End date"all_day:label: "All day event"description: "An all-day event will not have specific times, just a date. The event will run from the start of the day to the end of the day."reminders:label: "Reminders"types:- bump_topic: "auto-bump topic"- notification: "notify participants"+ bump_topic: "Auto-bump topic"+ notification: "Notify attendees"units:minutes: "minutes"hours: "hours"@@ -484,22 +514,30 @@ en:before: "before"after: "after"recurrence_until:- label: "Until (included)"+ label: "Until (includes this date)"recurrence:label: "Recurrence"none: "No recurrence"every_day: "Every day"- every_month: "Every month at this weekday"every_weekday: "Every weekday"- every_week: "Every week at this weekday"- every_two_weeks: "Every two weeks at this weekday"- every_four_weeks: "Every four weeks at this weekday"- minimal:- label: "Minimal event"- checkbox_label: "Hide Going/Not going buttons and invitees status"+ every_week: "Every %{weekday}"+ every_two_weeks: "Every other %{weekday}"+ every_four_weeks: "Every 4 weeks on %{weekday}"+ every_month: "The %{ordinal} %{weekday} of every month"+ ordinals:+ first: "first"+ second: "second"+ third: "third"+ fourth: "fourth"+ last: "last"max_attendees:label: "Maximum attendees"placeholder: "No limit"+ attendance:+ label: "How many members can RSVP to this event?"+ unlimited: "Unlimited"+ up_to: "Up to..."+ none: "None"allow_chat:label: "Chat integration"checkbox_label: "Create and manage event specific chat channel"@@ -517,8 +555,14 @@ en:placeholder: "Optional, defaults to topic title"invitees:label: "Invited groups"- status:- label: "Status"+ event_type:+ label: "Attendance type"+ public:+ title: "Public"+ description: "Anyone can attend."+ private:+ title: "Invite-only"+ description: "Only members of selected groups can attend."delete_confirmation_message: "Delete this event?"image:label: "Event image"diff --git a/plugins/discourse-calendar/lib/discourse_post_event/rrule_configurator.rb b/plugins/discourse-calendar/lib/discourse_post_event/rrule_configurator.rbindex ae5dfdd8f3f..b87d771e611 100644--- a/plugins/discourse-calendar/lib/discourse_post_event/rrule_configurator.rb+++ b/plugins/discourse-calendar/lib/discourse_post_event/rrule_configurator.rb@@ -17,7 +17,13 @@ class RRuleConfiguratorbreak if date.day == starts_at.dayend- "FREQ=MONTHLY;BYDAY=#{count}#{weekday.upcase[0, 2]}"+ # If this is the last occurrence of the weekday in the month, use -1+ # ("last") so the rule fires every month, including months where this+ # weekday only occurs four times.+ is_last = starts_at.day + 7 > starts_at.end_of_month.day+ byday_count = is_last ? -1 : count++ "FREQ=MONTHLY;BYDAY=#{byday_count}#{weekday.upcase[0, 2]}"when "every_weekday""FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"when "every_two_weeks"diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rbindex be31cc572d9..51a6cafe2c4 100644--- a/plugins/discourse-calendar/plugin.rb+++ b/plugins/discourse-calendar/plugin.rb@@ -39,6 +39,7 @@ register_svg_icon "file-csv"register_svg_icon "star"register_svg_icon "file-arrow-up"register_svg_icon "location-pin"+register_svg_icon "arrows-up-to-line"module ::DiscourseCalendarPLUGIN_NAME = "discourse-calendar"diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/rrule_configurator_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/rrule_configurator_spec.rbindex e2dc3d35dff..98d2fb9507a 100644--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/rrule_configurator_spec.rb+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/rrule_configurator_spec.rb@@ -26,10 +26,25 @@ describe RRuleConfigurator doexpect(rule).to eq("FREQ=MONTHLY;BYDAY=1MO")end- it "generates the correct rule for the last day of the month" do- last_day = Time.utc(2020, 8, 31, 16, 32) # Last day of August 2020+ it "uses BYDAY=-1 when the start is the fifth (and final) Monday of the month" do+ last_day = Time.utc(2020, 8, 31, 16, 32) # 5th and last Monday of August 2020rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: last_day)- expect(rule).to eq("FREQ=MONTHLY;BYDAY=5MO")+ expect(rule).to eq("FREQ=MONTHLY;BYDAY=-1MO")+ end++ it "uses BYDAY=-1 when the fourth occurrence is also the last in the month" do+ # September 2025 has only 4 Mondays (1, 8, 15, 22, 29 — 5 actually)+ # Use February 2026 instead: only 4 Mondays (2, 9, 16, 23)+ last_monday = Time.utc(2026, 2, 23, 12, 0)+ rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: last_monday)+ expect(rule).to eq("FREQ=MONTHLY;BYDAY=-1MO")+ end++ it "uses BYDAY=4 when there is also a fifth occurrence in the month" do+ # March 2027: 1, 8, 15, 22, 29 — 5 Mondays. The 4th Monday is Mar 22.+ fourth_monday = Time.utc(2027, 3, 22, 12, 0)+ rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: fourth_monday)+ expect(rule).to eq("FREQ=MONTHLY;BYDAY=4MO")endenddiff --git a/plugins/discourse-calendar/spec/system/composer/prosemirror_event_spec.rb b/plugins/discourse-calendar/spec/system/composer/prosemirror_event_spec.rbindex dd599e2db45..cce202f4c3d 100644--- a/plugins/discourse-calendar/spec/system/composer/prosemirror_event_spec.rb+++ b/plugins/discourse-calendar/spec/system/composer/prosemirror_event_spec.rb@@ -35,7 +35,7 @@ describe "Composer - ProseMirror - Event Editor" doexpect(rich).to have_css(".composer-event__month", text: "DEC")expect(rich).to have_css(".composer-event__day", text: "20")- expect(rich).to have_css(".composer-event__date-range--has-values")+ expect(rich).to have_css(".composer-event__date-input")endend@@ -81,10 +81,9 @@ describe "Composer - ProseMirror - Event Editor" doexpect(rich).to have_css(".composer-event__location-external-link")# Verify date inputs have values- start_input = rich.find("input[type='datetime-local']", match: :first)- end_input = rich.all("input[type='datetime-local']").last- expect(start_input.value).not_to be_empty- expect(end_input.value).not_to be_empty+ date_inputs = rich.all(".composer-event__date-input")+ expect(date_inputs.first.value).not_to be_empty+ expect(date_inputs.last.value).not_to be_emptyendit "allows editing name field and persists to markdown" do@@ -155,13 +154,12 @@ describe "Composer - ProseMirror - Event Editor" do)composer.toggle_rich_editor- start_input = rich.find("input[type='datetime-local']", match: :first)- start_input.fill_in(with: "2024-12-20T14:00")-- end_input = rich.all("input[type='datetime-local']").last- end_input.fill_in(with: "2024-12-20T16:00")-- expect(rich).to have_css(".composer-event__date-range--has-values")+ date_inputs = rich.all(".composer-event__date-input")+ time_inputs = rich.all(".composer-event__time-input")+ date_inputs.first.fill_in(with: "2024-12-20")+ time_inputs.first.fill_in(with: "14:00")+ date_inputs.last.fill_in(with: "2024-12-20")+ time_inputs.last.fill_in(with: "16:00")composer.toggle_rich_editormarkdown_content = find(".d-editor-input").value@@ -185,12 +183,17 @@ describe "Composer - ProseMirror - Event Editor" domax_attendees_input.fill_in(with: "25")expect(max_attendees_input.value).to eq("25")- # Invalid input gets cleared+ # Negative input gets clearedmax_attendees_input.fill_in(with: "-10")expect(max_attendees_input.value).to eq("")+ # Typing 0 disables attendancemax_attendees_input.fill_in(with: "0")- expect(max_attendees_input.value).to eq("")+ max_attendees_input.send_keys(:tab)+ expect(rich).to have_css(+ ".composer-event__max-attendees-display",+ text: I18n.t("js.discourse_post_event.composer.no_rsvps_label"),+ )endit "requires start date for event rendering" dodiff --git a/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/post_event_form.rb b/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/post_event_form.rbindex a3cf134ad61..4ab1e747ec1 100644--- a/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/post_event_form.rb+++ b/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/post_event_form.rb@@ -7,16 +7,17 @@ module PageObjectsMODAL_SELECTOR = ".post-event-builder-modal"def fill_location(with)- form.find(".event-field.location input").fill_in(with:)+ modal.find(".composer-event__location-input").fill_in(with:)selfenddef fill_description(with)- form.find(".event-field.description textarea").fill_in(with:)+ modal.find(".composer-event__description-textarea").fill_in(with:)selfenddef fill_timezone(with)+ open_advancedfilter =PageObjects::Components::SelectKit.new(".post-event-builder-modal .timezone-input")filter.search(with)@@ -24,6 +25,13 @@ module PageObjectsselfend+ def open_advanced+ if modal.has_css?(".d-modal__footer .advanced-settings", wait: 0)+ modal.find(".d-modal__footer .advanced-settings").click+ end+ self+ end+def formmodal.find("form")enddiff --git a/plugins/discourse-calendar/spec/system/post_event_spec.rb b/plugins/discourse-calendar/spec/system/post_event_spec.rbindex de2b5e99092..43d19be4f07 100644--- a/plugins/discourse-calendar/spec/system/post_event_spec.rb+++ b/plugins/discourse-calendar/spec/system/post_event_spec.rb@@ -76,10 +76,14 @@ describe "Post event" dovisit("/new-topic")find(".toolbar-menu__options-trigger").clickclick_button(I18n.t("js.discourse_post_event.builder_modal.attach"))- post_event_form_page.fill_description("foo\nbar").fill_timezone(timezone).submit++ # Toolbar inserts inline; fill the description in the preview editor and+ # focus out to flush back to raw.+ composer.preview.find(".composer-event__description-textarea").fill_in(with: "foo\nbar")+ find(".d-editor-input").clickexpect(composer).to have_value <<~EVENT.strip- [event start="2025-06-15 14:30" status="public" timezone="#{timezone}"]+ [event start="2025-06-15 15:00" status="public" timezone="#{timezone}" end="2025-06-15 16:00" reminders="notification.15.minutes"]foobar[/event]@@ -87,6 +91,59 @@ describe "Post event" doendend+ context "with markdown-mode preview" do+ it "inserts BBCode inline and renders the compact editor in the preview pane pre-populated" do+ visit("/new-topic")+ find(".toolbar-menu__options-trigger").click+ click_button(I18n.t("js.discourse_post_event.builder_modal.attach"))++ preview = composer.preview+ expect(preview).to have_css(".composer-event-node")+ expect(preview.find(".composer-event__date-input", match: :first).value).not_to(+ be_empty,+ "start date should be populated from the inserted BBCode",+ )+ expect(composer).to have_value(/\[event /)+ end++ it "preserves a multi-day end date when toggling all-day on" do+ visit("/new-topic")+ composer.fill_title("Multi-day all-day toggle")+ composer.fill_content <<~MD+ [event start='2024-06-01 10:00' end='2024-06-03 12:00' timezone='UTC' status='public']+ [/event]+ MD++ preview = composer.preview+ expect(preview).to have_css(".composer-event-node")++ preview.find(".composer-event__all-day-toggle .d-toggle-switch__label").click+ find(".d-editor-input").click++ expect(composer).to have_value(/start="2024-06-01"/)+ expect(composer).to have_value(/end="2024-06-03"/)+ end++ context "when showLocalTime is set and the event crosses midnight relative to the viewer",+ timezone: "Australia/Brisbane" do+ it "renders the preview badge in the event timezone, not the viewer's" do+ # 2025-09-07 22:30 Europe/Paris == 2025-09-08 06:30 Australia/Brisbane,+ # so without showLocalTime the viewer would see "Sep 8" in the badge.+ # With showLocalTime, the preview must stay anchored to the event timezone.+ visit("/new-topic")+ composer.fill_title("Local time preview test")+ composer.fill_content <<~MD+ [event start='2025-09-07 22:30' timezone='Europe/Paris' showLocalTime='true' status='public']+ [/event]+ MD++ preview = composer.preview+ expect(preview).to have_css(".composer-event__month", text: "SEP")+ expect(preview).to have_css(".composer-event__day", text: "7")+ end+ end+ end+context "with max attendees" doit "updates the going button label from Full after toggling" dogoing = I18n.t("js.discourse_post_event.models.invitee.status.going")@@ -116,6 +173,9 @@ describe "Post event" dofind(".toolbar-menu__options-trigger").clickclick_button(I18n.t("js.discourse_post_event.builder_modal.attach"))+ # Toolbar inserts inline; click gear to open the modal on advanced.+ find(".d-editor-preview .composer-event__more-dropdown button").click+tz_select =PageObjects::Components::SelectKit.new(".post-event-builder-modal .timezone-input")@@ -386,14 +446,17 @@ describe "Post event" docomposer.fill_title("Test event with updates")find(".toolbar-menu__options-trigger").clickfind("button[title='#{I18n.t("js.discourse_post_event.builder_modal.attach")}']").click- find(".d-modal input[name=status][value=private]").click++ # Toolbar inserts inline; click gear to open the modal on advanced.+ find(".d-editor-preview .composer-event__more-dropdown button").click++ form = PageObjects::Components::FormKit.new(".d-modal form")+ form.field("eventType").select("private")find(".group-selector").clickfind(".d-multi-select__search-input").send_keys(group.name)find(".d-multi-select__result", text: group.name).clickfind(".d-modal .custom-field-input").fill_in(with: "custom value")- dropdown = PageObjects::Components::SelectKit.new(".available-recurrences")- dropdown.expand- dropdown.select_row_by_value("every_day")+ form.field("recurrence").select("every_day")find(".d-modal .recurrence-until .date-picker").fill_in(with: "#{1.year.from_now.year}-12-30")find(".d-modal .btn-primary").clickcomposer.submit@@ -401,8 +464,10 @@ describe "Post event" doexpect(page).to have_css(".discourse-post-event")post_event_page.edit+ find(".d-modal .d-modal__footer .advanced-settings").click- expect(find(".d-modal input[name=status][value=private]").checked?).to eq(true)+ form = PageObjects::Components::FormKit.new(".d-modal form")+ expect(form.field("eventType")).to have_value("private")expect(find(".group-selector .d-multi-select-trigger__selection")).to have_text(group.name)expect(find(".d-modal .custom-field-input").value).to eq("custom value")expect(page).to have_selector(".d-modal .recurrence-until .date-picker") do |input|diff --git a/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js b/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.jsindex 7bb93051ec2..e175db838f1 100644--- a/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js+++ b/plugins/discourse-calendar/test/javascripts/acceptance/post-event-builder-test.js@@ -26,10 +26,14 @@ acceptance("Post event - composer", function (needs) {`button[title='${i18n("discourse_post_event.builder_modal.attach")}']`);+ // Toolbar inserts inline when the preview is visible; click the gear to+ // open the modal on the advanced screen.+ await click(".d-editor-preview .composer-event__more-dropdown button");+const modal = ".post-event-builder-modal";const timezoneInput = selectKit(- `${modal} .event-field.timezone .timezone-input`+ `${modal} [data-name="timezone"] .timezone-input`);await timezoneInput.expand();await timezoneInput.selectRowByValue("Europe/London");@@ -43,29 +47,53 @@ acceptance("Post event - composer", function (needs) {const fromTime = selectKit(`${modal} .from .d-time-input .select-kit`);await fromTime.expand();- await fromTime.selectRowByName("12:00");+ await fromTime.selectRowByName("12:00 PM");await fillIn(`${modal} .to input[type=date]`, "2022-07-01");const toTime = selectKit(`${modal} .to .d-time-input .select-kit`);await toTime.expand();- await toTime.selectRowByName("13:00");+ await toTime.selectRowByName("1:00 PM");await timezoneInput.expand();await timezoneInput.selectRowByName("Europe/Paris");- assert.strictEqual(fromTime.header().name(), "12:00");- assert.strictEqual(toTime.header().name(), "13:00");+ assert.strictEqual(fromTime.header().name(), "12:00 PM");+ assert.strictEqual(toTime.header().name(), "1:00 PM");await click(`${modal} .d-modal__footer .btn-primary`);assert.dom(".d-editor-input").hasValue(- `[event start="2022-07-01 12:00" status="public" timezone="Europe/Paris" end="2022-07-01 13:00"]\n[/event]`,+ `[event start="2022-07-01 12:00" status="public" timezone="Europe/Paris" end="2022-07-01 13:00" reminders="notification.15.minutes"]\n[/event]`,"bbcode is correct");});+ test("composer event builder - inline preview pre-populates defaults", async function (assert) {+ await visit("/");+ await click("#create-topic");+ const categoryChooser = selectKit(".category-chooser");+ await categoryChooser.expand();+ await categoryChooser.selectRowByValue(2);+ await click(".toolbar-menu__options-trigger");+ await click(+ `button[title='${i18n("discourse_post_event.builder_modal.attach")}']`+ );++ const preview = ".d-editor-preview";++ assert+ .dom(`${preview} input.composer-event__date-input`)+ .hasAnyValue("start date is pre-populated in the inline preview editor");+ assert+ .dom(`${preview} input.composer-event__time-input`)+ .hasAnyValue("start time is pre-populated");+ assert+ .dom(`${preview} .composer-event__reminder-value`)+ .hasAnyValue("default reminder is pre-populated");+ });+test("composer event builder - the timezone case", async function (assert) {await visit("/");@@ -94,6 +122,9 @@ acceptance("Post event - composer", function (needs) {`button[title='${i18n("discourse_post_event.builder_modal.attach")}']`);+ // Toolbar inserts inline; click gear to open the modal on advanced.+ await click(".d-editor-preview .composer-event__more-dropdown button");+const modal = ".post-event-builder-modal";// Select the date@@ -101,7 +132,7 @@ acceptance("Post event - composer", function (needs) {// Select the timezoneconst timezoneInput = selectKit(- `${modal} .event-field.timezone .timezone-input`+ `${modal} [data-name="timezone"] .timezone-input`);await timezoneInput.expand();await timezoneInput.selectRowByValue("Europe/London");diff --git a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.jsindex f80a65cf60f..ab05dc1c0dc 100644--- a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js+++ b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js@@ -1,10 +1,40 @@import { module, test } from "qunit";import {+ attendanceTransition,+ buildEventBlock,buildParams,+ defaultReminderFor,+ parseEventBlock,+ parseReminders,+ reconcileDefaultReminder,+ reminderToBBCode,removeEvent,replaceRaw,} from "discourse/plugins/discourse-calendar/discourse/lib/raw-event-helper";+const SAME_DAY_CONFIG = {+ startsAt: "2024-06-15T10:00:00Z",+ endsAt: "2024-06-15T11:00:00Z",+ allDay: false,+};+const ALL_DAY_CONFIG = {+ startsAt: "2024-06-15",+ endsAt: null,+ allDay: true,+};+const SHORT_DEFAULT = {+ type: "notification",+ value: 15,+ unit: "minutes",+ period: "before",+};+const LONG_DEFAULT = {+ type: "notification",+ value: 1,+ unit: "days",+ period: "before",+};+module("Unit | Lib | raw-event-helper", function () {test("removeEvent", function (assert) {assert.strictEqual(@@ -77,6 +107,307 @@ module("Unit | Lib | raw-event-helper", function () {);});+ test("parseEventBlock extracts attrs and description, buildEventBlock round-trips", function (assert) {+ const raw =+ 'preface\n[event start="2024-06-15 10:00" name="Demo"]\nbody line\n[/event]\ntail';+ const parsed = parseEventBlock(raw);++ assert.deepEqual(parsed.attrs, { start: "2024-06-15 10:00", name: "Demo" });+ assert.strictEqual(parsed.description, "body line");+ assert.strictEqual(+ parsed.full,+ '[event start="2024-06-15 10:00" name="Demo"]\nbody line\n[/event]'+ );++ assert.strictEqual(+ buildEventBlock(parsed.attrs, parsed.description),+ parsed.full,+ "buildEventBlock round-trips parsed values"+ );+ });++ test("parseEventBlock returns null when no event tag", function (assert) {+ assert.strictEqual(parseEventBlock("no event here"), null);+ assert.strictEqual(parseEventBlock(""), null);+ assert.strictEqual(parseEventBlock(null), null);+ });++ test("parseEventBlock accepts single-quoted attr values", function (assert) {+ const parsed = parseEventBlock(+ "[event start='2222-02-22 14:22' timezone='Australia/Sydney']\n[/event]"+ );+ assert.deepEqual(parsed.attrs, {+ start: "2222-02-22 14:22",+ timezone: "Australia/Sydney",+ });+ });++ test("parseEventBlock accepts unquoted attr values", function (assert) {+ const parsed = parseEventBlock(+ "[event start=2024-06-15 status=public timezone=Europe/Paris]\n[/event]"+ );+ assert.deepEqual(parsed.attrs, {+ start: "2024-06-15",+ status: "public",+ timezone: "Europe/Paris",+ });+ });++ test("parseEventBlock normalizes dashed keys to camelCase", function (assert) {+ const parsed = parseEventBlock(+ '[event start="2024-06-15 10:00" max-attendees="5" recurrence-until="2024-07-15" show-local-time="true"]\n[/event]'+ );+ assert.deepEqual(parsed.attrs, {+ start: "2024-06-15 10:00",+ maxAttendees: "5",+ recurrenceUntil: "2024-07-15",+ showLocalTime: "true",+ });+ });++ test("parseEventBlock accepts mixed quote forms in one tag", function (assert) {+ const parsed = parseEventBlock(+ `[event start="2024-06-15 10:00" status=public timezone='Europe/Paris' max-attendees=10]\nfine\n[/event]`+ );+ assert.deepEqual(parsed.attrs, {+ start: "2024-06-15 10:00",+ status: "public",+ timezone: "Europe/Paris",+ maxAttendees: "10",+ });+ assert.strictEqual(parsed.description, "fine");+ });++ test("parseReminders converts comma-separated BBCode into reminder objects", function (assert) {+ assert.deepEqual(parseReminders(""), []);+ assert.deepEqual(parseReminders(null), []);+ assert.deepEqual(+ parseReminders("notification.15.minutes,bumpTopic.-1.hours"),+ [+ { type: "notification", value: 15, unit: "minutes", period: "before" },+ { type: "bumpTopic", value: 1, unit: "hours", period: "after" },+ ]+ );+ });++ test("defaultReminderFor", function (assert) {+ assert.deepEqual(+ defaultReminderFor({+ startsAt: "2024-06-15T10:00:00Z",+ endsAt: "2024-06-15T11:00:00Z",+ allDay: false,+ }),+ { type: "notification", value: 15, unit: "minutes", period: "before" },+ "uses 15-minute reminder for same-day timed events"+ );++ assert.deepEqual(+ defaultReminderFor({+ startsAt: "2024-06-15T10:00:00Z",+ endsAt: "2024-06-16T10:00:00Z",+ allDay: false,+ }),+ { type: "notification", value: 1, unit: "days", period: "before" },+ "uses 1-day reminder for multi-day events"+ );++ assert.deepEqual(+ defaultReminderFor({+ startsAt: "2024-06-15",+ endsAt: null,+ allDay: true,+ }),+ { type: "notification", value: 1, unit: "days", period: "before" },+ "uses 1-day reminder for all-day events"+ );+ });++ test("reconcileDefaultReminder", function (assert) {+ assert.deepEqual(+ reconcileDefaultReminder([], SAME_DAY_CONFIG, ALL_DAY_CONFIG),+ [],+ "empty reminders pass through unchanged"+ );++ const multiple = [+ SHORT_DEFAULT,+ { type: "bumpTopic", value: 1, unit: "hours", period: "before" },+ ];+ assert.strictEqual(+ reconcileDefaultReminder(multiple, SAME_DAY_CONFIG, ALL_DAY_CONFIG),+ multiple,+ "multi-reminder arrays are left alone"+ );++ const customized = [+ { type: "notification", value: 30, unit: "minutes", period: "before" },+ ];+ assert.strictEqual(+ reconcileDefaultReminder(customized, SAME_DAY_CONFIG, ALL_DAY_CONFIG),+ customized,+ "user-customized reminder is preserved"+ );++ const otherSameDay = {+ startsAt: "2024-07-20T14:00:00Z",+ endsAt: "2024-07-20T15:00:00Z",+ allDay: false,+ };+ const reminders = [{ ...SHORT_DEFAULT }];+ assert.strictEqual(+ reconcileDefaultReminder(reminders, SAME_DAY_CONFIG, otherSameDay),+ reminders,+ "no swap when both configs share the same default"+ );++ assert.deepEqual(+ reconcileDefaultReminder(+ [{ ...SHORT_DEFAULT }],+ SAME_DAY_CONFIG,+ ALL_DAY_CONFIG+ ),+ [LONG_DEFAULT],+ "swaps short default for long default when going to all-day"+ );++ assert.deepEqual(+ reconcileDefaultReminder(+ [{ ...LONG_DEFAULT }],+ ALL_DAY_CONFIG,+ SAME_DAY_CONFIG+ ),+ [SHORT_DEFAULT],+ "swaps long default for short default when going to same-day timed"+ );++ assert.deepEqual(+ reconcileDefaultReminder(+ [{ ...SHORT_DEFAULT, type: "bumpTopic" }],+ SAME_DAY_CONFIG,+ ALL_DAY_CONFIG+ ),+ [{ ...LONG_DEFAULT, type: "bumpTopic" }],+ "preserves the original type when swapping default"+ );+ });++ test("reminderToBBCode", function (assert) {+ assert.strictEqual(+ reminderToBBCode({+ type: "notification",+ value: 15,+ unit: "minutes",+ period: "before",+ }),+ "notification.15.minutes",+ "serializes a before reminder"+ );++ assert.strictEqual(+ reminderToBBCode({+ type: "bumpTopic",+ value: 30,+ unit: "minutes",+ period: "after",+ }),+ "bumpTopic.-30.minutes",+ "serializes an after reminder with negative value"+ );+ });++ test("attendanceTransition: none captures status + max and flips notifications to bumpTopic", function (assert) {+ const result = attendanceTransition({+ mode: "none",+ status: "private",+ maxAttendees: 50,+ reminders: [+ { type: "notification", value: 15, unit: "minutes", period: "before" },+ ],+ previousRsvpStatus: "public",+ previousMaxAttendees: null,+ });++ assert.strictEqual(result.status, "standalone");+ assert.strictEqual(result.maxAttendees, null);+ assert.strictEqual(result.reminders[0].type, "bumpTopic");+ assert.strictEqual(result.previousRsvpStatus, "private");+ assert.strictEqual(result.previousMaxAttendees, 50);+ });++ test("attendanceTransition: switching from none to unlimited restores prior status and flips reminders", function (assert) {+ const result = attendanceTransition({+ mode: "unlimited",+ status: "standalone",+ maxAttendees: null,+ reminders: [+ { type: "bumpTopic", value: 15, unit: "minutes", period: "before" },+ ],+ previousRsvpStatus: "private",+ previousMaxAttendees: 50,+ });++ assert.strictEqual(result.status, "private");+ assert.strictEqual(result.maxAttendees, null);+ assert.strictEqual(result.reminders[0].type, "notification");+ });++ test("attendanceTransition: upTo restores previousMaxAttendees", function (assert) {+ const result = attendanceTransition({+ mode: "upTo",+ status: "standalone",+ maxAttendees: null,+ reminders: [],+ previousRsvpStatus: "public",+ previousMaxAttendees: 25,+ });++ assert.strictEqual(result.status, "public");+ assert.strictEqual(result.maxAttendees, 25);+ });++ test("attendanceTransition: upTo with no previous yields null max", function (assert) {+ const result = attendanceTransition({+ mode: "upTo",+ status: "public",+ maxAttendees: null,+ reminders: [],+ previousRsvpStatus: "public",+ previousMaxAttendees: null,+ });++ assert.strictEqual(result.maxAttendees, null);+ assert.strictEqual(result.status, "public");+ });++ test("attendanceTransition: unlimited from upTo captures the current max", function (assert) {+ const result = attendanceTransition({+ mode: "unlimited",+ status: "public",+ maxAttendees: 25,+ reminders: [],+ previousRsvpStatus: "public",+ previousMaxAttendees: null,+ });++ assert.strictEqual(result.maxAttendees, null);+ assert.strictEqual(result.previousMaxAttendees, 25);+ });++ test("attendanceTransition: does not mutate the input reminders array", function (assert) {+ const reminders = [+ { type: "notification", value: 15, unit: "minutes", period: "before" },+ ];+ attendanceTransition({+ mode: "none",+ status: "public",+ maxAttendees: null,+ reminders,+ previousRsvpStatus: "public",+ previousMaxAttendees: null,+ });+ assert.strictEqual(reminders[0].type, "notification");+ });+test("buildParams image handling", function (assert) {const startsAt = "2024-06-15T10:00:00Z";const siteSettings = { discourse_post_event_allowed_custom_fields: "" };diff --git a/spec/system/page_objects/components/form_kit.rb b/spec/system/page_objects/components/form_kit.rbindex aa420c6e0fa..07685ba27ce 100644--- a/spec/system/page_objects/components/form_kit.rb+++ b/spec/system/page_objects/components/form_kit.rb@@ -49,6 +49,8 @@ module PageObjectscomponent.find(".fk-d-menu__trigger")["data-value"]when "select"PageObjects::Components::DSelect.new(component.find("select")).value+ when "radio-group"+ component.find("input[type='radio']:checked", visible: :all).valuewhen "composer", "textarea"component.find("textarea").valuewhen "image"