A platform for community discussion. Free, open, simple.
FEATURE: Add structural editing controls to rich-editor tables (#43102)
Renato Atilio4e975155e2e0
diff --git a/app/assets/stylesheets/common/rich-editor/_index.scss b/app/assets/stylesheets/common/rich-editor/_index.scssindex 527639ffe90..98965dbf4db 100644--- a/app/assets/stylesheets/common/rich-editor/_index.scss+++ b/app/assets/stylesheets/common/rich-editor/_index.scss@@ -1,2 +1,3 @@@import "rich-editor";@import "composer-image-gallery";+@import "composer-table";diff --git a/app/assets/stylesheets/common/rich-editor/composer-table.scss b/app/assets/stylesheets/common/rich-editor/composer-table.scssnew file mode 100644index 00000000000..9f58c5f6044--- /dev/null+++ b/app/assets/stylesheets/common/rich-editor/composer-table.scss@@ -0,0 +1,574 @@+.ProseMirror {+ .composer-table {+ --handle-length: 1.375rem;+ --handle-thickness: 0.375rem;+ --append-thickness: 0.875rem;+ --grip-lane: 1.125rem;++ @media (hover: none) {+ --handle-length: 1.75rem;+ --handle-thickness: 0.5rem;+ --append-thickness: 1.125rem;+ --grip-lane: 1.375rem;+ }+ position: relative;+ overflow-x: auto;+ overflow-y: hidden;++ &.is-panning table {+ user-select: none;+ }++ // Reserve space for controls inside the scroll container.+ padding: var(--grip-lane);++ // Keep the negative margin within the editor padding to avoid clipping.+ margin: 1em -0.625rem;++ &__inner {+ position: relative;+ width: max-content;+ }++ // Use an outline to avoid layout shifts when controls appear.+ table {+ outline: 1px solid transparent;+ touch-action: pan-y pinch-zoom;+ transition: outline-color 0.12s ease;+ }++ th,+ td {+ position: relative;++ // Keep empty cells wide enough to place the caret.+ min-width: 5em;++ // Compose shadows so corner cells can display both highlighted edges.+ &.is-structural-target {+ --edge-top: 0 0 0 0 transparent;+ --edge-right: 0 0 0 0 transparent;+ --edge-bottom: 0 0 0 0 transparent;+ --edge-left: 0 0 0 0 transparent;+ background-color: var(--token-color-background-accent-subtlest);+ box-shadow:+ var(--edge-top), var(--edge-right), var(--edge-bottom),+ var(--edge-left);++ &.--axis-row {+ --edge-top: inset 0 2px 0 0 var(--token-color-border-focused);+ --edge-bottom: inset 0 -2px 0 0 var(--token-color-border-focused);++ &.--edge-start {+ --edge-left: inset 2px 0 0 0 var(--token-color-border-focused);+ }++ &.--edge-end {+ --edge-right: inset -2px 0 0 0 var(--token-color-border-focused);+ }+ }++ &.--axis-column {+ --edge-left: inset 2px 0 0 0 var(--token-color-border-focused);+ --edge-right: inset -2px 0 0 0 var(--token-color-border-focused);++ &.--edge-start {+ --edge-top: inset 0 2px 0 0 var(--token-color-border-focused);+ }++ &.--edge-end {+ --edge-bottom: inset 0 -2px 0 0 var(--token-color-border-focused);+ }+ }+ }+ }++ // Swap physical shadow offsets in RTL; box-shadow has no logical equivalent.+ html[dir="rtl"] & {+ th,+ td {+ &.is-structural-target.--axis-row {+ &.--edge-start {+ --edge-left: 0 0 0 0 transparent;+ --edge-right: inset -2px 0 0 0 var(--token-color-border-focused);+ }++ &.--edge-end {+ --edge-right: 0 0 0 0 transparent;+ --edge-left: inset 2px 0 0 0 var(--token-color-border-focused);+ }+ }+ }+ }++ &__grip,+ &__append {+ position: absolute;+ z-index: 1;+ padding: 0;+ border: var(--token-border-width) solid transparent;+ background-color: var(--token-color-surface-pressed);+ cursor: pointer;+ opacity: 0;+ pointer-events: none;+ transition:+ opacity 0.12s ease,+ background-color 0.12s ease;++ &:focus-visible {+ opacity: 1;+ pointer-events: auto;+ outline: 2px solid var(--token-color-border-focused);+ outline-offset: 2px;+ }+ }++ &__grip {+ border-radius: var(--token-radius-normal);+ cursor: grab;++ &::after {+ content: "";+ position: absolute;+ inset: -0.5rem;+ }++ @media (hover: hover) {+ &:hover {+ background-color: var(--token-color-icon-default);+ }+ }++ &.--column {+ top: 0;+ left: 50%;+ translate: -50% -50%;+ width: var(--handle-length);+ height: var(--handle-thickness);+ touch-action: none;+ }++ &.--row {+ inset-inline-start: 0;+ top: 50%;+ translate: -50% -50%;+ width: var(--handle-thickness);+ height: var(--handle-length);+ touch-action: none;++ &:dir(rtl) {+ translate: 50% -50%;+ }+ }++ &.is-visible {+ opacity: 1;+ pointer-events: auto;+ }+ }++ // The axis class prevents a highlighted header row from activating every column grip.+ .is-structural-target.--axis-column .composer-table__grip.--column,+ .is-structural-target.--axis-row .composer-table__grip.--row {+ opacity: 1;+ pointer-events: auto;+ border-color: transparent;+ background-color: var(--token-color-background-accent-bolder);++ &::before {+ content: "";+ position: absolute;+ top: 50%;+ left: 50%;+ translate: -50% -50%;+ background-image: radial-gradient(+ circle,+ var(--token-color-text-inverse) 0.75px,+ transparent 0.75px+ );+ background-size: 0.25rem 0.25rem;+ }+ }++ .is-structural-target.--axis-column .composer-table__grip.--column {+ height: calc(var(--handle-thickness) * 2);++ &::before {+ width: 0.75rem;+ height: 0.5rem;+ }+ }++ .is-structural-target.--axis-row .composer-table__grip.--row {+ width: calc(var(--handle-thickness) * 2);++ &::before {+ width: 0.5rem;+ height: 0.75rem;+ }+ }++ &__append {+ border-radius: var(--token-radius-normal);++ .d-icon {+ position: absolute;+ top: 50%;+ left: 50%;+ width: 0.625rem;+ height: 0.625rem;+ translate: -50% -50%;+ color: var(--token-color-icon-default);+ transition: color 0.12s ease;+ }++ &:focus-visible {+ background-color: var(--token-color-background-accent-bolder);++ .d-icon {+ color: var(--token-color-text-inverse);+ }+ }++ @media (hover: hover) {+ &:hover {+ background-color: var(--token-color-background-accent-bolder);++ .d-icon {+ color: var(--token-color-text-inverse);+ }+ }+ }++ &.is-appending,+ &.is-removing {+ opacity: 1;+ pointer-events: auto;++ .d-icon {+ opacity: 0;+ }++ .composer-table__append-count {+ display: block;+ }+ }++ &.is-appending {+ background-color: var(--token-color-background-accent-bolder);+ }++ &.is-removing {+ background-color: var(--danger);+ }++ &.--column {+ top: 0;+ bottom: 0;+ inset-inline-end: calc(var(--grip-lane) * -1);+ width: var(--append-thickness);+ touch-action: pan-y pinch-zoom;+ cursor: ew-resize;++ &::after {+ content: "";+ position: absolute;+ inset-block: 0;+ inset-inline: -0.375rem;+ }+ }++ &.--row {+ left: 0;+ right: 0;+ bottom: calc(var(--grip-lane) * -1);+ height: var(--append-thickness);+ touch-action: pan-x pinch-zoom;+ cursor: ns-resize;++ &::after {+ content: "";+ position: absolute;+ inset-block: -0.375rem;+ inset-inline: 0;+ }+ }+ }++ &__append-count {+ position: absolute;+ top: 50%;+ left: 50%;+ display: none;+ min-width: 1.25rem;+ padding: var(--space-half) var(--space-1);+ border: var(--token-border-width) solid var(--token-color-border-default);+ border-radius: var(--token-radius-full);+ translate: -50% -50%;+ background-color: var(--token-color-surface);+ box-shadow: 0 2px 5px rgb(var(--primary-rgb), 0.18);+ color: var(--token-color-text-default);+ font-size: var(--font-down-2);+ font-weight: var(--token-font-weight-semibold);+ line-height: 1;+ text-align: center;+ white-space: nowrap;+ }++ // The node view adds padding to prevent the drag preview from being clipped.+ &__ghost {+ --ghost-step: 0px;+ --ghost-flow: to right;+ position: absolute;+ z-index: 1;+ display: none;+ border: 1px dashed var(--token-color-border-focused);+ border-radius: var(--token-radius-normal);+ background-color: var(--token-color-background-accent-subtlest);+ background-image: repeating-linear-gradient(+ var(--ghost-flow),+ transparent 0 calc(var(--ghost-step) - 1px),+ currentcolor calc(var(--ghost-step) - 1px) var(--ghost-step)+ );+ pointer-events: none;++ &.--visible {+ display: block;+ }++ &.--column {+ --ghost-flow: to right;+ }++ &.--row {+ --ghost-flow: to bottom;+ }++ &.--add {+ border-color: var(--token-color-border-focused);+ background-color: var(--token-color-background-accent-subtlest);+ color: var(--token-color-border-focused);+ }++ &.--remove {+ border-color: var(--danger);+ background-color: var(--danger-low);+ color: var(--danger);+ }+ }++ &__drop-indicator {+ position: absolute;+ z-index: 2;+ display: none;+ border-radius: 1px;+ background-color: var(--token-color-border-focused);+ pointer-events: none;++ &.--row {+ display: block;+ left: 0;+ right: 0;+ height: 2px;+ translate: 0 -1px;+ }++ &.--column {+ display: block;+ top: 0;+ bottom: 0;+ width: 2px;+ translate: -1px 0;+ }+ }++ @media (hover: hover) {+ &:hover {+ .composer-table__append {+ opacity: 1;+ pointer-events: auto;+ }++ table {+ outline-color: var(--token-color-border-default);+ }+ }+ }++ @media (hover: none) {+ &.is-active {+ .composer-table__append {+ opacity: 1;+ pointer-events: auto;+ }++ table {+ outline-color: var(--token-color-border-default);+ }+ }++ .is-current-row .composer-table__grip.--row,+ .is-current-column .composer-table__grip.--column {+ opacity: 1;+ pointer-events: auto;+ }++ .composer-table__grip.--column::after {+ inset-block: -1.125rem;+ inset-inline: -0.5rem;+ }++ .composer-table__grip.--row::after {+ inset-block: -0.5rem;+ inset-inline: -1.125rem;+ }++ .composer-table__append.--column::after {+ inset-inline: -0.8125rem;+ }++ .composer-table__append.--row::after {+ inset-block: -0.8125rem;+ }+ }++ .is-reordering {+ .composer-table__grip.is-visible {+ cursor: grabbing;+ }++ th.is-moving,+ td.is-moving {+ z-index: 1;+ opacity: 0.55;+ background-color: var(--token-color-background-accent-subtlest);+ }+ }++ @media (prefers-reduced-motion: reduce) {+ table,+ .composer-table__grip,+ .composer-table__append,+ .composer-table__append .d-icon {+ transition: none;+ }+ }++ @media (forced-colors: active) {+ th.is-structural-target,+ td.is-structural-target {+ outline: 2px solid Highlight;+ outline-offset: -2px;+ }++ .composer-table__grip,+ .composer-table__append {+ border-color: ButtonText;+ }++ .is-structural-target.--axis-column .composer-table__grip.--column,+ .is-structural-target.--axis-row .composer-table__grip.--row {+ outline: 2px solid Highlight;+ background: Highlight;+ color: HighlightText;+ forced-color-adjust: none;+ }+ }+ }+}++.composer-table__drag-avatar {+ position: fixed;+ z-index: z("composer", "dropdown");+ border-radius: var(--token-radius-normal);+ background-color: var(--token-color-background-accent-bolder);+ pointer-events: none;++ &::before {+ content: "";+ position: absolute;+ top: 50%;+ left: 50%;+ width: 0.75rem;+ height: 0.5rem;+ translate: -50% -50%;+ background-image: radial-gradient(+ circle,+ var(--token-color-text-inverse) 0.75px,+ transparent 0.75px+ );+ background-size: 0.25rem 0.25rem;+ }++ &.--row::before {+ width: 0.5rem;+ height: 0.75rem;+ }+}++.composer-table__grip.is-drag-origin {+ opacity: 0;+}++.fk-d-menu[data-identifier="composer-table-menu"] {+ // The composer sits above the default dropdown layer.+ z-index: z("composer", "dropdown");+ user-select: none;++ .fk-d-menu__inner-content {+ overflow: hidden;+ border-color: var(--token-color-border-default);+ border-radius: var(--token-radius-large);+ }+}++.composer-table-menu {+ min-width: 15rem;+ gap: 0;+ padding: var(--space-1);++ .dropdown-menu__divider {+ margin-block: var(--space-1);+ border-color: var(--token-color-border-default);+ }++ .btn {+ min-height: 2.125rem;+ height: auto;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 0;+ color: var(--token-color-text-default);+ font-size: var(--font-down-1);+ line-height: var(--line-height-medium);++ .d-icon {+ width: 1rem;+ color: var(--token-color-icon-subtle);+ font-size: var(--font-down-1);+ }++ &:hover,+ &:focus-visible {+ background-color: var(--token-color-surface-hovered);+ }++ &.--active {+ background-color: var(--token-color-surface-selected);++ .d-icon {+ color: var(--token-color-text-accent);+ }+ }++ &.--dangerous:hover,+ &.--dangerous:focus-visible {+ background-color: var(--danger-low);+ color: var(--danger);++ .d-icon {+ color: var(--token-color-icon-danger);+ }+ }+ }+}diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex ffbcfb282d7..634cffa3d38 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3851,6 +3851,59 @@ en:show_source: "Show source"show_preview: "Show preview"+ table:+ add_row: "Add row"+ add_column: "Add column"+ insert_row_above: "Insert above"+ insert_header_above: "Insert header above"+ insert_row_below: "Insert below"+ insert_column_left: "Insert left"+ insert_column_right: "Insert right"+ duplicate_row: "Duplicate row"+ duplicate_column: "Duplicate column"+ move_row_up: "Move row up"+ move_row_down: "Move row down"+ move_column_left: "Move column left"+ move_column_right: "Move column right"+ clear_contents: "Clear contents"+ delete_row: "Delete row"+ delete_column: "Delete column"+ delete_table: "Delete table"+ align_left: "Align left"+ align_center: "Align center"+ align_right: "Align right"+ row_actions: "Row %{number} actions"+ column_actions: "Column %{number} actions"+ row_inserted: "Row inserted"+ header_inserted: "Header row inserted"+ column_inserted: "Column inserted"+ row_duplicated: "Row duplicated"+ column_duplicated: "Column duplicated"+ row_moved_up: "Row moved up"+ row_moved_down: "Row moved down"+ column_moved_left: "Column moved left"+ column_moved_right: "Column moved right"+ contents_cleared: "Cell contents cleared"+ row_deleted: "Row deleted"+ column_deleted: "Column deleted"+ table_deleted: "Table deleted"+ alignment_left: "left"+ alignment_center: "center"+ alignment_right: "right"+ alignment_changed: "Column alignment changed to %{alignment}"+ rows_added:+ one: "%{count} row added"+ other: "%{count} rows added"+ columns_added:+ one: "%{count} column added"+ other: "%{count} columns added"+ rows_removed:+ one: "%{count} row removed"+ other: "%{count} rows removed"+ columns_removed:+ one: "%{count} column removed"+ other: "%{count} columns removed"+unsupported_token: "The rich text editor doesn’t support all features used in this post; switching you to the Markdown editor."notifications:diff --git a/frontend/discourse/app/components/composer/node-menu.gjs b/frontend/discourse/app/components/composer/node-menu.gjsnew file mode 100644index 00000000000..0eea486ed0b--- /dev/null+++ b/frontend/discourse/app/components/composer/node-menu.gjs@@ -0,0 +1,31 @@+import { fn } from "@ember/helper";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++const NodeMenu = <template>+ <DDropdownMenu class={{@data.className}} as |dropdown|>+ {{#each @data.items as |item|}}+ {{#if item.divider}}+ <dropdown.divider />+ {{else}}+ <dropdown.item>+ <DButton+ class={{dConcatClass+ item.className+ (if item.active "--active")+ (if item.dangerous "--dangerous")+ }}+ @action={{fn @data.run item}}+ @ariaPressed={{item.active}}+ @icon={{item.icon}}+ >+ {{item.label}}+ </DButton>+ </dropdown.item>+ {{/if}}+ {{/each}}+ </DDropdownMenu>+</template>;++export default NodeMenu;diff --git a/frontend/discourse/app/lib/composer/rich-editor-extensions.ts b/frontend/discourse/app/lib/composer/rich-editor-extensions.tsindex 50fd33caeea..9987de3941a 100644--- a/frontend/discourse/app/lib/composer/rich-editor-extensions.ts+++ b/frontend/discourse/app/lib/composer/rich-editor-extensions.ts@@ -22,6 +22,7 @@ import type MenuService from "discourse/float-kit/services/menu";import type ToastsService from "discourse/float-kit/services/toasts";import type Session from "discourse/models/session";import type Site from "discourse/models/site";+import type A11yService from "discourse/services/a11y";import type AppEventsService from "discourse/services/app-events";import type { CapabilitiesService } from "discourse/services/capabilities";import type ModalService from "discourse/services/modal";@@ -60,6 +61,8 @@ export interface PluginContext {siteSettings: Record<string, unknown>;/** Application event bus. */appEvents: AppEventsService;+ /** Service used to announce editor changes to assistive technology. */+ a11y: A11yService;/** Service used to show confirmation and alert dialogs. */dialog: DialogService;/** Replaces or restores the toolbar displayed by the editor container. */diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gtsindex 077e3e8c5b5..278ba754b9d 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts@@ -47,6 +47,7 @@ import type Site from "discourse/models/site";import type User from "discourse/models/user";import forceScrollingElementPosition from "discourse/modifiers/force-scrolling-element-position";import { focusOffScreen } from "discourse/modifiers/prevent-scroll-on-focus";+import type A11yService from "discourse/services/a11y";import type AppEventsService from "discourse/services/app-events";import type { CapabilitiesService } from "discourse/services/capabilities";import type ModalService from "discourse/services/modal";@@ -148,6 +149,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat@service declare siteSettings: SiteSettings;@service declare appEvents: AppEventsService;+ @service declare a11y: A11yService;@service declare currentUser: User;schema: Schema = createSchema(this.extensions, this.args.includeDefault);@@ -190,6 +192,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignatsite: this.site,siteSettings: this.siteSettings,appEvents: this.appEvents,+ a11y: this.a11y,dialog: this.dialog,replaceToolbar: this.args.replaceToolbar,markdownOptions: this.args.markdownOptions,diff --git a/frontend/discourse/app/static/prosemirror/extensions/table.js b/frontend/discourse/app/static/prosemirror/extensions/table.jsindex b8169671fa0..485bc42d8c2 100644--- a/frontend/discourse/app/static/prosemirror/extensions/table.js+++ b/frontend/discourse/app/static/prosemirror/extensions/table.js@@ -1,3 +1,7 @@+import { tableChrome } from "../lib/table/chrome";+import tableEditing from "../lib/table/editing";+import { buildTableNodeView, TableCellView } from "../lib/table/node-view";+// Markdown Table Example://// | Left-aligned | Center-aligned | Right-aligned |@@ -5,21 +9,13 @@// | git status | git status | git status |// | git diff | git diff | git diff |-class TableNodeView {- constructor() {- const div = document.createElement("div");- div.classList.add("md-table");- const table = document.createElement("table");- div.appendChild(table);-- this.dom = div;- this.contentDOM = table;- }-}-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */const extension = {- nodeViews: { table: TableNodeView },+ nodeViews: {+ table: buildTableNodeView,+ table_cell: TableCellView,+ table_header_cell: TableCellView,+ },nodeSpec: {table: {content: "table_head? table_body",@@ -30,7 +26,7 @@ const extension = {draggable: true,parseDOM: [{ tag: "table" }],toDOM() {- return ["table", { class: "md-table" }, 0];+ return ["div", { class: "md-table" }, ["table", 0]];},},table_head: {@@ -43,7 +39,7 @@ const extension = {},},table_body: {- content: "table_row+",+ content: "table_row*",tableRole: "body",isolating: true,parseDOM: [{ tag: "tbody" }],@@ -205,7 +201,12 @@ const extension = {table_header_cell() {},table_cell() {},},- plugins({ pmState: { Plugin }, pmModel: { Slice, Fragment } }) {+ plugins(params) {+ const {+ pmState: { Plugin },+ pmModel: { Slice, Fragment },+ } = params;+function hasTableNodes(fragment) {let found = false;fragment.descendants((node) => {@@ -217,7 +218,7 @@ const extension = {return found;}- return new Plugin({+ const pastedTables = new Plugin({props: {transformPasted(paste) {if (!hasTableNodes(paste.content)) {@@ -247,6 +248,8 @@ const extension = {},},});++ return [pastedTables, tableEditing(), tableChrome(params)];},};diff --git a/frontend/discourse/app/static/prosemirror/lib/table/chrome.js b/frontend/discourse/app/static/prosemirror/lib/table/chrome.jsnew file mode 100644index 00000000000..b7cc6b56823--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/chrome.js@@ -0,0 +1,539 @@+import { Plugin, PluginKey } from "prosemirror-state";+import { Decoration, DecorationSet } from "prosemirror-view";+import { i18n } from "discourse-i18n";+import { moveColumn, moveRow, runCommand } from "./commands";+import dragAutoscroll from "./drag-autoscroll";+import {+ cellAround,+ cellCoords,+ findTable,+ isTable,+ rectFor,+ tableGrid,+} from "./grid";+import { handleContextMenuKey, openGripMenu } from "./menu";+import trackPointer from "./track-pointer";++const DRAG_THRESHOLD = 4;+const TOUCH_DRAG_THRESHOLD = 12;+const TABLE_CHROME_KEY = new PluginKey("tableChrome");++/**+ * Cell widgets position the grips through CSS. Resolving their row and column+ * from the current document position keeps reused widgets correct after edits.+ */+export function tableChrome(pluginParams) {+ const cache = new WeakMap();+ const activeGestures = new Set();++ return new Plugin({+ key: TABLE_CHROME_KEY,++ state: {+ init: () => null,+ apply(tr, target) {+ const next = tr.getMeta(TABLE_CHROME_KEY);+ if (next !== undefined) {+ return next;+ }+ return tr.selectionSet || tr.docChanged ? null : target;+ },+ },++ props: {+ decorations: (state) =>+ chromeDecorations(+ state,+ pluginParams,+ cache,+ activeGestures,+ TABLE_CHROME_KEY.getState(state)+ ),+ handleKeyDown: (view, event) =>+ handleContextMenuKey(view, event, pluginParams),+ },+ view: (view) => {+ syncGripAccessibility(view);++ return {+ update: (_, previousState) => {+ if (!view.editable || view.state.doc !== previousState.doc) {+ [...activeGestures].forEach((stop) => stop());+ }+ syncGripAccessibility(view);+ },+ destroy: () => {+ [...activeGestures].forEach((stop) => stop());+ },+ };+ },+ });+}++function chromeDecorations(state, pluginParams, cache, activeGestures, target) {+ let set = cache.get(state.doc);+ if (!set) {+ set = gripDecorations(state, pluginParams, activeGestures);+ cache.set(state.doc, set);+ }++ const selected = targetDecorations(state, target);+ return selected.length ? set.add(state.doc, selected) : set;+}++function gripDecorations(state, pluginParams, activeGestures) {+ const decorations = [];++ state.doc.descendants((node, pos) => {+ if (node.isTextblock || !node.isBlock) {+ return false;+ }+ if (!isTable(node)) {+ return;+ }++ const grid = tableGrid(node);+ const start = pos + 1;++ grid.rows.forEach((row, index) => {+ if (row.cells[0]) {+ decorations.push(+ gripDecoration(+ start + row.cells[0].offset + 1,+ "row",+ pluginParams,+ activeGestures+ )+ );+ }++ if (index === 0) {+ row.cells.forEach((cell) => {+ decorations.push(+ gripDecoration(+ start + cell.offset + 1,+ "column",+ pluginParams,+ activeGestures+ )+ );+ });+ }+ });++ return false;+ });++ return DecorationSet.create(state.doc, decorations);+}++function targetDecorations(state, target) {+ if (!target) {+ return [];+ }++ const node = state.doc.nodeAt(target.tablePos);+ if (!isTable(node)) {+ return [];+ }++ const grid = tableGrid(node);+ const rect = rectFor(grid, target.kind, target.index);+ const decorations = [];++ // The band is one row or one column, so only its two ends along the axis it+ // runs down need marking; its long sides follow from the axis class.+ const alongRow = target.kind === "row";+ const first = alongRow ? rect.left : rect.top;+ const last = alongRow ? rect.right : rect.bottom;++ for (let row = rect.top; row <= rect.bottom; row++) {+ for (let col = rect.left; col <= rect.right; col++) {+ const cell = grid.rows[row]?.cells[col];+ if (!cell) {+ continue;+ }++ const index = alongRow ? col : row;+ const classes = ["is-structural-target", `--axis-${target.kind}`];++ if (index === first) {+ classes.push("--edge-start");+ }+ if (index === last) {+ classes.push("--edge-end");+ }++ const pos = target.tablePos + 1 + cell.offset;+ decorations.push(+ Decoration.node(pos, pos + cell.node.nodeSize, {+ class: classes.join(" "),+ })+ );+ }+ }++ return decorations;+}++function gripDecoration(pos, kind, pluginParams, activeGestures) {+ return Decoration.widget(+ pos,+ (view, getPos) =>+ buildGrip(kind, view, getPos, pluginParams, activeGestures),+ {+ side: -1,+ key: `table-grip-${kind}`,+ ignoreSelection: true,+ stopEvent: () => true,+ }+ );+}++function buildGrip(kind, view, getPos, pluginParams, activeGestures) {+ const grip = document.createElement("button");+ grip.type = "button";+ grip.className = `composer-table__grip --${kind}`;+ grip.contentEditable = "false";+ grip.draggable = false;+ grip.tabIndex = -1;+ grip.setAttribute("aria-expanded", "false");+ // Open on click so a touch's delayed click cannot land on the new backdrop.+ const context = {+ kind,+ view,+ getPos,+ pluginParams,+ activeGestures,+ grip,+ dragged: false,+ };+ grip.addEventListener("mousedown", (event) => event.preventDefault());+ grip.addEventListener("pointerdown", (event) =>+ onGripPointerDown(event, context)+ );+ grip.addEventListener("click", (event) => onGripClick(event, context));++ return grip;+}++function onGripPointerDown(event, context) {+ if (!context.view.editable || event.button !== 0) {+ return;+ }+ event.preventDefault();+ context.dragged = false;++ const target = locateGrip(context);+ if (!target) {+ return;+ }++ highlightAt(context.view, target, context.kind);+ trackDrag(event, context, target);+}++function onGripClick(event, context) {+ if (!context.view.editable) {+ return;+ }++ if (event.detail !== 0 && context.dragged) {+ return;+ }++ const target = locateGrip(context);+ if (!target) {+ return;+ }++ highlightAt(context.view, target, context.kind);+ openGripMenu(context, target);+}++/** The table, row and column the grip currently belongs to. */+function locateGrip({ view, getPos }) {+ const pos = getPos();+ if (pos === undefined) {+ return null;+ }++ const $cell = cellAround(view.state.doc.resolve(pos));+ if (!$cell) {+ return null;+ }++ const table = findTable($cell);+ const coords = cellCoords(table.grid, $cell.pos - table.start);+ return coords ? { table, ...coords } : null;+}++function highlightAt(view, { table, row, col }, kind) {+ view.dispatch(+ view.state.tr.setMeta(TABLE_CHROME_KEY, {+ tablePos: table.pos,+ kind,+ index: kind === "row" ? row : col,+ })+ );+}++function trackDrag(startEvent, context, target) {+ const { activeGestures, kind, grip, view } = context;+ const inner = grip.closest(".composer-table__inner");+ const indicator = inner?.querySelector(".composer-table__drop-indicator");+ const grid = inner?.querySelector("table");+ if (!inner || !grid) {+ return;+ }++ const axis = kind === "row" ? "Y" : "X";+ const origin = kind === "row" ? startEvent.clientY : startEvent.clientX;+ const index = kind === "row" ? target.row : target.col;+ const dragThreshold =+ startEvent.pointerType === "touch" ? TOUCH_DRAG_THRESHOLD : DRAG_THRESHOLD;++ // Geometry is read once. The dragged row or column follows the pointer while+ // the gesture runs, so measuring again mid-drag would read its own offset+ // back and chase itself.+ const spans = measureSpans(inner, grid, kind);+ const forward = spanDirection(spans);+ const moving =+ kind === "row"+ ? [...(grid.rows[index]?.cells ?? [])]+ : [...grid.rows].map((row) => row.cells[index]).filter(Boolean);++ let dragging = false;+ let dropIndex = null;+ let current = origin;+ let avatar = null;+ let stopped = false;+ const updateLanding = () => {+ const over = spanUnderPointer(spans, current, forward);+ dropIndex = over === index ? null : over > index ? over + 1 : over;+ positionIndicator(indicator, kind, spans, dropIndex, forward);+ };++ const autoscroll = dragAutoscroll(inner, axis, (change) => {+ for (const span of spans) {+ span.start -= change;+ span.end -= change;+ }+ updateLanding();+ });++ const lift = (offset) => {+ moving.forEach((cell) => {+ cell.style.transform = `translate${axis}(${offset}px)`;+ });+ if (avatar) {+ avatar.style.transform = `translate${axis}(${offset}px)`;+ }+ };++ const settle = () => {+ moving.forEach((cell) => {+ cell.style.transform = "";+ cell.classList.remove("is-moving");+ });+ avatar?.remove();+ avatar = null;+ grip.classList.remove("is-drag-origin");+ inner.classList.remove("is-reordering");+ if (indicator) {+ indicator.className = "composer-table__drop-indicator";+ indicator.removeAttribute("style");+ }+ };++ const stop = () => {+ if (stopped) {+ return;+ }++ stopped = true;+ stopTracking();+ activeGestures.delete(stop);+ autoscroll.stop();+ settle();+ };++ const move = (event) => {+ current = kind === "row" ? event.clientY : event.clientX;+ const offset = current - origin;++ if (!dragging && Math.abs(offset) < dragThreshold) {+ return;+ }++ event.preventDefault();+ if (!dragging) {+ dragging = true;+ context.dragged = true;+ inner.classList.add("is-reordering");+ moving.forEach((cell) => cell.classList.add("is-moving"));+ avatar = dragAvatar(grip, kind);+ grip.classList.add("is-drag-origin");+ }++ lift(offset);+ autoscroll.update(event);++ // Landing is decided by which row or column the pointer is over, not by how+ // far past its middle: an insertion index taken from midpoints needs a drag+ // of one and a half columns to move a column by one.+ updateLanding();+ };++ const finish = (event) => {+ const landed = event.type === "pointercancel" ? null : dropIndex;+ stop();++ if (dragging && landed !== null) {+ const command =+ kind === "row"+ ? moveRow(index, landed, target.table)+ : moveColumn(index, landed, target.table);+ if (runCommand(view, command)) {+ announceMove(context, index, landed);+ }+ }+ };++ const stopTracking = trackPointer(startEvent, move, finish);+ activeGestures.add(stop);+}++function announceMove({ kind, pluginParams, view }, index, landed) {+ const forward = landed > index;+ let key;++ if (kind === "row") {+ key = forward ? "row_moved_down" : "row_moved_up";+ } else {+ const rtl = getComputedStyle(view.dom).direction === "rtl";+ key = forward !== rtl ? "column_moved_right" : "column_moved_left";+ }++ pluginParams.getContext().a11y.announce(i18n(`composer.table.${key}`));+}++function syncGripAccessibility(view) {+ for (const button of view.dom.querySelectorAll(+ ".composer-table__grip, .composer-table__append"+ )) {+ button.hidden = !view.editable;+ button.disabled = !view.editable;+ }+ for (const grip of view.dom.querySelectorAll(".composer-table__grip")) {+ const row = grip.closest("tr");+ const cell = grip.closest("th, td");+ const kind = grip.classList.contains("--row") ? "row" : "column";+ const current =+ kind === "row"+ ? cell?.matches(".is-current-row, .is-structural-target.--axis-row")+ : cell?.matches(+ ".is-current-column, .is-structural-target.--axis-column"+ );+ const number = kind === "row" ? row?.rowIndex + 1 : cell?.cellIndex + 1;++ grip.setAttribute("aria-hidden", current ? "false" : "true");+ if (number) {+ grip.setAttribute(+ "aria-label",+ i18n(`composer.table.${kind}_actions`, { number })+ );+ }+ }+}++function dragAvatar(grip, kind) {+ const bounds = grip.getBoundingClientRect();+ const avatar = document.createElement("div");+ avatar.className = `composer-table__drag-avatar --${kind}`;+ avatar.ariaHidden = "true";+ Object.assign(avatar.style, {+ top: `${bounds.top}px`,+ left: `${bounds.left}px`,+ width: `${bounds.width}px`,+ height: `${bounds.height}px`,+ });+ document.body.appendChild(avatar);+ return avatar;+}++/** Start, size and offset within `inner` of every row or column, in order. */+function measureSpans(inner, grid, kind) {+ const bounds = inner.getBoundingClientRect();+ const elements =+ kind === "row" ? [...grid.rows] : [...(grid.rows[0]?.cells ?? [])];++ return elements.map((element) => {+ const box = element.getBoundingClientRect();++ return kind === "row"+ ? {+ start: box.top,+ end: box.bottom,+ offset: box.top - bounds.top,+ size: box.height,+ }+ : {+ start: box.left,+ end: box.right,+ offset: box.left - bounds.left,+ size: box.width,+ };+ });+}++/** +1 when the axis grows with the index, -1 for columns in RTL. */+function spanDirection(spans) {+ if (spans.length < 2) {+ return 1;+ }++ const first = spans[0];+ const last = spans[spans.length - 1];+ return Math.sign(last.start + last.end - (first.start + first.end)) || 1;+}++function spanUnderPointer(spans, position, forward) {+ if (!spans.length) {+ return 0;+ }++ const found = spans.findIndex(+ (span) => position >= span.start && position < span.end+ );+ if (found !== -1) {+ return found;+ }++ const firstCenter = (spans[0].start + spans[0].end) / 2;+ return (position - firstCenter) * forward < 0 ? 0 : spans.length - 1;+}++function positionIndicator(indicator, kind, spans, dropIndex, forward) {+ if (!indicator) {+ return;+ }++ if (dropIndex === null) {+ indicator.className = "composer-table__drop-indicator";+ indicator.removeAttribute("style");+ return;+ }++ const after = dropIndex > 0 ? spans[dropIndex - 1] : null;+ const edge = after+ ? after.offset + (forward > 0 ? after.size : 0)+ : spans[0].offset + (forward > 0 ? 0 : spans[0].size);++ indicator.className = `composer-table__drop-indicator --${kind}`;+ if (kind === "row") {+ indicator.style.top = `${edge}px`;+ } else {+ indicator.style.left = `${edge}px`;+ }+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/commands.js b/frontend/discourse/app/static/prosemirror/lib/table/commands.jsnew file mode 100644index 00000000000..fd1aa2d34c5--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/commands.js@@ -0,0 +1,559 @@+import { Fragment } from "prosemirror-model";+import { TextSelection } from "prosemirror-state";+import {+ cellAround,+ cellCoords,+ cellType,+ copyCell,+ findTable,+ rowRange,+ tableGrid,+} from "./grid";++export function runCommand(view, command) {+ if (!view.editable) {+ return false;+ }+ const handled = command(view.state, view.dispatch);+ if (handled) {+ view.focus();+ }+ return handled;+}++export function selectCell(tr, tablePos, row, col) {+ const grid = tableGrid(tr.doc.nodeAt(tablePos));+ const cell = grid.rows[row]?.cells[col];+ return cell+ ? tr.setSelection(TextSelection.create(tr.doc, tablePos + cell.offset + 2))+ : tr;+}++export const ALIGNMENTS = ["left", "center", "right"];++/**+ * The table and cell containing the start of the current text selection, or+ * null when it is outside a table.+ */+export function currentCell(state) {+ const { selection } = state;+ const $cell = cellAround(selection.$from);++ if (!$cell) {+ return null;+ }++ const table = findTable($cell);+ if (!table) {+ return null;+ }++ const coords = cellCoords(table.grid, $cell.pos - table.start);+ if (!coords) {+ return null;+ }++ return {+ ...table,+ rect: {+ top: coords.row,+ bottom: coords.row,+ left: coords.col,+ right: coords.col,+ },+ };+}++/**+ * A command over `target`, or over the table the caret is in when no target is+ * given. `apply` builds the transaction and may return null to dispatch+ * nothing; `enabled` rejects the command before it is dispatched.+ */+function tableCommand(target, apply, enabled) {+ return (state, dispatch) => {+ const table = target ?? currentCell(state);+ if (+ !table ||+ table.pos > state.doc.content.size ||+ state.doc.nodeAt(table.pos) !== table.node ||+ enabled?.(table) === false+ ) {+ return false;+ }++ if (dispatch) {+ const tr = apply(state.tr, table);+ if (tr) {+ dispatch(tr);+ }+ }+ return true;+ };+}++/**+ * Trailing columns whose every cell is empty, and so can be dropped without+ * losing anything. At least one column always stays.+ */+export function emptyTrailingColumns(grid) {+ let count = 0;++ for (let col = grid.width - 1; col > 0; col--) {+ const empty = grid.rows.every((row) => isEmptyCell(row.cells[col]));+ if (!empty) {+ break;+ }+ count++;+ }++ return count;+}++/** The same for body rows. A header-only table is still a valid table. */+export function emptyTrailingRows(grid) {+ const body = grid.rows.filter((row) => !row.header);+ let count = 0;++ for (let index = body.length - 1; index >= 0; index--) {+ const empty = body[index].cells.every(isEmptyCell);+ if (!empty) {+ break;+ }+ count++;+ }++ return count;+}++function isEmptyCell(cell) {+ return !cell || cell.node.content.size === 0;+}++export function columnAlignment(table, col) {+ return table.grid.rows[0]?.cells[col]?.node.attrs.alignment ?? null;+}++export function addColumn(side, target, count = 1) {+ return tableCommand(target, (tr, table) =>+ insertColumn(+ tr,+ table,+ side < 0 ? table.rect.left : table.rect.right + 1,+ count+ ).scrollIntoView()+ );+}++export function deleteColumn(target) {+ return tableCommand(target, (tr, table) => {+ const { left, right } = table.rect;++ if (right - left + 1 >= table.grid.width) {+ return tr.delete(table.pos, table.pos + table.node.nodeSize);+ }++ forEachRowBottomUp(table, (row) => {+ for (let col = right; col >= left; col--) {+ const cell = row.cells[col];+ if (cell) {+ tr.delete(+ table.start + cell.offset,+ table.start + cell.offset + cell.node.nodeSize+ );+ }+ }+ });++ return tr;+ });+}++export function duplicateColumn(target) {+ return tableCommand(target, (tr, table) => {+ const { left, right } = table.rect;++ forEachRowBottomUp(table, (row) => {+ const copies = [];+ for (let col = left; col <= right; col++) {+ const cell = row.cells[col].node;+ copies.push(copyCell(cell.type, cell));+ }+ const ref = row.cells[right];+ tr.insert(+ table.start + ref.offset + ref.node.nodeSize,+ Fragment.from(copies)+ );+ });++ return tr.scrollIntoView();+ });+}++/**+ * @param {number} from index of the column to move+ * @param {number} to insertion index, in the coordinates of the unmoved grid+ */+export function moveColumn(from, to, tableTarget) {+ return tableCommand(+ tableTarget,+ (tr, table) => {+ const target = to > from ? to - 1 : to;++ forEachRowBottomUp(table, (row) => {+ const cells = row.cells.map((cell) => cell.node);+ const [moved] = cells.splice(from, 1);+ cells.splice(target, 0, moved);+ tr.replaceWith(+ table.start + row.offset + 1,+ table.start + row.offset + row.node.nodeSize - 1,+ Fragment.from(cells)+ );+ });++ return tr;+ },+ () => to !== from && to !== from + 1+ );+}++export function setColumnAlignment(alignment, target) {+ return tableCommand(target, (tr, table) => {+ for (const row of table.grid.rows) {+ for (let col = table.rect.left; col <= table.rect.right; col++) {+ const cell = row.cells[col];+ if (cell) {+ tr.setNodeMarkup(table.start + cell.offset, null, {+ ...cell.node.attrs,+ alignment,+ });+ }+ }+ }++ return tr;+ });+}++export function addRow(side, target, count = 1) {+ return tableCommand(+ target,+ (tr, table) => {+ const offset = headOffset(table.grid);+ const index =+ side < 0+ ? Math.max(table.rect.top - offset, 0)+ : table.rect.bottom - offset + 1;++ const pos = insertRow(tr, table, index, count);+ return selectCellContent(tr, pos + 1).scrollIntoView();+ },+ (table) => !!table.grid.body+ );+}++export function deleteRow(target) {+ return tableCommand(target, (tr, table) =>+ removeRows(tr, table, table.rect.top, table.rect.bottom)+ );+}++export function duplicateRow(target) {+ return tableCommand(+ target,+ (tr, table) => {+ const { top, bottom } = table.rect;+ const schema = table.node.type.schema;+ const copies = [];++ for (let index = top; index <= bottom; index++) {+ const row = table.grid.rows[index];+ const cells = [];+ row.node.forEach((cell) => {+ // A duplicated header row becomes a regular row: markdown allows only one.+ const type = row.header ? schema.nodes.table_cell : cell.type;+ cells.push(copyCell(type, cell));+ });+ copies.push(schema.nodes.table_row.create(null, Fragment.from(cells)));+ }++ tr.insert(+ bodyInsertPos(table, bottom - headOffset(table.grid) + 1),+ Fragment.from(copies)+ );++ return tr.scrollIntoView();+ },+ (table) => !!table.grid.body+ );+}++/**+ * @param {number} from index of the row to move+ * @param {number} to insertion index, in the coordinates of the unmoved grid+ */+export function moveRow(from, to, tableTarget) {+ return tableCommand(+ tableTarget,+ (tr, table) => {+ // Header status belongs to the first row, not the moved content.+ if (table.grid.head && (from === 0 || to === 0)) {+ return reorderAcrossHeader(tr, table, from, to);+ }++ const range = rowRange(table, from);+ const target = bodyInsertPos(table, to - headOffset(table.grid));++ tr.delete(range.from, range.to);+ tr.insert(tr.mapping.map(target), table.grid.rows[from].node);++ return tr;+ },+ (table) => to !== from && to !== from + 1 && !!table.grid.rows[from]+ );+}++// Replacing both sections together keeps header promotion schema-valid.+function replaceRows(tr, table, order) {+ const schema = table.node.type.schema;++ const rows = order.map((row, index) => {+ const type = cellType(schema, index === 0);+ const cells = [];+ row.forEach((cell) => cells.push(copyCell(type, cell)));+ return schema.nodes.table_row.create(null, Fragment.from(cells));+ });++ const replacement = schema.nodes.table.create(table.node.attrs, [+ schema.nodes.table_head.create(null, rows[0]),+ schema.nodes.table_body.create(null, Fragment.from(rows.slice(1))),+ ]);++ return tr.replaceWith(+ table.pos,+ table.pos + table.node.nodeSize,+ replacement+ );+}++function reorderAcrossHeader(tr, table, from, to) {+ const order = table.grid.rows.map((row) => row.node);+ const [moved] = order.splice(from, 1);+ const landing = to > from ? to - 1 : to;+ order.splice(landing, 0, moved);++ return selectCell(replaceRows(tr, table, order), table.pos, landing, 0);+}++/** Inserts a header and demotes the old one to the body. */+export function addHeaderRow(target) {+ return tableCommand(+ target,+ (tr, table) => {+ const schema = table.node.type.schema;+ const cells = Array.from({ length: table.grid.width }, (_, col) =>+ cellType(schema, true).createAndFill({+ alignment: columnAlignment(table, col),+ })+ );++ const header = schema.nodes.table_row.create(null, Fragment.from(cells));+ const order = [header, ...table.grid.rows.map((row) => row.node)];++ // The head's own row holds the first cell two positions in.+ return selectCellContent(+ replaceRows(tr, table, order),+ table.start + 2+ ).scrollIntoView();+ },+ (table) => !!table.grid.head+ );+}++export function deleteTable(target) {+ return tableCommand(target, (tr, table) =>+ tr.delete(table.pos, table.pos + table.node.nodeSize)+ );+}++export function goToNextCell(dir) {+ return (state, dispatch) => {+ const table = currentCell(state);+ if (!table) {+ return false;+ }++ const { grid, rect } = table;+ const index = rect.top * grid.width + rect.left + dir;++ if (index < 0) {+ return false;+ }++ if (index >= grid.width * grid.height) {+ if (dir < 0 || !grid.body) {+ return false;+ }++ if (dispatch) {+ const tr = state.tr;+ const pos = insertRow(tr, table, grid.height - headOffset(grid));+ dispatch(selectCellContent(tr, pos + 1).scrollIntoView());+ }+ return true;+ }++ if (dispatch) {+ const row = Math.floor(index / grid.width);+ const col = index % grid.width;+ dispatch(+ selectCellContent(+ state.tr,+ table.start + grid.rows[row].cells[col].offset+ ).scrollIntoView()+ );+ }+ return true;+ };+}++export function clearCellContents(target) {+ return tableCommand(target, (tr, table) => {+ const cells = [];+ for (let row = table.rect.top; row <= table.rect.bottom; row++) {+ for (let col = table.rect.left; col <= table.rect.right; col++) {+ const cell = table.grid.rows[row]?.cells[col];+ if (cell) {+ cells.push({ node: cell.node, pos: table.start + cell.offset });+ }+ }+ }++ for (let index = cells.length - 1; index >= 0; index--) {+ const { node, pos } = cells[index];+ if (node.content.size) {+ tr.delete(pos + 1, pos + node.nodeSize - 1);+ }+ }++ return tr.docChanged ? tr : null;+ });+}++function headOffset(grid) {+ return grid.head ? 1 : 0;+}++function forEachRowBottomUp(table, f) {+ for (let index = table.grid.rows.length - 1; index >= 0; index--) {+ f(table.grid.rows[index], index);+ }+}++function insertColumn(tr, table, col, count = 1) {+ const schema = table.node.type.schema;++ forEachRowBottomUp(table, (row) => {+ const last = row.cells[row.cells.length - 1];+ const at =+ col >= row.cells.length+ ? table.start + last.offset + last.node.nodeSize+ : table.start + row.cells[col].offset;++ const cells = Array.from({ length: count }, () =>+ cellType(schema, row.header).createAndFill()+ );+ tr.insert(at, Fragment.from(cells));+ });++ return tr;+}++/** Position where a body row inserted at `bodyIndex` would start. */+function bodyInsertPos(table, bodyIndex) {+ const { start, grid } = table;+ const rows = grid.rows.filter((row) => !row.header);++ if (!rows.length) {+ return start + grid.body.offset + 1;+ }+ if (bodyIndex >= rows.length) {+ const last = rows[rows.length - 1];+ return start + last.offset + last.node.nodeSize;+ }+ return start + rows[Math.max(bodyIndex, 0)].offset;+}++/** Inserts an empty body row and returns the position it starts at. */+function insertRow(tr, table, bodyIndex, count = 1) {+ const schema = table.node.type.schema;+ const cells = [];++ for (let col = 0; col < table.grid.width; col++) {+ cells.push(+ cellType(schema, false).createAndFill({+ alignment: columnAlignment(table, col),+ })+ );+ }++ const pos = bodyInsertPos(table, bodyIndex);+ const rows = Array.from({ length: count }, () =>+ schema.nodes.table_row.create(null, Fragment.from(cells))+ );+ tr.insert(pos, Fragment.from(rows));+ return pos;+}++function removeRows(tr, table, top, bottom) {+ const { grid, start } = table;+ const removingHeader = !!grid.head && top === 0;+ const promoted = removingHeader ? grid.rows[bottom + 1] : null;++ if (removingHeader && !promoted) {+ return tr.delete(table.pos, table.pos + table.node.nodeSize);+ }++ // Highest position first, so the offsets read from the original grid stay valid.+ if (promoted) {+ tr.delete(+ start + promoted.offset,+ start + promoted.offset + promoted.node.nodeSize+ );+ }++ for (let index = bottom; index >= Math.max(top, headOffset(grid)); index--) {+ const row = grid.rows[index];+ tr.delete(start + row.offset, start + row.offset + row.node.nodeSize);+ }++ if (promoted) {+ const schema = table.node.type.schema;+ const headRow = grid.rows[0];+ const cells = [];+ promoted.node.forEach((cell) =>+ cells.push(copyCell(cellType(schema, true), cell))+ );++ tr.replaceWith(+ start + headRow.offset + 1,+ start + headRow.offset + headRow.node.nodeSize - 1,+ Fragment.from(cells)+ );+ }++ return tr;+}++function selectCellContent(tr, pos) {+ const cell = tr.doc.nodeAt(pos);+ if (!cell) {+ return tr;+ }++ return tr.setSelection(+ TextSelection.between(+ tr.doc.resolve(pos + 1),+ tr.doc.resolve(pos + cell.nodeSize - 1)+ )+ );+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/drag-autoscroll.js b/frontend/discourse/app/static/prosemirror/lib/table/drag-autoscroll.jsnew file mode 100644index 00000000000..43c296ba5a2--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/drag-autoscroll.js@@ -0,0 +1,90 @@+const EDGE_SIZE = 32;+const MAX_STEP = 18;++export default function dragAutoscroll(anchor, axis, onScroll) {+ let frame = null;+ let point = null;+ let stopped = false;++ const tick = () => {+ frame = null;+ if (stopped || point === null) {+ return;+ }++ const scroller = scrollTarget(anchor, axis, point);+ if (!scroller) {+ return;+ }++ const property = axis === "X" ? "scrollLeft" : "scrollTop";+ const before = scroller.element[property];+ scroller.element[property] += scroller.delta;+ const change = scroller.element[property] - before;++ if (change) {+ onScroll?.(change);+ frame = requestAnimationFrame(tick);+ }+ };++ return {+ update(event) {+ point = axis === "X" ? event.clientX : event.clientY;+ if (frame === null) {+ frame = requestAnimationFrame(tick);+ }+ },++ stop() {+ stopped = true;+ if (frame !== null) {+ cancelAnimationFrame(frame);+ frame = null;+ }+ },+ };+}++function scrollTarget(anchor, axis, point) {+ const overflowProperty = axis === "X" ? "overflowX" : "overflowY";+ const scrollSize = axis === "X" ? "scrollWidth" : "scrollHeight";+ const clientSize = axis === "X" ? "clientWidth" : "clientHeight";++ for (let element = anchor; element; element = element.parentElement) {+ const overflow = getComputedStyle(element)[overflowProperty];+ if (+ !/(auto|scroll)/.test(overflow) ||+ element[scrollSize] <= element[clientSize]+ ) {+ continue;+ }++ const bounds = element.getBoundingClientRect();+ const start = axis === "X" ? bounds.left : bounds.top;+ const end = axis === "X" ? bounds.right : bounds.bottom;+ const delta = edgeDelta(point, start, end);+ // Let the browser clamp the write at either boundary. This works for both+ // positive and negative RTL scrollLeft conventions; the RAF stops when the+ // applied write produces no change.+ if (delta) {+ return { delta, element };+ }+ }++ return null;+}++function edgeDelta(point, start, end) {+ if (point < start + EDGE_SIZE) {+ return -Math.ceil(+ MAX_STEP * Math.min((start + EDGE_SIZE - point) / EDGE_SIZE, 1)+ );+ }+ if (point > end - EDGE_SIZE) {+ return Math.ceil(+ MAX_STEP * Math.min((point - (end - EDGE_SIZE)) / EDGE_SIZE, 1)+ );+ }+ return 0;+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/editing.js b/frontend/discourse/app/static/prosemirror/lib/table/editing.jsnew file mode 100644index 00000000000..ae9b42da39d--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/editing.js@@ -0,0 +1,239 @@+import { Fragment, Slice } from "prosemirror-model";+import { Plugin, TextSelection } from "prosemirror-state";+import { Decoration, DecorationSet } from "prosemirror-view";+import { currentCell, goToNextCell } from "./commands";+import { cellAround, findTable } from "./grid";+import handleTablePaste from "./paste";+import { fixTables } from "./repair";++export default function tableEditing() {+ return new Plugin({+ props: {+ decorations: selectionDecorations,+ handleKeyDown,+ handlePaste: handleTablePaste,+ handleTextInput: (view, from, to, text) =>+ replaceCrossCellSelection(view, text),+ handleDOMEvents: {+ beforeinput: handleDelete((event) =>+ event.inputType?.startsWith("delete")+ ),+ keydown: handleDelete(+ (event) => event.key === "Backspace" || event.key === "Delete"+ ),+ },+ },++ appendTransaction(transactions, oldState, newState) {+ const changed = transactions.some((tr) => tr.docChanged)+ ? repairableRange(oldState.doc, newState.doc)+ : null;+ let tr = changed+ ? fixTables(newState, null, changed.from, changed.to)+ : null;+ const selection = tr?.selection ?? newState.selection;+ if (+ !(selection instanceof TableTextSelection) &&+ crossCellRange(selection)+ ) {+ tr ??= newState.tr;+ tr.setSelection(+ new TableTextSelection(selection.$anchor, selection.$head)+ );+ }+ return tr;+ },+ });+}++function crossCellRange(selection) {+ if (!(selection instanceof TextSelection) || selection.empty) {+ return null;+ }++ const $fromCell = cellAround(selection.$from);+ const $toCell = cellAround(selection.$to);+ if (!$fromCell || !$toCell || $fromCell.pos === $toCell.pos) {+ return null;+ }++ const table = findTable($fromCell);+ const endTable = findTable($toCell);+ return table && endTable?.pos === table.pos ? table : null;+}++// Preserve native text selection and clipboard slices, but replace only the+// selected content of each cell, including commands that insert nodes directly.+class TableTextSelection extends TextSelection {+ map(doc, mapping) {+ const selection = super.map(doc, mapping);+ return crossCellRange(selection)+ ? new TableTextSelection(selection.$anchor, selection.$head)+ : selection;+ }++ replace(tr, content = Slice.empty) {+ const table = crossCellRange(this);+ const mapFrom = tr.steps.length;+ const ranges = [];+ for (const row of table.grid.rows) {+ for (const cell of row.cells) {+ const start = table.start + cell.offset + 1;+ const from = Math.max(this.from, start);+ const to = Math.min(this.to, start + cell.node.content.size);+ if (from < to) {+ ranges.push({ from, to });+ }+ }+ }+ for (const { from, to } of ranges.reverse()) {+ tr.delete(from, to);+ }+ tr.setSelection(+ TextSelection.create(tr.doc, tr.mapping.slice(mapFrom).map(this.from, -1))+ );+ tr.replaceSelection(content);+ }++ replaceWith(tr, node) {+ this.replace(tr, new Slice(Fragment.from(node), 0, 0));+ }+}++function replaceCrossCellSelection(view, text) {+ if (!view.editable || !(view.state.selection instanceof TableTextSelection)) {+ return false;+ }+ const tr = view.state.tr;+ view.dispatch(+ (text === undefined+ ? tr.deleteSelection()+ : tr.insertText(text)+ ).scrollIntoView()+ );+ return true;+}++function handleDelete(deleting) {+ return (view, event) => {+ if (!deleting(event)) {+ return false;+ }++ const handled = replaceCrossCellSelection(view);+ if (handled) {+ event.preventDefault();+ }+ return handled;+ };+}++/** Returns the changed span that may contain a malformed table. */+function repairableRange(oldDoc, newDoc) {+ const start = oldDoc.content.findDiffStart(newDoc.content);+ if (start === null) {+ return null;+ }++ const end = oldDoc.content.findDiffEnd(newDoc.content);+ if (+ end &&+ changeInsideOneCell(oldDoc, start, end.a) &&+ changeInsideOneCell(newDoc, start, end.b)+ ) {+ return null;+ }++ const size = newDoc.content.size;+ const last = end ? end.b : size;++ // Widened by one either side: `nodesBetween` skips a node that begins or ends+ // exactly on the boundary, and a deletion collapses to a single position.+ return {+ from: Math.max(Math.min(start, last) - 1, 0),+ to: Math.min(Math.max(start, last) + 1, size),+ };+}++function changeInsideOneCell(doc, from, to) {+ const safeFrom = Math.min(from, doc.content.size);+ const safeTo = Math.min(Math.max(to, safeFrom), doc.content.size);+ const $from = cellAround(doc.resolve(safeFrom));+ const $to = cellAround(doc.resolve(safeTo));++ return (+ $from &&+ $to &&+ $from.pos === $to.pos &&+ safeFrom > $from.pos &&+ safeTo < $from.pos + $from.nodeAfter.nodeSize+ );+}++function selectionDecorations(state) {+ const decorations = [];+ const current = currentCell(state);++ // Touch input uses the active table to reveal controls without hover. This+ // class must not change with the selection: a node decoration on the table+ // redraws its whole content, which would rebuild every grip widget inside it.+ if (current) {+ decorations.push(+ Decoration.node(current.pos, current.pos + current.node.nodeSize, {+ class: "is-active",+ })+ );++ const currentRow = current.grid.rows[current.rect.top];+ const rowCell = currentRow?.cells[0];+ const columnCell = current.grid.rows[0]?.cells[current.rect.left];++ if (rowCell) {+ decorations.push(+ Decoration.node(+ current.start + rowCell.offset,+ current.start + rowCell.offset + rowCell.node.nodeSize,+ { class: "is-current-row" }+ )+ );+ }+ if (columnCell) {+ decorations.push(+ Decoration.node(+ current.start + columnCell.offset,+ current.start + columnCell.offset + columnCell.node.nodeSize,+ { class: "is-current-column" }+ )+ );+ }+ }++ return decorations.length+ ? DecorationSet.create(state.doc, decorations)+ : null;+}++function handleKeyDown(view, event) {+ if (!view.editable) {+ return false;+ }++ const { state } = view;++ if (event.key === "Tab") {+ if (!currentCell(state)) {+ return false;+ }+ const handled = goToNextCell(event.shiftKey ? -1 : 1)(+ state,+ view.dispatch,+ view+ );+ if (handled) {+ event.preventDefault();+ }+ return handled;+ }++ return false;+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/grid.js b/frontend/discourse/app/static/prosemirror/lib/table/grid.jsnew file mode 100644index 00000000000..be286364f92--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/grid.js@@ -0,0 +1,158 @@+const CELL_ROLES = ["cell", "header_cell"];++const gridCache = new WeakMap();++export function isCell(node) {+ return CELL_ROLES.includes(node?.type.spec.tableRole);+}++export function isTable(node) {+ return node?.type.spec.tableRole === "table";+}++export function cellType(schema, header) {+ return header ? schema.nodes.table_header_cell : schema.nodes.table_cell;+}++/** Re-creates a cell as `type`, carrying its content and marks over. */+export function copyCell(type, cell, attrs = cell.attrs) {+ return type.create(attrs, cell.content, cell.marks);+}++/**+ * Flattened geometry of a table.+ *+ * Markdown tables never merge cells, so a normalized grid is a plain rectangle+ * and a cell can be addressed by `(row, col)` alone. Offsets are relative to the+ * table's content start, which keeps the result cacheable per node.+ *+ * @param {import("prosemirror-model").Node} table+ * @returns {{+ * rows: { node: import("prosemirror-model").Node, offset: number, header: boolean,+ * cells: { node: import("prosemirror-model").Node, offset: number }[] }[],+ * head: { node: import("prosemirror-model").Node, offset: number } | null,+ * body: { node: import("prosemirror-model").Node, offset: number } | null,+ * width: number,+ * height: number,+ * }}+ */+export function tableGrid(table) {+ const cached = gridCache.get(table);+ if (cached) {+ return cached;+ }++ const rows = [];+ let head = null;+ let body = null;+ let sectionOffset = 0;++ table.forEach((section) => {+ const header = section.type.spec.tableRole === "head";+ if (header) {+ head = { node: section, offset: sectionOffset };+ } else {+ body = { node: section, offset: sectionOffset };+ }++ let rowOffset = sectionOffset + 1;+ section.forEach((row) => {+ const cells = [];+ let cellOffset = rowOffset + 1;+ row.forEach((cell) => {+ cells.push({ node: cell, offset: cellOffset });+ cellOffset += cell.nodeSize;+ });+ rows.push({ node: row, offset: rowOffset, header, cells });+ rowOffset += row.nodeSize;+ });++ sectionOffset += section.nodeSize;+ });++ const grid = {+ rows,+ head,+ body,+ height: rows.length,+ width: rows.reduce((max, row) => Math.max(max, row.cells.length), 0),+ };++ gridCache.set(table, grid);+ return grid;+}++/**+ * The table enclosing a resolved position, if any.+ *+ * @param {import("prosemirror-model").ResolvedPos} $pos+ * @returns {{ node: import("prosemirror-model").Node, pos: number, start: number,+ * grid: ReturnType<typeof tableGrid> } | null}+ */+export function findTable($pos) {+ for (let depth = $pos.depth; depth > 0; depth--) {+ const node = $pos.node(depth);+ if (isTable(node)) {+ return {+ node,+ pos: $pos.before(depth),+ start: $pos.start(depth),+ grid: tableGrid(node),+ };+ }+ }+ return null;+}++/**+ * Resolves to the position *before* the cell enclosing `$pos`.+ *+ * @param {import("prosemirror-model").ResolvedPos} $pos+ * @returns {import("prosemirror-model").ResolvedPos | null}+ */+export function cellAround($pos) {+ for (let depth = $pos.depth; depth > 0; depth--) {+ if (isCell($pos.node(depth))) {+ return $pos.doc.resolve($pos.before(depth));+ }+ }+ return null;+}++export function cellCoords(grid, offset) {+ for (let row = 0; row < grid.rows.length; row++) {+ const col = grid.rows[row].cells.findIndex(+ (cell) => cell.offset === offset+ );+ if (col !== -1) {+ return { row, col };+ }+ }+ return null;+}++export function rowRange(table, row) {+ const { node, offset } = table.grid.rows[row];+ return {+ from: table.start + offset,+ to: table.start + offset + node.nodeSize,+ };+}++export function rectFor(grid, kind, index, through = index) {+ return kind === "row"+ ? { top: index, bottom: through, left: 0, right: grid.width - 1 }+ : { top: 0, bottom: grid.height - 1, left: index, right: through };+}++export function rowTarget(table, row, through = row) {+ return { ...table, rect: rectFor(table.grid, "row", row, through) };+}++export function columnTarget(table, col, through = col) {+ return { ...table, rect: rectFor(table.grid, "column", col, through) };+}++export function cellTarget(table, row, col) {+ return { ...table, rect: { top: row, bottom: row, left: col, right: col } };+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/menu.js b/frontend/discourse/app/static/prosemirror/lib/table/menu.jsnew file mode 100644index 00000000000..f9c73c0f456--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/menu.js@@ -0,0 +1,365 @@+import NodeMenu from "discourse/components/composer/node-menu";+import { i18n } from "discourse-i18n";+import {+ addColumn,+ addHeaderRow,+ addRow,+ ALIGNMENTS,+ clearCellContents,+ columnAlignment,+ currentCell,+ deleteColumn,+ deleteRow,+ deleteTable,+ duplicateColumn,+ duplicateRow,+ moveColumn,+ moveRow,+ runCommand,+ setColumnAlignment,+} from "./commands";+import { cellTarget, columnTarget, rowTarget } from "./grid";++export const TABLE_MENU_IDENTIFIER = "composer-table-menu";++const ALIGNMENT_ICONS = {+ left: "align-left",+ center: "align-center",+ right: "align-right",+};++let triggerSequence = 0;++export async function openGripMenu({ kind, view, pluginParams, grip }, target) {+ if (!view.editable) {+ return;+ }++ const items =+ kind === "row" ? rowMenuItems(view, target) : columnMenuItems(view, target);++ await showMenu(pluginParams, view, grip, items, {+ placement: kind === "row" ? "right-start" : "bottom-start",+ });+}++async function showMenu(pluginParams, view, trigger, items, options) {+ if (!view.editable) {+ return;+ }++ let instance;+ const context = pluginParams.getContext();++ if (trigger instanceof HTMLElement) {+ trigger.id ||= `${TABLE_MENU_IDENTIFIER}-trigger-${++triggerSequence}`;+ trigger.setAttribute("aria-expanded", "false");+ }++ instance = await context.menu.show(trigger, {+ identifier: TABLE_MENU_IDENTIFIER,+ component: NodeMenu,+ placement: options.placement,+ contentRole: "none",+ // The mobile composer sits above the composer dropdown layer, and a sheet+ // is a better touch target than a dropdown anchored to a thin grip.+ modalForMobile: true,+ autofocus: true,+ trapTab: true,+ onClose: () => {+ trigger.setAttribute?.("aria-expanded", "false");+ view.focus();+ },+ data: {+ className: TABLE_MENU_IDENTIFIER,+ items,+ run: (item) => {+ instance?.close();+ if (item.action() && item.announcement) {+ context.a11y.announce(item.announcement);+ }+ },+ },+ });++ if (instance?.expanded) {+ trigger.setAttribute?.("aria-expanded", "true");+ }++ return instance;+}++const ITEMS = {+ insertRowAbove: (view, target) => ({+ icon: "arrow-up",+ label: i18n("composer.table.insert_row_above"),+ className: "composer-table-menu__insert-above",+ announcement: i18n("composer.table.row_inserted"),+ action: () => runCommand(view, addRow(-1, target)),+ }),+ insertHeaderAbove: (view, target) => ({+ icon: "arrow-up",+ label: i18n("composer.table.insert_header_above"),+ className: "composer-table-menu__insert-header-above",+ announcement: i18n("composer.table.header_inserted"),+ action: () => runCommand(view, addHeaderRow(target)),+ }),+ insertRowBelow: (view, target) => ({+ icon: "arrow-down",+ label: i18n("composer.table.insert_row_below"),+ className: "composer-table-menu__insert-below",+ announcement: i18n("composer.table.row_inserted"),+ action: () => runCommand(view, addRow(1, target)),+ }),+ insertColumnLeft: (view, target) => ({+ icon: "arrow-left",+ label: i18n("composer.table.insert_column_left"),+ className: "composer-table-menu__insert-left",+ announcement: i18n("composer.table.column_inserted"),+ action: () => runCommand(view, addColumn(isRtl(view) ? 1 : -1, target)),+ }),+ insertColumnRight: (view, target) => ({+ icon: "arrow-right",+ label: i18n("composer.table.insert_column_right"),+ className: "composer-table-menu__insert-right",+ announcement: i18n("composer.table.column_inserted"),+ action: () => runCommand(view, addColumn(isRtl(view) ? -1 : 1, target)),+ }),+ duplicateRow: (view, target) => ({+ icon: "copy",+ label: i18n("composer.table.duplicate_row"),+ className: "composer-table-menu__duplicate-row",+ announcement: i18n("composer.table.row_duplicated"),+ action: () => runCommand(view, duplicateRow(target)),+ }),+ duplicateColumn: (view, target) => ({+ icon: "copy",+ label: i18n("composer.table.duplicate_column"),+ className: "composer-table-menu__duplicate-column",+ announcement: i18n("composer.table.column_duplicated"),+ action: () => runCommand(view, duplicateColumn(target)),+ }),+ moveRowUp: (view, row, target) => ({+ icon: "arrow-up",+ label: i18n("composer.table.move_row_up"),+ className: "composer-table-menu__move-row-up",+ announcement: i18n("composer.table.row_moved_up"),+ action: () => runCommand(view, moveRow(row, row - 1, target)),+ }),+ moveRowDown: (view, row, target) => ({+ icon: "arrow-down",+ label: i18n("composer.table.move_row_down"),+ className: "composer-table-menu__move-row-down",+ announcement: i18n("composer.table.row_moved_down"),+ action: () => runCommand(view, moveRow(row, row + 2, target)),+ }),+ moveColumnLeft: (view, col, target) => ({+ icon: "arrow-left",+ label: i18n("composer.table.move_column_left"),+ className: "composer-table-menu__move-column-left",+ announcement: i18n("composer.table.column_moved_left"),+ action: () =>+ runCommand(+ view,+ moveColumn(col, isRtl(view) ? col + 2 : col - 1, target)+ ),+ }),+ moveColumnRight: (view, col, target) => ({+ icon: "arrow-right",+ label: i18n("composer.table.move_column_right"),+ className: "composer-table-menu__move-column-right",+ announcement: i18n("composer.table.column_moved_right"),+ action: () =>+ runCommand(+ view,+ moveColumn(col, isRtl(view) ? col - 1 : col + 2, target)+ ),+ }),+ clearContents: (view, target) => ({+ icon: "circle-xmark",+ label: i18n("composer.table.clear_contents"),+ className: "composer-table-menu__clear-contents",+ announcement: i18n("composer.table.contents_cleared"),+ action: () => runCommand(view, clearCellContents(target)),+ }),+ deleteRow: (view, target) => ({+ icon: "trash-can",+ label: i18n("composer.table.delete_row"),+ className: "composer-table-menu__delete-row",+ announcement: i18n("composer.table.row_deleted"),+ dangerous: true,+ action: () => runCommand(view, deleteRow(target)),+ }),+ deleteColumn: (view, target) => ({+ icon: "trash-can",+ label: i18n("composer.table.delete_column"),+ className: "composer-table-menu__delete-column",+ announcement: i18n("composer.table.column_deleted"),+ dangerous: true,+ action: () => runCommand(view, deleteColumn(target)),+ }),+ deleteTable: (view, table) => ({+ icon: "trash-can",+ label: i18n("composer.table.delete_table"),+ className: "composer-table-menu__delete-table",+ announcement: i18n("composer.table.table_deleted"),+ dangerous: true,+ action: () => runCommand(view, deleteTable(table)),+ }),+};++function alignmentItems(view, alignment, target) {+ return ALIGNMENTS.map((value) => ({+ icon: ALIGNMENT_ICONS[value],+ label: i18n(`composer.table.align_${value}`),+ className: `composer-table-menu__align-${value}`,+ active: alignment === value,+ announcement: i18n("composer.table.alignment_changed", {+ alignment: i18n(`composer.table.alignment_${value}`),+ }),+ action: () =>+ runCommand(+ view,+ setColumnAlignment(alignment === value ? null : value, target)+ ),+ }));+}++function insertRowAboveItems(view, table, row, target) {+ return table.grid.rows[row].header+ ? [ITEMS.insertHeaderAbove(view, target)]+ : [ITEMS.insertRowAbove(view, target)];+}++function rowMoveItems(view, table, row, target) {+ return [+ ...(row > 0 ? [ITEMS.moveRowUp(view, row, target)] : []),+ ...(row < table.grid.height - 1+ ? [ITEMS.moveRowDown(view, row, target)]+ : []),+ ];+}++function columnMoveItems(view, table, col, target) {+ const last = table.grid.width - 1;+ const rtl = isRtl(view);++ return [+ ...((rtl ? col < last : col > 0)+ ? [ITEMS.moveColumnLeft(view, col, target)]+ : []),+ ...((rtl ? col > 0 : col < last)+ ? [ITEMS.moveColumnRight(view, col, target)]+ : []),+ ];+}++function rowMenuItems(view, { table, row }) {+ const target = rowTarget(table, row);++ return [+ ...insertRowAboveItems(view, table, row, target),+ ITEMS.insertRowBelow(view, target),+ ITEMS.duplicateRow(view, target),+ ...rowMoveItems(view, table, row, target),+ ITEMS.clearContents(view, target),+ { divider: true },+ ITEMS.deleteRow(view, target),+ ];+}++function columnMenuItems(view, { table, col }) {+ const target = columnTarget(table, col);++ return [+ ITEMS.insertColumnLeft(view, target),+ ITEMS.insertColumnRight(view, target),+ ITEMS.duplicateColumn(view, target),+ ...columnMoveItems(view, table, col, target),+ { divider: true },+ ...alignmentItems(view, columnAlignment(table, col), target),+ { divider: true },+ ITEMS.clearContents(view, target),+ ITEMS.deleteColumn(view, target),+ ];+}++// Everything that applies to the cell the caret is in. This is the only menu+// reachable without a pointer, so it has to cover both axes.+export function cellMenuItems(view, { table, row, col }) {+ const cell = cellTarget(table, row, col);+ const column = columnTarget(table, col);+ const rowBand = rowTarget(table, row);++ return [+ ...insertRowAboveItems(view, table, row, rowBand),+ ITEMS.insertRowBelow(view, rowBand),+ ITEMS.insertColumnLeft(view, column),+ ITEMS.insertColumnRight(view, column),+ { divider: true },+ ITEMS.duplicateRow(view, rowBand),+ ITEMS.duplicateColumn(view, column),+ ...rowMoveItems(view, table, row, rowBand),+ ...columnMoveItems(view, table, col, column),+ { divider: true },+ ...alignmentItems(view, columnAlignment(table, col), column),+ { divider: true },+ ITEMS.clearContents(view, cell),+ ITEMS.deleteRow(view, rowBand),+ ITEMS.deleteColumn(view, column),+ ITEMS.deleteTable(view, table),+ ];+}++function isRtl(view) {+ return getComputedStyle(view.dom).direction === "rtl";+}++/**+ * What a context menu opened right now would act on.+ *+ * @returns {{ table: object, row: number, col: number } | null}+ */+export function menuTargetFor(state) {+ const table = currentCell(state);+ if (!table) {+ return null;+ }++ return { table, row: table.rect.top, col: table.rect.left };+}++// Shift+F10 and the ContextMenu key are the platform gesture for "open the menu+// for what is focused", but macOS has neither a ContextMenu key nor F-keys that+// reach the page by default, so Alt+Enter carries the same meaning there.+function opensTableMenu(event) {+ return (+ event.key === "ContextMenu" ||+ (event.key === "F10" && event.shiftKey) ||+ (event.key === "Enter" && event.altKey && !event.ctrlKey && !event.metaKey)+ );+}++export function handleContextMenuKey(view, event, pluginParams) {+ if (!view.editable || !opensTableMenu(event)) {+ return false;+ }++ const target = menuTargetFor(view.state);+ if (!target) {+ return false;+ }++ event.preventDefault();++ const { table, row, col } = target;+ const anchor =+ view.nodeDOM(table.start + table.grid.rows[row].cells[col].offset) ??+ view.dom;++ showMenu(pluginParams, view, anchor, cellMenuItems(view, target), {+ placement: "bottom-start",+ });++ return true;+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/node-view.js b/frontend/discourse/app/static/prosemirror/lib/table/node-view.jsnew file mode 100644index 00000000000..ecc9d2b8abb--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/node-view.js@@ -0,0 +1,513 @@+import { DOMSerializer } from "prosemirror-model";+import { iconElement } from "discourse/lib/icon-library";+import { i18n } from "discourse-i18n";+import {+ addColumn,+ addRow,+ deleteColumn,+ deleteRow,+ emptyTrailingColumns,+ emptyTrailingRows,+ runCommand,+} from "./commands";+import dragAutoscroll from "./drag-autoscroll";+import { columnTarget, isTable, rowTarget, tableGrid } from "./grid";+import { TABLE_MENU_IDENTIFIER } from "./menu";+import trackPointer from "./track-pointer";++const APPEND_DRAG_THRESHOLD = 4;+const APPEND_DRAG_MAX = { column: 8, row: 12 };+const APPEND_DRAG_STEP_EM = { column: 5, row: 2 };+const TOUCH_SCROLL_THRESHOLD = 8;++const AXES = {+ column: {+ target: columnTarget,+ add: addColumn,+ remove: deleteColumn,+ emptyTrailing: emptyTrailingColumns,+ },+ row: {+ target: rowTarget,+ add: addRow,+ remove: deleteRow,+ emptyTrailing: emptyTrailingRows,+ },+};++export class TableCellView {+ #node;++ constructor(node) {+ this.#node = node;+ const { dom, contentDOM } = DOMSerializer.renderSpec(+ document,+ node.type.spec.toDOM(node)+ );+ this.dom = dom;+ this.contentDOM = contentDOM;+ }++ ignoreMutation(mutation) {+ return (+ mutation.target === this.dom &&+ mutation.type === "attributes" &&+ (mutation.attributeName === "class" ||+ (mutation.attributeName === "style" &&+ this.dom.style.textAlign === (this.#node.attrs.alignment || "")))+ );+ }+}++/**+ * @param {import("discourse/lib/composer/rich-editor-extensions").PluginParams} pluginParams+ * @returns {new (...args: Parameters<import("prosemirror-view").NodeViewConstructor>) => import("prosemirror-view").NodeView}+ */+export function buildTableNodeView(pluginParams) {+ return class TableNodeView {+ #hovered = null;+ #stopAppendDrag = null;+ #stopTouchScroll = null;++ #clearPointer = () => {+ this.#hovered = null;+ this.#showHandlesFor(null);+ };++ #trackPointer = (event) => {+ if (!this.view.editable) {+ this.#clearPointer();+ return;+ }++ // A reorder owns the handle it started from; re-targeting mid-drag would+ // take it out from under the pointer.+ if (this.inner.classList.contains("is-reordering")) {+ return;+ }++ const cell = event.target.closest?.("th, td");+ if (!cell || !this.contentDOM.contains(cell) || cell === this.#hovered) {+ return;+ }++ this.#hovered = cell;+ this.#showHandlesFor(cell);+ };++ #trackTouchScroll = (startEvent) => {+ if (+ startEvent.pointerType !== "touch" ||+ !startEvent.isPrimary ||+ startEvent.button !== 0 ||+ startEvent.target.closest?.(".composer-table__grip")+ ) {+ return;+ }++ this.#stopTouchScroll?.();++ const { clientX, clientY } = startEvent;+ const initialScroll = this.dom.scrollLeft;+ let scrolling = false;++ const stop = () => {+ this.dom.classList.remove("is-panning");+ stopTracking();+ this.#stopTouchScroll = null;+ };++ const move = (event) => {+ const horizontal = event.clientX - clientX;+ const vertical = event.clientY - clientY;+ if (+ !scrolling &&+ (Math.abs(horizontal) < TOUCH_SCROLL_THRESHOLD ||+ Math.abs(horizontal) <= Math.abs(vertical))+ ) {+ return;+ }++ scrolling = true;+ event.preventDefault();+ this.dom.classList.add("is-panning");+ this.dom.scrollLeft = initialScroll - horizontal;+ };++ const stopTracking = trackPointer(startEvent, move, stop);+ this.#stopTouchScroll = stop;+ };++ constructor(node, view, getPos) {+ this.node = node;+ this.view = view;+ this.getPos = getPos;++ this.dom = document.createElement("div");+ this.dom.className = "md-table composer-table";++ this.inner = document.createElement("div");+ this.inner.className = "composer-table__inner";+ this.dom.appendChild(this.inner);++ this.contentDOM = document.createElement("table");+ this.inner.appendChild(this.contentDOM);++ this.inner.appendChild(+ this.#appendButton("column", "composer.table.add_column")+ );+ this.inner.appendChild(+ this.#appendButton("row", "composer.table.add_row")+ );++ this.dropIndicator = document.createElement("div");+ this.dropIndicator.className = "composer-table__drop-indicator";+ this.inner.appendChild(this.dropIndicator);++ this.appendGhost = document.createElement("div");+ this.appendGhost.className = "composer-table__ghost";+ this.inner.appendChild(this.appendGhost);++ // Only the pointer's own row and column show a handle, so the table stays+ // quiet while it is being typed in. Done in the DOM rather than through a+ // transaction: hovering a cell is not a document change.+ this.dom.addEventListener("mousemove", this.#trackPointer);+ this.dom.addEventListener("mouseleave", this.#clearPointer);+ this.contentDOM.addEventListener("pointerdown", this.#trackTouchScroll);+ }++ destroy() {+ this.#stopAppendDrag?.();+ this.#stopTouchScroll?.();+ this.dom.removeEventListener("mousemove", this.#trackPointer);+ this.dom.removeEventListener("mouseleave", this.#clearPointer);+ this.contentDOM.removeEventListener(+ "pointerdown",+ this.#trackTouchScroll+ );+ }++ update(node) {+ if (node.type !== this.node.type) {+ return false;+ }+ this.#stopAppendDrag?.();+ this.node = node;+ return true;+ }++ stopEvent(event) {+ return !!event.target.closest?.(+ `.composer-table__append, [data-identifier="${TABLE_MENU_IDENTIFIER}"]`+ );+ }++ ignoreMutation(mutation) {+ return (+ mutation.type !== "selection" &&+ !this.contentDOM.contains(mutation.target)+ );+ }++ #resize(kind, delta) {+ if (!this.view.editable || !delta) {+ return;+ }++ const table = this.#table();+ if (!table) {+ return;+ }++ const axis = AXES[kind];+ if (delta < 0) {+ delta = -Math.min(-delta, axis.emptyTrailing(table.grid));+ if (!delta) {+ return;+ }+ }+ const size = kind === "column" ? table.grid.width : table.grid.height;+ const target = axis.target(+ table,+ delta > 0 ? size - 1 : size + delta,+ size - 1+ );++ const changed = runCommand(+ this.view,+ delta > 0 ? axis.add(1, target, delta) : axis.remove(target)+ );+ if (changed) {+ this.#announceChange(kind, delta);+ }+ }++ #appendButton(kind, labelKey) {+ let dragged = false;+ const button = this.#button(`append --${kind}`, labelKey, (event) => {+ if (dragged && event.detail !== 0) {+ dragged = false;+ return;+ }++ this.#resize(kind, 1);+ });++ button.appendChild(iconElement("plus"));++ const count = document.createElement("span");+ count.className = "composer-table__append-count";+ count.ariaHidden = "true";+ button.appendChild(count);++ button.addEventListener("pointerdown", (event) =>+ this.#trackAppend(event, kind, button, (value) => (dragged = value))+ );+ return button;+ }++ #button(className, labelKey, onClick) {+ const button = document.createElement("button");+ button.type = "button";+ button.className = `composer-table__${className}`;+ button.contentEditable = "false";+ button.tabIndex = -1;+ button.setAttribute("aria-label", i18n(labelKey));+ // Click preserves synthesized activation; mousedown only holds the caret.+ button.addEventListener("mousedown", (event) => event.preventDefault());+ button.addEventListener("click", onClick);+ return button;+ }++ #showGhost(kind, delta, step, bounds, rtl = false) {+ const ghost = this.appendGhost;++ ghost.className = "composer-table__ghost";+ ghost.removeAttribute("style");+ this.inner.style.paddingInlineEnd = "";+ this.inner.style.paddingBlockEnd = "";++ if (!delta) {+ return;+ }++ const adding = delta > 0;+ const count = Math.abs(delta);+ const span = adding ? count * step : this.#trailingExtent(kind, count);++ ghost.classList.add(+ "--visible",+ `--${kind}`,+ adding ? "--add" : "--remove"+ );+ ghost.style.setProperty("--ghost-step", `${span / count}px`);++ if (kind === "column") {+ if (adding) {+ this.inner.style.paddingInlineEnd = `${span}px`;+ }+ // Adding draws just past the edge, removing over the doomed columns.+ const offset = adding ? bounds.width : bounds.width - span;+ Object.assign(ghost.style, {+ top: "0px",+ left: `${this.contentDOM.offsetLeft + (rtl ? bounds.width - offset - span : offset)}px`,+ width: `${span}px`,+ height: `${bounds.height}px`,+ });+ } else {+ if (adding) {+ this.inner.style.paddingBlockEnd = `${span}px`;+ }+ Object.assign(ghost.style, {+ top: `${adding ? bounds.height : bounds.height - span}px`,+ left: `${this.contentDOM.offsetLeft}px`,+ width: `${bounds.width}px`,+ height: `${span}px`,+ });+ }+ }++ #trailingExtent(kind, count) {+ const rows = [...this.contentDOM.rows];++ if (kind === "row") {+ return rows+ .slice(-count)+ .reduce(+ (total, row) => total + row.getBoundingClientRect().height,+ 0+ );+ }++ return [...(rows[0]?.cells ?? [])]+ .slice(-count)+ .reduce((total, cell) => total + cell.getBoundingClientRect().width, 0);+ }++ #showHandlesFor(cell) {+ for (const grip of this.contentDOM.querySelectorAll(+ ".composer-table__grip"+ )) {+ grip.classList.remove("is-visible");+ }++ if (!cell) {+ return;+ }++ const row = cell.parentElement;+ const column = [...row.cells].indexOf(cell);++ row.cells[0]+ ?.querySelector(".composer-table__grip.--row")+ ?.classList.add("is-visible");+ this.contentDOM.rows[0]?.cells[column]+ ?.querySelector(".composer-table__grip.--column")+ ?.classList.add("is-visible");+ }++ #table() {+ const pos = this.getPos();+ if (pos === undefined) {+ return null;+ }++ const node = this.view.state.doc.nodeAt(pos);+ if (!isTable(node)) {+ return null;+ }++ return { node, pos, start: pos + 1, grid: tableGrid(node) };+ }++ #announceChange(kind, delta) {+ const change = delta > 0 ? "added" : "removed";+ pluginParams+ .getContext()+ .a11y.announce(+ i18n(`composer.table.${kind}s_${change}`, { count: Math.abs(delta) })+ );+ }++ #trackAppend(startEvent, kind, button, setDragged) {+ if (!this.view.editable || startEvent.button !== 0) {+ return;+ }++ startEvent.preventDefault();++ // A drag that ends off the button gets no click, so the suppression flag+ // has to be cleared by the next press rather than by the click it eats.+ setDragged(false);+ this.#stopAppendDrag?.();++ const table = this.#table();+ if (!table) {+ return;+ }++ const column = kind === "column";+ const initialDoc = this.view.state.doc;+ const origin = column ? startEvent.clientX : startEvent.clientY;++ const bounds = this.contentDOM.getBoundingClientRect();+ const style = getComputedStyle(this.contentDOM);+ const measuredStep = column+ ? bounds.width / table.grid.width+ : bounds.height / table.grid.height;+ const fontSize = parseFloat(style.fontSize) || 16;+ const step = Math.max(measuredStep, fontSize * APPEND_DRAG_STEP_EM[kind]);+ const rtl = style.direction === "rtl";+ const direction = column && rtl ? -1 : 1;+ const removable = AXES[kind].emptyTrailing(table.grid);++ const countElement = button.querySelector(+ ".composer-table__append-count"+ );++ let dragging = false;+ let delta = 0;+ let current = origin;+ let scrollDistance = 0;++ const reset = () => {+ button.classList.remove("is-appending", "is-removing");+ countElement.textContent = "";+ this.#showGhost(kind, 0, step, bounds);+ };++ const updateDelta = () => {+ const distance = (current - origin) * direction + scrollDistance;++ if (!dragging && Math.abs(distance) < APPEND_DRAG_THRESHOLD) {+ return false;+ }++ if (!dragging) {+ dragging = true;+ setDragged(true);+ }++ const steps = Math.min(+ Math.round(Math.abs(distance) / Math.max(step, 1)),+ APPEND_DRAG_MAX[kind]+ );+ delta = distance > 0 ? steps : -Math.min(steps, removable);++ if (!delta) {+ reset();+ return true;+ }++ button.classList.toggle("is-appending", delta > 0);+ button.classList.toggle("is-removing", delta < 0);+ countElement.textContent = delta > 0 ? `+${delta}` : `\u2212${-delta}`;+ this.#showGhost(kind, delta, step, bounds, rtl);+ return true;+ };++ const autoscroll = dragAutoscroll(+ button.closest(".composer-table"),+ column ? "X" : "Y",+ (change) => {+ scrollDistance += change * direction;+ updateDelta();+ }+ );++ const move = (event) => {+ current = column ? event.clientX : event.clientY;+ if (!updateDelta()) {+ return;+ }++ event.preventDefault();+ autoscroll.update(event);+ };++ const finish = (event) => {+ this.#stopAppendDrag?.();++ if (+ event.type === "pointercancel" ||+ this.view.state.doc !== initialDoc ||+ !this.view.editable+ ) {+ setDragged(false);+ return;+ }++ this.#resize(kind, delta);+ };++ this.#stopAppendDrag = () => {+ reset();+ autoscroll.stop();+ stopTracking();+ this.#stopAppendDrag = null;+ };++ const stopTracking = trackPointer(startEvent, move, finish);+ }+ };+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/paste.js b/frontend/discourse/app/static/prosemirror/lib/table/paste.jsnew file mode 100644index 00000000000..652db9b1423--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/paste.js@@ -0,0 +1,90 @@+import { Fragment } from "prosemirror-model";+import { currentCell, selectCell } from "./commands";+import { cellType, copyCell, isTable, tableGrid } from "./grid";++// A table pasted into a cell can't nest, so its cells are written into the grid+// starting at the target cell, growing the table when the paste overflows it.+export default function handlePaste(view, event, slice) {+ if (!view.editable) {+ return false;+ }+ const table = currentCell(view.state);+ if (!table) {+ return false;+ }++ const rows = pastedRows(slice);+ if (!rows) {+ return false;+ }++ const { state } = view;+ const schema = state.schema;+ const { top, left } = table.rect;+ const width = Math.max(+ table.grid.width,+ left + Math.max(...rows.map((row) => row.length))+ );+ const height = Math.max(table.grid.height, top + rows.length);++ const built = [];+ for (let row = 0; row < height; row++) {+ const source = table.grid.rows[row];+ const type = cellType(schema, row === 0 && !!table.grid.head);+ const cells = [];++ for (let col = 0; col < width; col++) {+ const alignment =+ table.grid.rows[0]?.cells[col]?.node.attrs.alignment ?? null;+ const incoming =+ col >= left && row >= top ? rows[row - top]?.[col - left] : undefined;+ const existing = source?.cells[col]?.node;++ if (incoming) {+ cells.push(copyCell(type, incoming, { alignment }));+ } else if (existing) {+ cells.push(copyCell(type, existing));+ } else {+ cells.push(type.createAndFill({ alignment }));+ }+ }++ built.push(schema.nodes.table_row.create(null, Fragment.from(cells)));+ }++ const sections = [];+ if (table.grid.head) {+ sections.push(schema.nodes.table_head.create(null, built[0]));+ }+ sections.push(+ schema.nodes.table_body.create(+ null,+ Fragment.from(built.slice(table.grid.head ? 1 : 0))+ )+ );++ view.dispatch(+ selectCell(+ state.tr.replaceWith(+ table.pos,+ table.pos + table.node.nodeSize,+ schema.nodes.table.create(table.node.attrs, Fragment.from(sections))+ ),+ table.pos,+ top,+ left+ )+ .setMeta("paste", true)+ .setMeta("uiEvent", "paste")+ );+ return true;+}++function pastedRows(slice) {+ const table = slice.content.childCount === 1 && slice.content.firstChild;+ if (!table || !isTable(table)) {+ return null;+ }++ return tableGrid(table).rows.map((row) => row.cells.map((cell) => cell.node));+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/repair.js b/frontend/discourse/app/static/prosemirror/lib/table/repair.jsnew file mode 100644index 00000000000..ca8f348e511--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/repair.js@@ -0,0 +1,78 @@+import { Fragment } from "prosemirror-model";+import { cellType, isTable, tableGrid } from "./grid";++/** Repairs malformed table structures within a document range. */+export function fixTables(state, tr, from = 0, to = state.doc.content.size) {+ const tables = [];+ state.doc.nodesBetween(from, to, (node, pos) => {+ if (!node.isBlock) {+ return false;+ }+ if (isTable(node)) {+ tables.push({ node, pos });+ return false;+ }+ });++ let result = tr;+ // Bottom-up, so positions read from the untouched document stay valid.+ for (let index = tables.length - 1; index >= 0; index--) {+ result = fixTable(state, tables[index], result);+ }++ return result;+}++function fixTable(state, { node, pos }, tr) {+ const schema = state.schema;+ const grid = tableGrid(node);+ const start = pos + 1;+ let result = tr;++ if (!grid.height) {+ result ??= state.tr;+ result.replaceWith(+ pos,+ pos + node.nodeSize,+ schema.nodes.paragraph.createAndFill()+ );+ return result;+ }++ for (const row of grid.rows) {+ const expected = cellType(schema, row.header);++ for (const cell of row.cells) {+ if (cell.node.type !== expected) {+ result ??= state.tr;+ result.setNodeMarkup(start + cell.offset, expected, cell.node.attrs);+ }+ }+ }++ // Padding is applied bottom-up: cell type fixes above never move positions.+ for (let index = grid.rows.length - 1; index >= 0; index--) {+ const row = grid.rows[index];+ const missing = grid.width - row.cells.length;+ if (missing <= 0) {+ continue;+ }++ const type = cellType(schema, row.header);+ const cells = Array.from({ length: missing }, (_, offset) =>+ type.createAndFill({+ alignment:+ grid.rows[0]?.cells[row.cells.length + offset]?.node.attrs+ .alignment ?? null,+ })+ );++ result ??= state.tr;+ result.insert(+ start + row.offset + row.node.nodeSize - 1,+ Fragment.from(cells)+ );+ }++ return result;+}diff --git a/frontend/discourse/app/static/prosemirror/lib/table/track-pointer.js b/frontend/discourse/app/static/prosemirror/lib/table/track-pointer.jsnew file mode 100644index 00000000000..cb15aaf9256--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/table/track-pointer.js@@ -0,0 +1,11 @@+export default function trackPointer(startEvent, move, finish) {+ const events = ["pointermove", "pointerup", "pointercancel"];+ const handle = (event) => {+ if (event.pointerId === startEvent.pointerId) {+ (event.type === "pointermove" ? move : finish)(event);+ }+ };+ events.forEach((type) => document.addEventListener(type, handle));+ return () =>+ events.forEach((type) => document.removeEventListener(type, handle));+}diff --git a/frontend/discourse/tests/helpers/rich-editor-helper.gjs b/frontend/discourse/tests/helpers/rich-editor-helper.gjsindex ab27310d0ea..145aaa05a2f 100644--- a/frontend/discourse/tests/helpers/rich-editor-helper.gjs+++ b/frontend/discourse/tests/helpers/rich-editor-helper.gjs@@ -1,9 +1,16 @@import { tracked } from "@glimmer/tracking";import { click, render, settled, waitFor } from "@ember/test-helpers";+import ModalContainer from "discourse/components/modal-container";+import DMenus from "discourse/float-kit/components/d-menus";import DEditor from "discourse/ui-kit/d-editor";export async function setupRichEditor(assert, markdown, opts = {}) {- const { multiToggle = false, markdownOptions } = opts;+ const {+ disabled = false,+ multiToggle = false,+ markdownOptions,+ withMenus = false,+ } = opts;const self = new (class {@tracked value = markdown;@tracked view;@@ -15,11 +22,16 @@ export async function setupRichEditor(assert, markdown, opts = {}) {await render(<template><DEditor+ @disabled={{disabled}}@markdownOptions={{markdownOptions}}@onSetup={{handleSetup}}@processPreview={{false}}@value={{self.value}}/>+ {{#if withMenus}}+ <DMenus />+ <ModalContainer />+ {{/if}}</template>);diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/table-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/table-test.jsindex 1be040be44d..7315d9ec420 100644--- a/frontend/discourse/tests/integration/components/prosemirror-editor/table-test.js+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/table-test.js@@ -1,6 +1,210 @@+import {+ click,+ find,+ findAll,+ settled,+ waitFor,+ waitUntil,+} from "@ember/test-helpers";+import { undo } from "prosemirror-history";+import { TextSelection } from "prosemirror-state";import { module, test } from "qunit";+import { forceMobile } from "discourse/lib/mobile";+import {+ addColumn,+ addHeaderRow,+ addRow,+ deleteColumn,+ deleteRow,+ deleteTable,+ duplicateColumn,+ duplicateRow,+ goToNextCell,+ moveColumn,+ moveRow,+ setColumnAlignment,+} from "discourse/static/prosemirror/lib/table/commands";+import { tableGrid } from "discourse/static/prosemirror/lib/table/grid";+import {+ cellMenuItems,+ menuTargetFor,+} from "discourse/static/prosemirror/lib/table/menu";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";++const TABLE = `| h1 | h2 | h3 |\n| --- | --- | --- |\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |`;+const UNEVEN_TABLE = `| short | a much longer heading | x |\n| --- | --- | --- |\n| one | a much longer value | three |`;++function locateTable(view) {+ let node = null;+ let pos = null;+ view.state.doc.descendants((child, at) => {+ if (child.type.name === "table") {+ node = child;+ pos = at;+ return false;+ }+ });+ return { node, pos, start: pos + 1, grid: tableGrid(node) };+}++function cellPos(view, row, col) {+ const { start, grid } = locateTable(view);+ return start + grid.rows[row].cells[col].offset;+}++async function selectCell(view, row, col) {+ const pos = cellPos(view, row, col);+ view.dispatch(+ view.state.tr.setSelection(TextSelection.create(view.state.doc, pos + 1))+ );+ await settled();+}++async function apply(view, command) {+ command(view.state, view.dispatch, view);+ await settled();+}++async function hoverCell(cell) {+ const rect = cell.getBoundingClientRect();+ cell.dispatchEvent(+ new MouseEvent("mousemove", {+ bubbles: true,+ clientX: rect.left + 2,+ clientY: rect.top + 2,+ })+ );+ await settled();+}++async function pressKey(view, key, modifiers = {}) {+ const event = new KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ ...modifiers,+ });+ view.dom.dispatchEvent(event);+ await settled();+ return event;+}++async function pressGrip(+ grip,+ {+ activate = false,+ click: withClick = activate,+ moveBy = 0,+ pointerType = "mouse",+ } = {}+) {+ const rect = grip.getBoundingClientRect();+ const at = {+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 2,+ pointerType,+ isPrimary: true,+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height / 2,+ };++ grip.dispatchEvent(new PointerEvent("pointerdown", at));+ const end = { ...at, clientY: at.clientY + moveBy };+ if (moveBy) {+ document.dispatchEvent(new PointerEvent("pointermove", end));+ }+ document.dispatchEvent(+ new PointerEvent(activate || withClick ? "pointerup" : "pointercancel", end)+ );+ if (withClick) {+ grip.dispatchEvent(new MouseEvent("click", { ...end, detail: 1 }));+ }+ await settled();+}++async function dragGrip(grip, target, beforeDrop) {+ const from = grip.getBoundingClientRect();+ const to = target.getBoundingClientRect();+ const at = (x, y) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 1,+ isPrimary: true,+ clientX: x,+ clientY: y,+ });++ grip.dispatchEvent(+ new PointerEvent("pointerdown", at(from.left + 1, from.top + 1))+ );+ document.dispatchEvent(+ new PointerEvent(+ "pointermove",+ at(to.left + to.width / 2 + 1, to.top + to.height / 2 + 1)+ )+ );+ await settled();+ await beforeDrop?.();+ document.dispatchEvent(+ new PointerEvent(+ "pointerup",+ at(to.left + to.width / 2 + 1, to.top + to.height / 2 + 1)+ )+ );+ // The browser sends this after a short drag; a drag must not also open a menu.+ grip.dispatchEvent(+ new MouseEvent("click", { ...at(to.left, to.top), detail: 1 })+ );+ await settled();+}++async function dragAppend(button, distance) {+ const rect = button.getBoundingClientRect();+ const column = button.classList.contains("--column");+ const start = {+ x: rect.left + rect.width / 2,+ y: rect.top + rect.height / 2,+ };+ const at = (x, y) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 3,+ isPrimary: true,+ clientX: x,+ clientY: y,+ });+ const end = column+ ? { x: start.x + distance, y: start.y }+ : { x: start.x, y: start.y + distance };++ button.dispatchEvent(new PointerEvent("pointerdown", at(start.x, start.y)));+ document.dispatchEvent(new PointerEvent("pointermove", at(end.x, end.y)));+ document.dispatchEvent(new PointerEvent("pointerup", at(end.x, end.y)));+ button.dispatchEvent(+ new MouseEvent("click", { ...at(end.x, end.y), detail: 1 })+ );+ await settled();+}++// The editor's table carries its own chrome, which is not part of the document.+function tableMarkup() {+ const table = find(".ProseMirror .composer-table table").cloneNode(true);+ table.querySelectorAll(".composer-table__grip").forEach((el) => el.remove());+ table+ .querySelectorAll(+ ".is-current-row, .is-current-column, .is-structural-target, .--axis-row, .--axis-column"+ )+ .forEach((cell) => cell.removeAttribute("class"));+ return table.outerHTML;+}module("Integration | Component | prosemirror-editor - table extension",@@ -10,32 +214,1741 @@ module(Object.entries({"basic table": ["| Header 1 | Header 2 |\n| --- | --- |\n| Cell 1 | Cell 2 |",- `<div class="md-table"><table><thead><tr><th>Header 1</th><th>Header 2</th></tr></thead><tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table></div>`,+ `<table><thead><tr><th>Header 1</th><th>Header 2</th></tr></thead><tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table>`,`| Header 1 | Header 2 |\n|----|----|\n| Cell 1 | Cell 2 |\n\n`,],"table with alignment": [`| Left | Center | Right |\n| :--- | :---: | ---: |\n| A | B | C |`,- `<div class="md-table"><table><thead><tr><th style="text-align: left;">Left</th><th style="text-align: center;">Center</th><th style="text-align: right;">Right</th></tr></thead><tbody><tr><td style="text-align: left;">A</td><td style="text-align: center;">B</td><td style="text-align: right;">C</td></tr></tbody></table></div>`,+ `<table><thead><tr><th style="text-align: left;">Left</th><th style="text-align: center;">Center</th><th style="text-align: right;">Right</th></tr></thead><tbody><tr><td style="text-align: left;">A</td><td style="text-align: center;">B</td><td style="text-align: right;">C</td></tr></tbody></table>`,`| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |\n\n`,],- "table within quotes": [- `> \n> | Header 1 | Header 2 |\n> | --- | --- |\n> | Cell 1 | Cell 2 |\n`,- `<blockquote><div class="md-table"><table><thead><tr><th>Header 1</th><th>Header 2</th></tr></thead><tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table></div></blockquote>`,- `> \n> | Header 1 | Header 2 |\n> |----|----|\n> | Cell 1 | Cell 2 |\n\n`,- ],"table with br in cells": [`| Line1<br>Line2 | Cell 2 |\n| --- | --- |\n| Cell 3 | Cell 4 |`,- `<div class="md-table"><table><thead><tr><th>Line1<br>Line2</th><th>Cell 2</th></tr></thead><tbody><tr><td>Cell 3</td><td>Cell 4</td></tr></tbody></table></div>`,+ `<table><thead><tr><th>Line1<br>Line2</th><th>Cell 2</th></tr></thead><tbody><tr><td>Cell 3</td><td>Cell 4</td></tr></tbody></table>`,`| Line1<br>Line2 | Cell 2 |\n|----|----|\n| Cell 3 | Cell 4 |\n\n`,],"table with pipes inside a link": [`| Link | Note |\n| --- | --- |\n| [x|y](https://example.com "title|value") | ok |`,- `<div class="md-table"><table><thead><tr><th>Link</th><th>Note</th></tr></thead><tbody><tr><td><a href="https://example.com" title="title|value">x|y</a></td><td>ok</td></tr></tbody></table></div>`,+ `<table><thead><tr><th>Link</th><th>Note</th></tr></thead><tbody><tr><td><a href="https://example.com" title="title|value">x|y</a></td><td>ok</td></tr></tbody></table>`,`| Link | Note |\n|----|----|\n| [x\\|y](https://example.com "title\\|value") | ok |\n\n`,],}).forEach(([name, [markdown, html, expectedMarkdown]]) => {test(name, async function (assert) {- await testMarkdown(assert, markdown, html, expectedMarkdown);+ await testMarkdown(+ assert,+ markdown,+ (a) =>+ a.strictEqual(tableMarkup(), html, "table markup should match"),+ expectedMarkdown+ );+ });+ });++ test("table within quotes", async function (assert) {+ await testMarkdown(+ assert,+ `> \n> | Header 1 | Header 2 |\n> | --- | --- |\n> | Cell 1 | Cell 2 |\n`,+ (a) => {+ a.dom(".ProseMirror blockquote .composer-table table").exists();+ a.strictEqual(+ tableMarkup(),+ `<table><thead><tr><th>Header 1</th><th>Header 2</th></tr></thead><tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table>`+ );+ },+ `> \n> | Header 1 | Header 2 |\n> |----|----|\n> | Cell 1 | Cell 2 |\n\n`+ );+ });++ test("renders a grip for every row and column", async function (assert) {+ await setupRichEditor(assert, TABLE);++ assert.dom(".composer-table__grip.--column").exists({ count: 3 });+ assert.dom(".composer-table__grip.--row").exists({ count: 3 });+ assert.dom(".composer-table__append.--column").exists();+ assert.dom(".composer-table__append.--row").exists();+ });++ test("adds and deletes columns", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 1);+ await apply(view, addColumn(1));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | | h3 |\n|----|----|----|----|\n| a1 | a2 | | a3 |\n| b1 | b2 | | b3 |\n\n`,+ "inserts an empty column after the selected one"+ );++ await selectCell(view, 1, 2);+ await apply(view, deleteColumn());++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "removes the column again"+ );+ });++ test("adds and deletes rows", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 0);+ await apply(view, addRow(-1));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| | | |\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "inserts an empty row above the selected one"+ );++ await selectCell(view, 1, 0);+ await apply(view, deleteRow());++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "removes the row again"+ );+ });++ test("deleting the header row promotes the next one", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ await apply(view, deleteRow());++ assert.strictEqual(+ editor.value,+ `| a1 | a2 | a3 |\n|----|----|----|\n| b1 | b2 | b3 |\n\n`,+ "a markdown table always keeps a header row"+ );+ });++ test("alignment survives a header promotion", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ `| h1 | h2 |\n| --- | :---: |\n| a1 | a2 |\n| b1 | b2 |`+ );+ const { view } = editor;++ await selectCell(view, 0, 0);+ await apply(view, deleteRow());++ assert.strictEqual(+ editor.value,+ `| a1 | a2 |\n|----|:---:|\n| b1 | b2 |\n\n`,+ "the promoted row carries the column's alignment"+ );+ });++ test("alignment travels with a moved column", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ `| h1 | h2 |\n| --- | :---: |\n| a1 | a2 |`+ );+ const { view } = editor;++ await selectCell(view, 1, 0);+ await apply(view, moveColumn(1, 0));++ assert.strictEqual(+ editor.value,+ `| h2 | h1 |\n|:---:|----|\n| a2 | a1 |\n\n`+ );+ });++ test("sets alignment for the whole column", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 2, 1);+ await apply(view, setColumnAlignment("center"));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|:---:|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`+ );++ assert+ .dom(+ ".ProseMirror .composer-table tbody tr:first-child td:nth-child(2)"+ )+ .hasStyle({ textAlign: "center" }, "body cells follow the column");+ });++ test("reorders rows and columns", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 0);+ await apply(view, moveRow(1, 3));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| b1 | b2 | b3 |\n| a1 | a2 | a3 |\n\n`,+ "moves a row down"+ );++ await selectCell(view, 1, 0);+ await apply(view, moveColumn(0, 3));++ assert.strictEqual(+ editor.value,+ `| h2 | h3 | h1 |\n|----|----|----|\n| b2 | b3 | b1 |\n| a2 | a3 | a1 |\n\n`,+ "moves a column to the end"+ );+ });++ test("Tab walks the cells and appends a row at the end", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ await apply(view, goToNextCell(1));++ assert.strictEqual(+ view.state.selection.$from.parent.textContent,+ "h2",+ "moves to the next cell"+ );++ await selectCell(view, 2, 2);+ await apply(view, goToNextCell(1));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n| | | |\n\n`,+ "appends a row past the last cell"+ );+ });++ test("a caret in a cell targets both of its axes", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 1);+ const target = menuTargetFor(view.state);++ assert.deepEqual(+ cellMenuItems(view, target)+ .filter((item) => !item.divider)+ .map((item) => item.className),+ [+ "composer-table-menu__insert-above",+ "composer-table-menu__insert-below",+ "composer-table-menu__insert-left",+ "composer-table-menu__insert-right",+ "composer-table-menu__duplicate-row",+ "composer-table-menu__duplicate-column",+ "composer-table-menu__move-row-up",+ "composer-table-menu__move-row-down",+ "composer-table-menu__move-column-left",+ "composer-table-menu__move-column-right",+ "composer-table-menu__align-left",+ "composer-table-menu__align-center",+ "composer-table-menu__align-right",+ "composer-table-menu__clear-contents",+ "composer-table-menu__delete-row",+ "composer-table-menu__delete-column",+ "composer-table-menu__delete-table",+ ],+ "every table command is reachable from one cell"+ );+ });++ test("the keyboard opens the rendered cell menu and clears its cell", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE, {+ withMenus: true,+ });+ const { view } = editor;++ await selectCell(view, 1, 1);+ await pressKey(view, "Enter", { altKey: true });+ await waitFor('.fk-d-menu[data-identifier="composer-table-menu"]');++ assert+ .dom(".composer-table-menu__duplicate-row")+ .doesNotHaveAttribute(+ "aria-keyshortcuts",+ "a cell menu does not advertise a row shortcut"+ );+ assert+ .dom(".composer-table-menu__align-left")+ .hasAttribute("aria-pressed", "false");+ assert+ .dom(".composer-table-menu__align-center")+ .hasAttribute("aria-pressed", "false");++ await click(".composer-table-menu__clear-contents");++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | | a3 |\n| b1 | b2 | b3 |\n\n`,+ "clear contents works from a caret"+ );+ });++ test("the header row is offered a header above instead of a plain row", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ const classNames = cellMenuItems(view, menuTargetFor(view.state)).map(+ (item) => item.className+ );++ assert.false(+ classNames.includes("composer-table-menu__insert-above"),+ "a row cannot be inserted above the header"+ );+ assert.true(+ classNames.includes("composer-table-menu__insert-header-above"),+ "a new header can be"+ );+ });++ test("inserting a header above demotes the one it replaces", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ `| left | right |\n| :--- | ---: |\n| a1 | a2 |`+ );+ const { view } = editor;++ await selectCell(view, 0, 0);+ await apply(view, addHeaderRow());++ assert.strictEqual(+ editor.value,+ `| | |\n|:---|---:|\n| left | right |\n| a1 | a2 |\n\n`,+ "the old header becomes a body row and the column alignment survives"+ );+ });++ test("an inserted header row undoes in one step", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ await apply(view, addHeaderRow());+ await apply(view, undo);++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "the table returns to its original shape"+ );+ });++ test("a caret outside a table has no target", async function (assert) {+ const [editor] = await setupRichEditor(assert, `text\n\n${TABLE}`);+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 2))+ );+ await settled();++ assert.strictEqual(menuTargetFor(view.state), null);+ });++ test("a grip highlights its row without replacing the caret", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ await selectCell(view, 2, 1);+ const caret = view.state.selection.from;++ await pressGrip(findAll(".composer-table__grip.--row")[1]);+ assert+ .dom(".ProseMirror .composer-table .is-structural-target")+ .exists({ count: 3 }, "one row");+ assert.strictEqual(+ view.state.selection.from,+ caret,+ "the document selection remains a caret"+ );+ });++ ["row", "column"].forEach((kind) => {+ test(`clicking a ${kind} grip opens its rendered action menu`, async function (assert) {+ await setupRichEditor(assert, TABLE, { withMenus: true });+ const grip = findAll(`.composer-table__grip.--${kind}`)[1];++ await click(grip);+ await waitFor('.fk-d-menu[data-identifier="composer-table-menu"]');++ assert+ .dom(`.composer-table-menu__duplicate-${kind}`)+ .exists(`the selected ${kind}'s actions are rendered`);+ assert+ .dom(".composer-table-menu__clear-contents")+ .exists(`the menu can clear the targeted ${kind}`);+ assert+ .dom(grip)+ .hasAttribute("aria-expanded", "true", "the grip exposes menu state");++ const menuBounds = find(+ '.fk-d-menu[data-identifier="composer-table-menu"]'+ ).getBoundingClientRect();+ assert.notDeepEqual(+ [Math.round(menuBounds.left), Math.round(menuBounds.top)],+ [0, 0],+ "the menu is positioned from its connected grip"+ );+ });+ });++ test("tapping a grip opens the table actions on mobile", async function (assert) {+ forceMobile();+ await setupRichEditor(assert, TABLE, { withMenus: true });+ const grip = findAll(".composer-table__grip.--row")[1];++ await pressGrip(grip, {+ activate: true,+ moveBy: 6,+ pointerType: "touch",+ });+ await waitFor('.fk-d-menu-modal[data-identifier="composer-table-menu"]');+ await settled();++ assert+ .dom(".composer-table-menu__duplicate-row")+ .exists("the row actions render in a touch-friendly sheet");+ });++ test("a mobile grip can reopen its drawer after closing", async function (assert) {+ forceMobile();+ await setupRichEditor(assert, TABLE, { withMenus: true });+ const grip = findAll(".composer-table__grip.--row")[1];+ const selector =+ '.fk-d-menu-modal[data-identifier="composer-table-menu"]';++ for (let attempt = 0; attempt < 3; attempt++) {+ await pressGrip(grip, {+ activate: true,+ pointerType: "touch",+ click: true,+ });+ assert.dom(selector).exists(`tap ${attempt + 1} opens the drawer`);+ await this.owner+ .lookup("service:menu")+ .getByIdentifier("composer-table-menu")+ .close();+ await settled();+ assert.dom(selector).doesNotExist("the drawer closes");+ }+ });++ test("an active mobile grip does not expose vertical table scrolling", async function (assert) {+ forceMobile();+ await setupRichEditor(assert, TABLE);+ const scroller = find(".composer-table");++ await pressGrip(findAll(".composer-table__grip.--column")[1]);++ assert.strictEqual(+ getComputedStyle(scroller).overflowY,+ "hidden",+ "horizontal overflow cannot induce a second scrollbar"+ );+ });++ test("touch dragging the table body scrolls it horizontally", async function (assert) {+ await setupRichEditor(assert, TABLE);+ const scroller = find(".composer-table");+ const inner = find(".composer-table__inner");+ const cell = find(".composer-table td");++ Object.assign(scroller.style, { width: "12rem" });+ Object.assign(inner.style, { width: "36rem" });+ scroller.scrollLeft = 0;++ const at = (x, y) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 11,+ pointerType: "touch",+ isPrimary: true,+ clientX: x,+ clientY: y,+ });++ cell.dispatchEvent(new PointerEvent("pointerdown", at(160, 50)));+ document.dispatchEvent(new PointerEvent("pointermove", at(60, 52)));++ assert.strictEqual(+ getComputedStyle(scroller).overflowX,+ "auto",+ "the table owns its horizontal overflow"+ );+ assert.true(+ scroller.scrollLeft > 0,+ "a horizontal touch gesture moves the table"+ );++ document.dispatchEvent(new PointerEvent("pointerup", at(60, 52)));+ assert+ .dom(scroller)+ .doesNotHaveClass("is-panning", "the transient gesture state clears");+ });++ test("table chrome reserves only the touch gestures it uses", async function (assert) {+ await setupRichEditor(assert, TABLE);++ assert.strictEqual(+ getComputedStyle(find(".composer-table table")).touchAction,+ "pan-y pinch-zoom",+ "the table body keeps vertical page scrolling and pinch zoom"+ );++ for (const control of findAll(".composer-table__grip")) {+ assert.strictEqual(+ getComputedStyle(control).touchAction,+ "none",+ "a grip keeps small tap movements from being canceled"+ );+ }++ assert.strictEqual(+ getComputedStyle(find(".composer-table__append.--row")).touchAction,+ "pan-x pinch-zoom",+ "the row append bar leaves native horizontal panning available"+ );+ assert.strictEqual(+ getComputedStyle(find(".composer-table__append.--column")).touchAction,+ "pan-y pinch-zoom",+ "the column append bar leaves vertical page scrolling available"+ );+ });++ test("an assistive click opens a grip without pointer events", async function (assert) {+ await setupRichEditor(assert, TABLE, { withMenus: true });+ const grip = findAll(".composer-table__grip.--column")[1];++ grip.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ await waitFor('.fk-d-menu[data-identifier="composer-table-menu"]');++ assert+ .dom(".composer-table-menu__duplicate-column")+ .exists("synthesized activation remains supported");+ });++ test("a canceled grip drag does not swallow the next click", async function (assert) {+ await setupRichEditor(assert, TABLE, { withMenus: true });+ const grip = findAll(".composer-table__grip.--row")[1];+ const bounds = grip.getBoundingClientRect();+ const at = (y) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 9,+ isPrimary: true,+ clientX: bounds.left + 1,+ clientY: y,+ });++ grip.dispatchEvent(new PointerEvent("pointerdown", at(bounds.top + 1)));+ document.dispatchEvent(+ new PointerEvent("pointermove", at(bounds.top + 10))+ );+ document.dispatchEvent(+ new PointerEvent("pointercancel", at(bounds.top + 10))+ );+ await settled();++ assert+ .dom('.fk-d-menu[data-identifier="composer-table-menu"]')+ .doesNotExist("canceling does not open a menu");++ const currentGrip = findAll(".composer-table__grip.--row")[1];+ currentGrip.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ await waitFor('.fk-d-menu[data-identifier="composer-table-menu"]');++ assert+ .dom(".composer-table-menu__duplicate-row")+ .exists("the next genuine click opens the menu");+ });++ test("duplicating a row and a column copies their contents", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 0);+ await apply(view, duplicateRow());++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`+ );++ await selectCell(view, 1, 1);+ await apply(view, duplicateColumn());++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h2 | h3 |\n|----|----|----|----|\n| a1 | a2 | a2 | a3 |\n| a1 | a2 | a2 | a3 |\n| b1 | b2 | b2 | b3 |\n\n`+ );+ });++ test("deleting the table removes it from the document", async function (assert) {+ const [editor] = await setupRichEditor(assert, `before\n\n${TABLE}`);+ const { view } = editor;++ await selectCell(view, 1, 1);+ await apply(view, deleteTable());++ assert.strictEqual(editor.value, "before");+ assert.dom(".ProseMirror .composer-table").doesNotExist();+ });++ test("Tab moves between cells through the keymap", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ await pressKey(view, "Tab");++ assert.strictEqual(view.state.selection.$from.parent.textContent, "h2");++ await pressKey(view, "Tab", { shiftKey: true });++ assert.strictEqual(view.state.selection.$from.parent.textContent, "h1");+ });++ test("Shift+Tab at the first cell remains available to the browser", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 0, 0);+ const event = await pressKey(view, "Tab", { shiftKey: true });++ assert.false(+ event.defaultPrevented,+ "the editor does not trap backward focus at the table boundary"+ );+ });++ test("a cell that ends up the wrong type is corrected", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ const pos = cellPos(view, 1, 0);+ const cell = view.state.doc.nodeAt(pos);+ view.dispatch(+ view.state.tr.setNodeMarkup(+ pos,+ view.state.schema.nodes.table_header_cell,+ cell.attrs+ )+ );+ await settled();++ assert.strictEqual(+ view.state.doc.nodeAt(cellPos(view, 1, 0)).type.name,+ "table_cell",+ "a header cell in the body is put back"+ );+ });++ // Merged cells and header columns are expressible in a post through the+ // sanitized HTML subset, which this editor keeps verbatim rather than+ // flattening into a pipe table that cannot represent them.+ Object.entries({+ colspan: `<table>\n<thead>\n<tr><th>A</th><th colspan="2">B</th></tr>\n</thead>\n<tbody>\n<tr><td>1</td><td>2</td><td>3</td></tr>\n</tbody>\n</table>`,+ rowspan: `<table>\n<tbody>\n<tr><td rowspan="2">A</td><td>1</td></tr>\n<tr><td>2</td></tr>\n</tbody>\n</table>`,+ "header column": `<table>\n<tbody>\n<tr><th>Row A</th><td>1</td></tr>\n<tr><th>Row B</th><td>2</td></tr>\n</tbody>\n</table>`,+ }).forEach(([name, markdown]) => {+ test(`an HTML table with ${name} survives untouched`, async function (assert) {+ const [editor] = await setupRichEditor(assert, markdown);++ assert.strictEqual(editor.value, `${markdown}\n\n`);+ assert.dom(".ProseMirror .composer-table").doesNotExist();+ assert.dom(".ProseMirror .html-block").exists();+ });+ });++ test("hovering a cell reveals only its own row and column handle", async function (assert) {+ await setupRichEditor(assert, TABLE);++ assert+ .dom(".composer-table__grip.is-visible")+ .doesNotExist("no pointer-specific handles are shown yet");++ const cell = findAll(".ProseMirror .composer-table td").find(+ (td) => td.textContent === "b2"+ );+ await hoverCell(cell);++ const shown = findAll(".composer-table__grip.is-visible");+ assert.strictEqual(shown.length, 2, "one per axis, not the whole set");++ const cellOf = (grip) => grip.closest("th, td");+ assert.strictEqual(+ cellOf(shown.find((g) => g.classList.contains("--column"))).textContent,+ "h2",+ "the handle for the hovered column"+ );+ assert.strictEqual(+ cellOf(shown.find((g) => g.classList.contains("--row"))).textContent,+ "b1",+ "and for the hovered row"+ );+ });++ test("a caret keeps pointer-specific handles quiet", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);++ await selectCell(editor.view, 2, 1);++ assert+ .dom(".composer-table__grip.is-visible")+ .doesNotExist("typing does not summon structural chrome");+ assert.dom(".composer-table.is-active").exists("the table stays active");+ assert+ .dom(".composer-table .is-current-row")+ .exists({ count: 1 }, "touch has one caret-aware row target");+ assert+ .dom(".composer-table .is-current-column")+ .exists({ count: 1 }, "and one caret-aware column target");+ });++ test("only the caret's handles are exposed to assistive technology", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);++ await selectCell(editor.view, 2, 1);++ const grips = findAll(".composer-table__grip");+ const exposed = grips.filter(+ (grip) => grip.getAttribute("aria-hidden") === "false"+ );++ assert.strictEqual(grips.length, 6, "every row and column has one");+ assert.strictEqual(+ exposed.length,+ 2,+ "only one control per axis is exposed"+ );+ assert.deepEqual(+ exposed.map((grip) => grip.getAttribute("aria-label")).sort(),+ ["Column 2 actions", "Row 3 actions"],+ "the controls name the structure they act on"+ );+ grips+ .filter((grip) => !exposed.includes(grip))+ .forEach((grip) =>+ assert.dom(grip).hasAttribute("aria-hidden", "true")+ );+ });++ test("a disabled editor hides table chrome and rejects its events", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE, {+ disabled: true,+ withMenus: true,+ });+ const before = editor.value;+ const grip = find(".composer-table__grip.--row");+ const append = find(".composer-table__append.--row");++ assert.dom(grip).hasAttribute("hidden");+ assert.dom(append).hasAttribute("hidden");++ grip.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ append.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ cellMenuItems(editor.view, menuTargetFor(editor.view.state))+ .find((item) => item.className === "composer-table-menu__insert-below")+ .action();+ await pressKey(editor.view, "Enter", { altKey: true });+ await settled();++ assert.strictEqual(editor.value, before, "the document is unchanged");+ assert+ .dom('.fk-d-menu[data-identifier="composer-table-menu"]')+ .doesNotExist("no table action menu opens");+ });++ test("a structural target marks the sides that face out of it", async function (assert) {+ await setupRichEditor(assert, TABLE);++ await pressGrip(findAll(".composer-table__grip.--row")[1]);++ const edges = findAll(+ ".ProseMirror .composer-table .is-structural-target"+ ).map((cell) =>+ [...cell.classList]+ .filter((name) => name.startsWith("--edge"))+ .sort()+ .join(" ")+ );++ assert.deepEqual(+ edges,+ ["--edge-start", "", "--edge-end"],+ "the highlighted row has one continuous boundary"+ );+ });++ test("clicking an append bar after dragging it still adds one", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const columns = () => findAll(".ProseMirror .composer-table th").length;+ const button = find(".composer-table__append.--column");+ const rect = button.getBoundingClientRect();+ const at = (x) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 4,+ isPrimary: true,+ clientX: x,+ clientY: rect.top + rect.height / 2,+ });+ const origin = rect.left + rect.width / 2;++ button.dispatchEvent(new PointerEvent("pointerdown", at(origin)));+ document.dispatchEvent(new PointerEvent("pointermove", at(origin + 600)));+ document.dispatchEvent(new PointerEvent("pointerup", at(origin + 600)));+ await settled();++ const afterDrag = columns();+ assert.true(afterDrag > 3, "the drag added columns");++ button.dispatchEvent(new PointerEvent("pointerdown", at(origin)));+ document.dispatchEvent(new PointerEvent("pointerup", at(origin)));+ button.dispatchEvent(new MouseEvent("click", at(origin)));+ await settled();++ assert.strictEqual(+ columns(),+ afterDrag + 1,+ "and a plain click afterwards still adds one"+ );+ assert.strictEqual(+ editor.value.split("\n")[0].split("|").length - 2,+ afterDrag + 1,+ "the markdown has the same column count"+ );+ });++ test("dragging an append bar back removes empty rows or columns", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ `| h1 | h2 |\n| --- | --- |\n| a1 | a2 |`+ );+ const columns = () => editor.value.split("\n")[0].split("|").length - 2;+ const before = columns();++ await dragAppend(find(".composer-table__append.--column"), 400);+ const added = columns();+ assert.true(added > before, `columns added (${before} -> ${added})`);++ await dragAppend(find(".composer-table__append.--column"), -400);+ assert.strictEqual(+ columns(),+ before,+ "dragging back the same way drops the empty ones again"+ );+ });++ test("dragging back never removes a row or column with content", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const before = editor.value;++ await dragAppend(find(".composer-table__append.--column"), -600);+ assert.strictEqual(+ editor.value,+ before,+ "every column carries content, so there is nothing to take away"+ );++ await dragAppend(find(".composer-table__append.--row"), -600);+ assert.strictEqual(editor.value, before, "and the same for rows");+ });++ test("dragging back preserves non-text cell content", async function (assert) {+ const markdown = `| h1 | |+| --- | --- |+| |  |`;+ const [editor] = await setupRichEditor(assert, markdown);+ const before = editor.value;++ await dragAppend(find(".composer-table__append.--column"), -600);+ assert.strictEqual(+ editor.value,+ before,+ "an image-only trailing column is not removed"+ );++ await dragAppend(find(".composer-table__append.--row"), -600);+ assert.strictEqual(+ editor.value,+ before,+ "an image-only trailing row is not removed"+ );+ });++ test("a row can be dragged into and out of the header", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 2, 0);+ await apply(view, moveRow(2, 0));++ assert.strictEqual(+ editor.value,+ `| b1 | b2 | b3 |\n|----|----|----|\n| h1 | h2 | h3 |\n| a1 | a2 | a3 |\n\n`,+ "the row that lands first becomes the header"+ );++ await selectCell(view, 0, 0);+ await apply(view, moveRow(0, 3));++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "and the old header becomes a body row on the way back"+ );+ });++ test("crossing the header re-types the cells it moves", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 0);+ await apply(view, moveRow(1, 0));++ const types = [];+ view.state.doc.descendants((node) => {+ if (node.type.spec.tableRole === "row") {+ types.push(+ [...node.children].map((cell) => cell.type.name).join(",")+ );+ }+ });++ assert.strictEqual(+ types[0],+ "table_header_cell,table_header_cell,table_header_cell",+ "the promoted row holds header cells"+ );+ assert.strictEqual(+ types[1],+ "table_cell,table_cell,table_cell",+ "and the demoted one holds body cells"+ );+ });++ test("the append bars grow the table", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);++ await click(".composer-table__append.--column");++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 | |\n|----|----|----|----|\n| a1 | a2 | a3 | |\n| b1 | b2 | b3 | |\n\n`,+ "appends a column at the right edge"+ );++ await click(".composer-table__append.--row");++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 | |\n|----|----|----|----|\n| a1 | a2 | a3 | |\n| b1 | b2 | b3 | |\n| | | | |\n\n`,+ "appends a row at the bottom edge"+ );+ });++ test("dragging an append bar adds multiple rows or columns", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const table = find(".composer-table table");+ table.getBoundingClientRect = () => ({ width: 300, height: 90 });++ await dragAppend(find(".composer-table__append.--column"), 200);+ await dragAppend(find(".composer-table__append.--row"), 60);++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 | | |\n|----|----|----|----|----|\n| a1 | a2 | a3 | | |\n| b1 | b2 | b3 | | |\n| | | | | |\n| | | | | |\n\n`,+ "the drag distance controls how many are appended"+ );+ });++ test("a narrow table does not over-count a column drag", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const table = find(".composer-table table");+ table.getBoundingClientRect = () => ({ width: 90, height: 90 });++ await dragAppend(find(".composer-table__append.--column"), 100);++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 | |\n|----|----|----|----|\n| a1 | a2 | a3 | |\n| b1 | b2 | b3 | |\n\n`,+ "the drag uses a usable column width instead of the collapsed table width"+ );+ });++ test("a long append drag is capped", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const table = find(".composer-table table");+ table.getBoundingClientRect = () => ({ width: 300, height: 90 });++ await dragAppend(find(".composer-table__append.--column"), 10_000);++ assert.strictEqual(+ editor.value.split("\n")[0].split("|").length - 2,+ 11,+ "one gesture adds at most eight columns"+ );+ });++ test("an append drag autoscrolls at the table edge", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const scroller = find(".composer-table");+ const button = find(".composer-table__append.--column");+ const inner = find(".composer-table__inner");+ Object.assign(scroller.style, {+ width: "200px",+ overflowX: "auto",+ });+ inner.style.width = "600px";+ scroller.scrollLeft = 0;+ const bounds = scroller.getBoundingClientRect();++ const at = (x) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 8,+ isPrimary: true,+ clientX: x,+ clientY: 50,+ });+ button.dispatchEvent(+ new PointerEvent("pointerdown", at(bounds.left + bounds.width / 2))+ );+ document.dispatchEvent(+ new PointerEvent("pointermove", at(bounds.right - 2))+ );+ await waitUntil(+ () =>+ find(".composer-table__append.--column .composer-table__append-count")+ .textContent === "+2"+ );++ assert.true(scroller.scrollLeft > 0, "the table scrolls under the drag");++ document.dispatchEvent(+ new PointerEvent("pointerup", at(bounds.right - 2))+ );+ await settled();++ assert.true(+ editor.value.split("\n")[0].split("|").length - 2 >= 5,+ "stationary edge scrolling advances the append count"+ );+ });++ test("a row reorder autoscrolls at the composer edge", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const scroller = find(".composer-table");+ const inner = find(".composer-table__inner");+ const grip = findAll(".composer-table__grip.--row")[1];+ Object.assign(scroller.style, {+ height: "70px",+ overflowY: "auto",+ });+ inner.style.height = "300px";+ const gripBounds = grip.getBoundingClientRect();+ const bounds = scroller.getBoundingClientRect();+ const at = (y) => ({+ bubbles: true,+ cancelable: true,+ button: 0,+ pointerId: 9,+ isPrimary: true,+ clientX: gripBounds.left + gripBounds.width / 2,+ clientY: y,+ });++ grip.dispatchEvent(+ new PointerEvent(+ "pointerdown",+ at(gripBounds.top + gripBounds.height / 2)+ )+ );+ document.dispatchEvent(+ new PointerEvent("pointermove", at(bounds.bottom - 2))+ );+ await waitUntil(() => scroller.scrollTop > 0);++ assert.true(+ scroller.scrollTop > 0,+ "the composer scrolls while the pointer stays at its lower edge"+ );++ document.dispatchEvent(+ new PointerEvent("pointerup", at(bounds.bottom - 2))+ );+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| b1 | b2 | b3 |\n| a1 | a2 | a3 |\n\n`,+ "releasing a stationary pointer uses the autoscrolled landing target"+ );+ });++ test("a text selection across cells remains ordinary text selection", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ const from = cellPos(view, 1, 0) + 1;+ const to = cellPos(view, 1, 2) + 2;+ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(view.state.doc, from, to)+ )+ );+ await settled();++ view.focus();+ assert.true(+ view.state.selection instanceof TextSelection,+ "the selection retains text semantics"+ );+ assert.strictEqual(+ window.getSelection().toString().replace(/\s/g, ""),+ "a1a2a",+ "native selection keeps the partial final cell"+ );+ assert+ .dom(".ProseMirror .composer-table .is-structural-target")+ .doesNotExist("no spreadsheet-style selection is introduced");+ });++ test("Delete across cells preserves their boundaries", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ cellPos(view, 1, 0) + 2,+ cellPos(view, 1, 2) + 2+ )+ )+ );+ await pressKey(view, "Delete");++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a | | 3 |\n| b1 | b2 | b3 |\n\n`,+ "only selected cell content is removed"+ );+ assert.strictEqual(+ locateTable(view).grid.width,+ 3,+ "the row keeps all of its cells"+ );+ });++ test("mobile deletion across table sections preserves their structure", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ cellPos(view, 0, 2) + 2,+ cellPos(view, 1, 0) + 2+ )+ )+ );+ view.dom.dispatchEvent(+ new InputEvent("beforeinput", {+ bubbles: true,+ cancelable: true,+ inputType: "deleteContentBackward",+ })+ );+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h |\n|----|----|----|\n| 1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "content is removed without joining the header and body"+ );+ assert.deepEqual(+ locateTable(view).grid.rows.map((row) =>+ row.cells.map((cell) => cell.node.type.name)+ ),+ [+ ["table_header_cell", "table_header_cell", "table_header_cell"],+ ["table_cell", "table_cell", "table_cell"],+ ["table_cell", "table_cell", "table_cell"],+ ],+ "each section keeps the correct cell types"+ );+ });++ for (const backwards of [false, true]) {+ test(`Shift+Enter across rows preserves cells (${backwards ? "backward" : "forward"})`, async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ const from = cellPos(view, 1, 0) + 2;+ const to = cellPos(view, 2, 0) + 2;+ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ backwards ? to : from,+ backwards ? from : to+ )+ )+ );+ await pressKey(view, "Enter", { shiftKey: true });+ const { grid } = locateTable(view);+ assert.strictEqual(grid.height, 3, "all rows survive");+ assert.deepEqual(+ grid.rows.map((row) => row.cells.length),+ [3, 3, 3],+ "all cells survive"+ );+ assert.strictEqual(+ grid.rows[1].cells[0].node.lastChild.type.name,+ "hard_break",+ "the break lands in the first selected cell"+ );+ assert.strictEqual(+ grid.rows[2].cells[0].node.textContent,+ "1",+ "the unselected suffix survives"+ );+ await apply(view, undo);+ assert.strictEqual(+ locateTable(view).grid.rows[1].cells[0].node.textContent,+ "a1",+ "undo restores the selected content"+ );+ view.dispatch(view.state.tr.insertText("X"));+ assert.strictEqual(+ locateTable(view).grid.height,+ 3,+ "the restored selection remains safe to replace"+ );+ });+ }++ test("editing a trailing cell cancels an append-removal drag", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ await selectCell(view, 1, 2);+ await apply(view, addColumn(1));+ const button = find(".composer-table__append.--column");+ const bounds = button.getBoundingClientRect();+ const start = {+ bubbles: true,+ button: 0,+ pointerId: 8,+ clientX: bounds.left,+ clientY: bounds.top,+ };+ const end = { ...start, clientX: bounds.left - 200 };+ button.dispatchEvent(new PointerEvent("pointerdown", start));+ document.dispatchEvent(new PointerEvent("pointermove", end));+ view.dispatch(view.state.tr.insertText("keep", cellPos(view, 1, 3) + 1));+ document.dispatchEvent(new PointerEvent("pointerup", end));+ assert.strictEqual(+ locateTable(view).grid.rows[1].cells[3].node.textContent,+ "keep",+ "new content is not removed by the old gesture"+ );+ assert+ .dom(".composer-table__ghost.--visible")+ .doesNotExist("the canceled preview is removed");+ });++ test("a captured command rejects a changed table position", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ const target = locateTable(view);+ view.dispatch(+ view.state.tr.insert(+ 0,+ view.state.schema.nodes.paragraph.create(+ null,+ view.state.schema.text("before")+ )+ )+ );+ const doc = view.state.doc;+ assert.false(+ moveRow(1, 3, target)(view.state, view.dispatch),+ "the old target is rejected"+ );+ assert.strictEqual(view.state.doc, doc, "no content is changed");+ });++ test("header moves keep subsequent typing in the moved row", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE + "\n\nafter");+ const { view } = editor;+ await selectCell(view, 1, 0);+ await apply(view, moveRow(1, 0));+ view.dispatch(view.state.tr.insertText("X"));+ assert.strictEqual(+ locateTable(view).grid.rows[0].cells[0].node.textContent,+ "Xa1",+ "typing stays in the promoted row"+ );+ });++ test("pasting a table keeps subsequent typing inside the destination", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE + "\n\nafter");+ const { view } = editor;+ await selectCell(view, 1, 0);+ view.pasteHTML("<table><tbody><tr><td>pasted</td></tr></tbody></table>");+ view.dispatch(view.state.tr.insertText("X"));+ assert.strictEqual(+ locateTable(view).grid.rows[1].cells[0].node.textContent,+ "Xpasted",+ "typing stays in the pasted cell"+ );+ });++ test("a caret in table chrome returns to editable cell content", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ await selectCell(view, 2, 0);+ view.focus();+ window.getSelection().collapse(find(".composer-table__inner"), 0);+ document.dispatchEvent(new Event("selectionchange"));+ await settled();++ const selection = window.getSelection();+ const element =+ selection.anchorNode.nodeType === Node.ELEMENT_NODE+ ? selection.anchorNode+ : selection.anchorNode.parentElement;+ assert.true(+ !!element.closest("th, td"),+ "the browser caret is restored inside a cell"+ );+ document.execCommand("insertText", false, "sss");+ await settled();+ assert.true(+ view.state.doc.textContent.includes("sss"),+ "typed text belongs to the document"+ );+ assert.strictEqual(+ find(".composer-table__inner").firstChild.tagName,+ "TABLE",+ "no text appears in the table chrome"+ );+ });++ test("cell mutation handling still reads text edits", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ const cell = find(".composer-table td");+ [...cell.childNodes].find(+ (node) => node.nodeType === Node.TEXT_NODE+ ).textContent = "edited";+ await settled();+ assert.strictEqual(+ locateTable(view).grid.rows[1].cells[0].node.textContent,+ "edited",+ "text changes are still read from the cell"+ );+ });++ test("an assistive append activation works after a drag ends elsewhere", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const button = find(".composer-table__append.--column");+ const bounds = button.getBoundingClientRect();+ const start = {+ bubbles: true,+ button: 0,+ pointerId: 8,+ clientX: bounds.left,+ clientY: bounds.top,+ };+ button.dispatchEvent(new PointerEvent("pointerdown", start));+ document.dispatchEvent(+ new PointerEvent("pointermove", {+ ...start,+ clientX: bounds.left + 200,+ })+ );+ document.dispatchEvent(+ new PointerEvent("pointerup", { ...start, clientX: bounds.left + 200 })+ );+ const width = locateTable(editor.view).grid.width;+ button.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ assert.strictEqual(+ locateTable(editor.view).grid.width,+ width + 1,+ "assistive activation is not swallowed"+ );+ });++ for (const direction of ["ltr", "rtl"]) {+ test(`row grips follow ${direction} table direction on an RTL page`, async function (assert) {+ const original = document.documentElement.dir;+ try {+ document.documentElement.dir = "rtl";+ const [editor] = await setupRichEditor(assert, TABLE);+ editor.view.dom.dir = direction;+ const grip = find(".composer-table__grip.--row");+ const cell = grip.closest("th");+ const gripBounds = grip.getBoundingClientRect();+ const edge =+ cell.getBoundingClientRect()[+ direction === "rtl" ? "right" : "left"+ ];+ assert.true(+ Math.abs(gripBounds.left + gripBounds.width / 2 - edge) < 1,+ "the grip is centered on the table's outside edge"+ );+ } finally {+ document.documentElement.dir = original;+ }+ });+ }++ test("editable changes synchronize all table controls", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ for (const editable of [false, true]) {+ view.setProps({ editable: () => editable });+ for (const control of findAll(+ ".composer-table__grip, .composer-table__append"+ )) {+ assert.strictEqual(+ control.hidden,+ !editable,+ "visibility follows editability"+ );+ assert.strictEqual(+ control.disabled,+ !editable,+ "activation follows editability"+ );+ }+ }+ });++ test("dragging keeps the editable cells intact between pointer events", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ const cell = findAll(".composer-table td")[0];+ await dragGrip(+ findAll(".composer-table__grip.--row")[1],+ findAll(".composer-table tr")[2],+ () => {+ assert.strictEqual(+ findAll(".composer-table td")[0],+ cell,+ "the observer does not replace the lifted cell"+ );+ assert.true(+ cell.classList.contains("is-moving"),+ "the cell stays lifted"+ );+ assert.notStrictEqual(+ cell.style.transform,+ "",+ "the cell follows the pointer"+ );+ }+ );+ assert.strictEqual(+ locateTable(view).grid.rows[2].cells[0].node.textContent,+ "a1",+ "the move still commits"+ );+ });++ test("a document change cancels a pending reorder", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ await dragGrip(+ findAll(".composer-table__grip.--row")[1],+ findAll(".composer-table tr")[2],+ () => {+ view.dispatch(view.state.tr.insertText("X", cellPos(view, 1, 0) + 1));+ }+ );+ assert.strictEqual(+ locateTable(view).grid.rows[1].cells[0].node.textContent,+ "Xa1",+ "the edit survives without reordering"+ );+ assert+ .dom(".composer-table__drag-avatar")+ .doesNotExist("the drag presentation is cleaned up");+ });++ test("typing across cells is one safe undoable edit", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ cellPos(view, 0, 2) + 2,+ cellPos(view, 1, 0) + 2+ )+ )+ );+ view.dom.dispatchEvent(+ new KeyboardEvent("keypress", {+ bubbles: true,+ cancelable: true,+ charCode: 88,+ key: "X",+ keyCode: 88,+ })+ );+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | hX |\n|----|----|----|\n| 1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "text lands in the first cell without joining cells"+ );+ assert.true(view.state.selection.empty, "the replacement leaves a caret");++ await apply(view, undo);+ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "one undo restores the range"+ );+ });++ test("pasting text across cells preserves the grid", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ cellPos(view, 1, 0) + 2,+ cellPos(view, 1, 1) + 2+ )+ )+ );+ view.pasteHTML("<p>Z</p>");+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| aZ | 2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "the paste replaces content rather than cell nodes"+ );+ });++ test("cutting across cells preserves the grid and is undoable", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;+ const clipboardData = new DataTransfer();++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(+ view.state.doc,+ cellPos(view, 1, 0) + 2,+ cellPos(view, 1, 1) + 2+ )+ )+ );+ view.dom.dispatchEvent(+ new ClipboardEvent("cut", {+ bubbles: true,+ cancelable: true,+ clipboardData,+ })+ );+ await settled();++ assert.strictEqual(clipboardData.getData("text/plain"), "1\n\na");+ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a | 2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "the cut removes content without joining cells"+ );++ await apply(view, undo);+ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`,+ "one undo restores the cut range"+ );+ });++ test("a row left short of cells is padded back out", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ const pos = cellPos(view, 1, 2);+ const cell = view.state.doc.nodeAt(pos);+ view.dispatch(view.state.tr.delete(pos, pos + cell.nodeSize));+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | |\n| b1 | b2 | b3 |\n\n`,+ "the grid stays rectangular"+ );+ });++ test("pasting a table into a cell fills the grid instead of nesting", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 1);+ view.pasteHTML(+ "<table><tbody><tr><td>x1</td><td>x2</td></tr><tr><td>y1</td><td>y2</td></tr></tbody></table>"+ );+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | x1 | x2 |\n| b1 | y1 | y2 |\n\n`,+ "the pasted cells land at the target cell"+ );+ });++ test("pasting a table larger than the grid grows it", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 2, 2);+ view.pasteHTML(+ "<table><tbody><tr><td>x1</td><td>x2</td></tr><tr><td>y1</td><td>y2</td></tr></tbody></table>"+ );+ await settled();++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 | |\n|----|----|----|----|\n| a1 | a2 | a3 | |\n| b1 | b2 | x1 | x2 |\n| | | y1 | y2 |\n\n`,+ "the table is extended to fit the paste"+ );+ });++ test("pasting a table alongside other content keeps the other content", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 1);+ view.pasteHTML("<hr><table><tbody><tr><td>x1</td></tr></tbody></table>");+ await settled();++ let horizontalRules = 0;+ editor.view.state.doc.descendants((node) => {+ if (node.type.name === "horizontal_rule") {+ horizontalRules++;+ }+ });+ assert.strictEqual(+ horizontalRules,+ 1,+ "a non-text block beside the table is not dropped"+ );+ });++ test("structural edits undo in one step", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);+ const { view } = editor;++ await selectCell(view, 1, 1);+ await apply(view, addColumn(1));+ await apply(view, undo);++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| a1 | a2 | a3 |\n| b1 | b2 | b3 |\n\n`+ );+ });++ test("an imported table with no rows is removed safely", async function (assert) {+ const [editor] = await setupRichEditor(assert, "before");+ const { schema, tr } = editor.view.state;+ const emptyTable = schema.nodes.table.create(+ null,+ schema.nodes.table_body.create()+ );++ editor.view.dispatch(+ tr.replaceWith(0, editor.view.state.doc.content.size, emptyTable)+ );+ await settled();++ assert.dom(".composer-table").doesNotExist();+ assert.notStrictEqual(+ editor.view.state.doc.firstChild.type.name,+ "table",+ "the editor does not leave invalid append chrome behind"+ );+ });++ test("dragging a row grip past another row reorders them", async function (assert) {+ const [editor] = await setupRichEditor(assert, TABLE);++ const grips = findAll(".composer-table__grip.--row");+ const rows = findAll(".ProseMirror .composer-table table tr");+ await dragGrip(grips[1], rows[2]);++ assert.strictEqual(+ editor.value,+ `| h1 | h2 | h3 |\n|----|----|----|\n| b1 | b2 | b3 |\n| a1 | a2 | a3 |\n\n`,+ "the dragged row lands past the one it was dropped over"+ );+ });++ Object.entries({+ right: [+ 0,+ 2,+ `| a much longer heading | x | short |\n|----|----|----|\n| a much longer value | three | one |\n\n`,+ ],+ left: [+ 2,+ 0,+ `| x | short | a much longer heading |\n|----|----|----|\n| three | one | a much longer value |\n\n`,+ ],+ }).forEach(([direction, [from, to, expected]]) => {+ test(`dragging a column grip to the ${direction} reorders unequal cells`, async function (assert) {+ const [editor] = await setupRichEditor(assert, UNEVEN_TABLE);+ const grips = findAll(".composer-table__grip.--column");+ const cells = findAll(".ProseMirror .composer-table table th");++ await dragGrip(grips[from], cells[to], () => {+ // Portaled to the body, so out of reach of the container-scoped `find`.+ const avatar = document.querySelector(+ ".composer-table__drag-avatar.--column"+ );+ assert.true(+ !!avatar,+ "the portaled active grip follows the pointer during the drag"+ );+ assert.true(+ avatar.style.transform.startsWith("translateX("),+ "the avatar carries the same horizontal drag offset"+ );+ });++ assert.strictEqual(+ editor.value,+ expected,+ "the dragged column lands past the one it was dropped over"+ );});});}diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rbindex 2461e89296d..d5e8497d02b 100644--- a/lib/svg_sprite.rb+++ b/lib/svg_sprite.rb@@ -6,7 +6,9 @@ module SvgSpriteaaddress-bookaddress-card+ align-centeralign-left+ align-rightanchorangle-downangle-left