A platform for community discussion. Free, open, simple.
FEATURE: Allow editing `[date]` and `[date-range]` in the rich editor (#43049)
Renato Atilioe44970f22f53
diff --git a/frontend/discourse/app/ui-kit/d-calendar-date-time-input.gjs b/frontend/discourse/app/ui-kit/d-calendar-date-time-input.gjsindex c683020d73b..a38431ab27d 100644--- a/frontend/discourse/app/ui-kit/d-calendar-date-time-input.gjs+++ b/frontend/discourse/app/ui-kit/d-calendar-date-time-input.gjs@@ -28,7 +28,16 @@ export default class DCalendarDateTimeInput extends Component {@actionsetupPikaday(element) {this.#setupPicker(element).then((picker) => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }+this._picker = picker;++ // didUpdate only fires on later changes, so seed the initial @date here+ if (this.args.date) {+ this.changeDate();+ }});}diff --git a/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs b/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjsindex 53501e27e63..918982cdc8c 100644--- a/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs+++ b/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs@@ -41,6 +41,8 @@ export default class LocalDatesCreate extends Component {timezone = null;fromSelected = null;toSelected = null;+ countdown = null;+ displayedTimezone = null;init() {super.init(...arguments);@@ -55,6 +57,25 @@ export default class LocalDatesCreate extends Component {timezone: this.currentUserTimezone,date: moment().format(this.dateFormat),});++ const { initialValues } = this.model;++ if (initialValues) {+ this.setProperties(initialValues);+ // open the advanced pane when the date carries an option only editable there+ this.set(+ "advancedMode",+ !!(+ initialValues.format ||+ initialValues.recurring ||+ initialValues.timezones?.length+ )+ );+ }+ }++ get isEditing() {+ return !!this.model.initialValues;}@computed("date")@@ -197,13 +218,23 @@ export default class LocalDatesCreate extends Component {});}- @computed("recurring", "timezones", "timezone", "format")+ @computed(+ "recurring",+ "timezones",+ "timezone",+ "format",+ "countdown",+ "displayedTimezone"+ )get options() {return EmberObject.create({recurring: this.recurring,timezones: this.timezones,timezone: this.timezone,format: this.format,+ // no UI of their own: carried through so editing a date keeps them+ countdown: this.countdown,+ displayedTimezone: this.displayedTimezone,});}@@ -410,7 +441,11 @@ export default class LocalDatesCreate extends Component {<template><DModal- @title={{i18n "discourse_local_dates.title"}}+ @title={{if+ this.isEditing+ (i18n "discourse_local_dates.edit")+ (i18n "discourse_local_dates.title")+ }}@closeModal={{@closeModal}}class="discourse-local-dates-create-modal --large">@@ -596,7 +631,11 @@ export default class LocalDatesCreate extends Component {{{#if this.isValid}}<DButton@action={{this.save}}- @label="discourse_local_dates.create.form.insert"+ @label={{if+ this.isEditing+ "discourse_local_dates.create.form.save"+ "discourse_local_dates.create.form.insert"+ }}class="btn-primary"/>{{/if}}diff --git a/plugins/discourse-local-dates/assets/javascripts/lib/local-date-node-view.js b/plugins/discourse-local-dates/assets/javascripts/lib/local-date-node-view.jsnew file mode 100644index 00000000000..40ecebe86af--- /dev/null+++ b/plugins/discourse-local-dates/assets/javascripts/lib/local-date-node-view.js@@ -0,0 +1,218 @@+import { iconHTML } from "discourse/lib/icon-library";+import { i18n } from "discourse-i18n";+import LocalDatesCreateModal from "../discourse/components/modal/local-dates-create";++const DATE_NODE_TYPES = ["local_date", "local_date_range"];+const EDIT_BUTTON_CLASS = "composer-local-date__edit-button";++function nodeToInitialValues(node) {+ const attrs = node.attrs;+ const isRange = node.type.name === "local_date_range";++ return {+ date: isRange ? attrs.fromDate : attrs.date,+ time: isRange ? attrs.fromTime : attrs.time,+ toDate: isRange ? attrs.toDate : null,+ toTime: isRange ? attrs.toTime : null,+ timezone: attrs.timezone,+ format: attrs.format,+ timezones: attrs.timezones ? attrs.timezones.split("|") : [],+ recurring: isRange ? null : attrs.recurring,+ countdown: attrs.countdown,+ displayedTimezone: attrs.displayedTimezone,+ };+}++class LocalDateNodeView {+ dom;++ #node;+ #view;+ #getPos;+ #getContext;+ #convertFromMarkdown;+ #NodeSelection;+ #DOMSerializer;+ #editButton;++ #returnFocusToEditor = (event) => {+ if (event.key !== "Tab") {+ return;+ }++ event.preventDefault();+ this.#view.focus();+ };++ #openEditModal = (event) => {+ event.preventDefault();+ event.stopPropagation();++ const { modal } = this.#getContext();+ modal.show(LocalDatesCreateModal, {+ model: {+ initialValues: nodeToInitialValues(this.#node),+ insertDate: (markup) => this.#applyEdit(markup),+ },+ });+ };++ constructor({+ node,+ view,+ getPos,+ getContext,+ convertFromMarkdown,+ NodeSelection,+ DOMSerializer,+ }) {+ this.#node = node;+ this.#view = view;+ this.#getPos = getPos;+ this.#getContext = getContext;+ this.#convertFromMarkdown = convertFromMarkdown;+ this.#NodeSelection = NodeSelection;+ this.#DOMSerializer = DOMSerializer;++ this.dom = document.createElement("span");+ this.dom.classList.add("composer-local-date");+ this.dom.setAttribute("contenteditable", "false");++ this.#editButton = document.createElement("button");+ this.#editButton.type = "button";+ this.#editButton.classList.add(EDIT_BUTTON_CLASS);+ this.#editButton.innerHTML = iconHTML("pencil");+ this.#editButton.addEventListener("click", this.#openEditModal);+ this.#editButton.addEventListener("keydown", this.#returnFocusToEditor);++ this.#render();+ }++ update(node) {+ const changed = !this.#node.sameMarkup(node);+ this.#node = node;++ if (changed) {+ this.#render();+ }++ return true;+ }++ selectNode() {+ this.dom.classList.add("ProseMirror-selectednode");+ }++ deselectNode() {+ this.dom.classList.remove("ProseMirror-selectednode");+ }++ stopEvent(event) {+ return this.#editButton.contains(event.target);+ }++ ignoreMutation() {+ return true;+ }++ destroy() {+ this.#editButton.removeEventListener("click", this.#openEditModal);+ this.#editButton.removeEventListener("keydown", this.#returnFocusToEditor);+ }++ /** Renders via the node spec's toDOM, so the chip matches what the schema serializes. */+ #render() {+ const { dom } = this.#DOMSerializer.renderSpec(+ document,+ this.#node.type.spec.toDOM(this.#node)+ );++ this.dom.replaceChildren(dom, this.#editButton);++ // names the date it edits, so several chips are told apart when read aloud+ const label = i18n("discourse_local_dates.edit_date", {+ date: dom.textContent.trim(),+ });+ this.#editButton.setAttribute("title", label);+ this.#editButton.setAttribute("aria-label", label);+ }++ #applyEdit(markup) {+ const pos = this.#getPos();++ if (pos === undefined) {+ return;+ }++ // the modal hands back a single date bbcode, so it parses to one paragraph+ const content = this.#convertFromMarkdown(markup).firstChild?.content;++ if (!content) {+ return;+ }++ const tr = this.#view.state.tr.replaceWith(+ pos,+ pos + this.#node.nodeSize,+ content+ );+ tr.setSelection(this.#NodeSelection.create(tr.doc, pos));+ this.#view.dispatch(tr);+ this.#view.focus();+ }+}++export default function createLocalDateNodeView({+ getContext,+ utils: { convertFromMarkdown },+ pmState: { NodeSelection },+ pmModel: { DOMSerializer },+}) {+ return (node, view, getPos) =>+ new LocalDateNodeView({+ node,+ view,+ getPos,+ getContext,+ convertFromMarkdown,+ NodeSelection,+ DOMSerializer,+ });+}++/**+ * Tab is bound by the composer, so a selected chip's edit button would+ * otherwise be unreachable without a mouse.+ */+export function focusEditButtonPlugin({ pmState: { Plugin, NodeSelection } }) {+ return new Plugin({+ props: {+ handleKeyDown(view, event) {+ if (event.key !== "Tab" || event.shiftKey) {+ return false;+ }++ const { selection } = view.state;++ if (+ !(selection instanceof NodeSelection) ||+ !DATE_NODE_TYPES.includes(selection.node.type.name)+ ) {+ return false;+ }++ const button = view+ .nodeDOM(selection.from)+ ?.querySelector?.(`.${EDIT_BUTTON_CLASS}`);++ if (!button) {+ return false;+ }++ button.focus();++ return true;+ },+ },+ });+}diff --git a/plugins/discourse-local-dates/assets/javascripts/lib/rich-editor-extension.js b/plugins/discourse-local-dates/assets/javascripts/lib/rich-editor-extension.jsindex ef4d7c95217..b45de9f86a4 100644--- a/plugins/discourse-local-dates/assets/javascripts/lib/rich-editor-extension.js+++ b/plugins/discourse-local-dates/assets/javascripts/lib/rich-editor-extension.js@@ -1,5 +1,8 @@import { buildBBCodeAttrs } from "discourse/lib/text";import formatLocalDate from "./format-local-date";+import createLocalDateNodeView, {+ focusEditButtonPlugin,+} from "./local-date-node-view";function wrapDateRangeSpans(element) {const dateSpans = element.querySelectorAll(@@ -98,6 +101,11 @@ function buildFormatOptions(nodeAttrs, includeRecurring = false) {/** @type {RichEditorExtension} */const extension = {+ nodeViews: {+ local_date: createLocalDateNodeView,+ local_date_range: createLocalDateNodeView,+ },+nodeSpec: {local_date: {attrs: {@@ -234,6 +242,9 @@ const extension = {},},},++ plugins: focusEditButtonPlugin,+parse: {span_open(state, token, tokens, i) {if (token.attrGet("class") !== "discourse-local-date") {diff --git a/plugins/discourse-local-dates/assets/stylesheets/common/discourse-local-dates.scss b/plugins/discourse-local-dates/assets/stylesheets/common/discourse-local-dates.scssindex caaa0b916d6..60c1f6cb9c5 100644--- a/plugins/discourse-local-dates/assets/stylesheets/common/discourse-local-dates.scss+++ b/plugins/discourse-local-dates/assets/stylesheets/common/discourse-local-dates.scss@@ -47,3 +47,33 @@cursor: pointer;margin-top: 0.5em;}++.composer-local-date {+ display: inline-flex;+ align-items: baseline;+ gap: var(--space-half);++ // keeps the button clear of the node-selection outline drawn at this edge+ padding-inline-end: var(--space-half);++ &__edit-button {+ padding: var(--space-half);+ line-height: 1;+ border: none;+ border-radius: var(--d-border-radius);+ background: none;+ color: var(--primary-low-mid);+ cursor: pointer;++ &:hover {+ color: var(--primary);+ }++ // a fill rather than a ring: the chip already carries a blue outline when selected+ &:focus-visible {+ outline: none;+ background: var(--d-hover);+ color: var(--primary);+ }+ }+}diff --git a/plugins/discourse-local-dates/config/locales/client.en.yml b/plugins/discourse-local-dates/config/locales/client.en.ymlindex 784bc74fb71..eb5fe6d4e65 100644--- a/plugins/discourse-local-dates/config/locales/client.en.yml+++ b/plugins/discourse-local-dates/config/locales/client.en.yml@@ -13,9 +13,12 @@ en:countdown:passed: date has passedtitle: Insert date / time+ edit: Edit date / time+ edit_date: Edit %{date}create:form:insert: Insert+ save: Saveformat_description: "Format used to display the date to the user. Use Z to show the offset and zz for the timezone name."timezones_title: Timezones to displaytimezones_description: Timezones will be used to display dates in preview and fallback.diff --git a/plugins/discourse-local-dates/spec/system/rich_editor_extension_spec.rb b/plugins/discourse-local-dates/spec/system/rich_editor_extension_spec.rbindex 659e59fd51d..ea17db57bfd 100644--- a/plugins/discourse-local-dates/spec/system/rich_editor_extension_spec.rb+++ b/plugins/discourse-local-dates/spec/system/rich_editor_extension_spec.rb@@ -5,6 +5,7 @@ describe "Composer - ProseMirror editor - Local Dates extension" dolet(:cdp) { PageObjects::CDP.new }let(:composer) { PageObjects::Components::Composer.new }let(:rich) { composer.rich_editor }+ let(:insert_datetime_modal) { PageObjects::Modals::InsertDateTime.new }before { sign_in(user) }@@ -102,4 +103,115 @@ describe "Composer - ProseMirror editor - Local Dates extension" do)endend++ describe "editing a date" do+ def paste_and_edit(markdown)+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ rich.click++ cdp.copy_paste(markdown)++ rich.find(".composer-local-date__edit-button").click+ expect(insert_datetime_modal).to be_open+ end++ it "opens the modal seeded with the date and replaces the node on save" do+ paste_and_edit(<<~MARKDOWN)+ [date=2022-12-15 time=14:19:00 timezone="Asia/Singapore"]+ MARKDOWN++ insert_datetime_modal.calendar_date_time_picker.fill_time("11:45")+ insert_datetime_modal.click_primary_button++ expect(rich).to have_css(+ "span.discourse-local-date[data-date='2022-12-15'][data-time='11:45:00']" \+ "[data-timezone='Asia/Singapore']",+ )++ composer.toggle_rich_editor++ expect(composer).to have_value("[date=2022-12-15 time=11:45:00 timezone=Asia/Singapore]")+ end++ it "keeps attributes the form has no field for" do+ paste_and_edit(<<~MARKDOWN)+ [date=2022-12-15 time=14:19:00 timezone="Asia/Singapore" countdown=true displayedTimezone=Europe/London]+ MARKDOWN++ insert_datetime_modal.calendar_date_time_picker.fill_time("11:45")+ insert_datetime_modal.click_primary_button++ expect(rich).to have_css(+ "span.discourse-local-date[data-time='11:45:00'][data-countdown='true']" \+ "[data-displayed-timezone='Europe/London']",+ )+ end++ it "edits the end of a date range" do+ paste_and_edit(<<~MARKDOWN)+ [date-range from=2022-12-15T14:19:00 to=2022-12-16T15:20:00 timezone="Asia/Singapore"]+ MARKDOWN++ insert_datetime_modal.select_to+ insert_datetime_modal.calendar_date_time_picker.fill_time("16:30")+ insert_datetime_modal.click_primary_button++ expect(rich).to have_css(+ "span.discourse-local-date[data-range='to'][data-date='2022-12-16']" \+ "[data-time='16:30:00']",+ )+ end++ it "shows the timezone preview when the date itself is clicked" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ rich.click++ cdp.copy_paste(<<~MARKDOWN)+ [date=2022-12-15 time=14:19:00 timezone="Asia/Singapore"]+ MARKDOWN++ rich.find("span.discourse-local-date").click++ expect(page).to have_css("[data-content] .locale-dates-previews")+ end++ it "reaches the edit button with the keyboard" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ rich.click++ cdp.copy_paste(<<~MARKDOWN)+ Meeting is [date=2022-12-15 time=14:19:00 timezone="Asia/Singapore"] ok+ MARKDOWN++ # arrow onto the chip, which selects it as a node+ 4.times { rich.send_keys(:left) }+ expect(rich).to have_css(".composer-local-date.ProseMirror-selectednode")++ rich.send_keys(:tab)+ expect(rich).to have_css(".composer-local-date__edit-button:focus")++ page.send_keys(:enter)+ expect(insert_datetime_modal).to be_open+ end++ it "tabs focus back to the editor from the edit button" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ rich.click++ cdp.copy_paste(<<~MARKDOWN)+ Meeting is [date=2022-12-15 time=14:19:00 timezone="Asia/Singapore"] ok+ MARKDOWN++ 4.times { rich.send_keys(:left) }+ rich.send_keys(:tab)+ expect(rich).to have_css(".composer-local-date__edit-button:focus")++ page.send_keys(:tab)+ expect(page).to have_css(".ProseMirror:focus")+ end+ endenddiff --git a/plugins/discourse-local-dates/test/javascripts/integration/rich-editor-extension-test.js b/plugins/discourse-local-dates/test/javascripts/integration/rich-editor-extension-test.jsindex d461ac9fb91..f66690a7ce3 100644--- a/plugins/discourse-local-dates/test/javascripts/integration/rich-editor-extension-test.js+++ b/plugins/discourse-local-dates/test/javascripts/integration/rich-editor-extension-test.js@@ -1,6 +1,10 @@+import { click, settled } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";+import {+ setupRichEditor,+ testMarkdown,+} from "discourse/tests/helpers/rich-editor-helper";module("Integration | Component | prosemirror-editor - local-dates plugin extension",@@ -15,6 +19,21 @@ module(return document.querySelector(".ProseMirror .discourse-local-date-range");}+ async function editDate(context, assert, markdown, markup) {+ const [editor] = await setupRichEditor(assert, markdown);++ await click(".composer-local-date__edit-button");++ const { model } = context.owner.lookup("service:modal").activeModal.opts;++ if (markup) {+ model.insertDate(markup);+ await settled();+ }++ return { editor, model };+ }+test("local date", async function (assert) {const markdown = "[date=2021-01-01 time=12:00:00]";@@ -280,5 +299,86 @@ module(markdown);});++ test("edit seeds the modal from the node attributes", async function (assert) {+ const { model } = await editDate(+ this,+ assert,+ '[date=2021-01-01 time=12:00:00 timezone=America/New_York format="YYYY-MM-DD" recurring=1.weeks timezones=Europe/Paris|Asia/Tokyo countdown=true displayedTimezone=Europe/London]'+ );++ assert.deepEqual(model.initialValues, {+ date: "2021-01-01",+ time: "12:00:00",+ toDate: null,+ toTime: null,+ timezone: "America/New_York",+ format: "YYYY-MM-DD",+ timezones: ["Europe/Paris", "Asia/Tokyo"],+ recurring: "1.weeks",+ countdown: "true",+ displayedTimezone: "Europe/London",+ });+ });++ test("edit seeds the modal from a range's node attributes", async function (assert) {+ const { model } = await editDate(+ this,+ assert,+ "[date-range from=2021-01-01T12:00:00 to=2021-01-02T13:00:00 timezone=America/New_York]"+ );++ assert.deepEqual(model.initialValues, {+ date: "2021-01-01",+ time: "12:00:00",+ toDate: "2021-01-02",+ toTime: "13:00:00",+ timezone: "America/New_York",+ format: null,+ timezones: [],+ recurring: null,+ countdown: null,+ displayedTimezone: null,+ });+ });++ test("applying an edit replaces the date node", async function (assert) {+ const { editor } = await editDate(+ this,+ assert,+ "before [date=2021-01-01 time=12:00:00] after",+ "[date=2022-02-02 time=13:00:00]"+ );++ assert.strictEqual(+ editor.value,+ "before [date=2022-02-02 time=13:00:00] after"+ );+ });++ test("applying an edit can turn a date into a range", async function (assert) {+ const { editor } = await editDate(+ this,+ assert,+ "[date=2021-01-01 time=12:00:00]",+ "[date-range from=2021-01-01T12:00:00 to=2021-01-02T13:00:00]"+ );++ assert.strictEqual(+ editor.value,+ "[date-range from=2021-01-01T12:00:00 to=2021-01-02T13:00:00]"+ );+ });++ test("applying an edit can turn a range into a date", async function (assert) {+ const { editor } = await editDate(+ this,+ assert,+ "[date-range from=2021-01-01T12:00:00 to=2021-01-02T13:00:00]",+ "[date=2021-01-01 time=12:00:00]"+ );++ assert.strictEqual(editor.value, "[date=2021-01-01 time=12:00:00]");+ });});