Skip to content

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

UX: Replace the table builder with direct table insertion (#44773)

David Taylor0d84ef341847
diff --git a/.licensee.json b/.licensee.json
index c7a584ae500..0d3f5309b99 100644
--- a/.licensee.json
+++ b/.licensee.json
@@ -10,10 +10,8 @@
},
"packages": {
"@fortawesome/fontawesome-free": "*",
- "@jspreadsheet/formula": "2.0.2",
"cli-table": "0.3.11",
"jsonify": "0.0.1",
- "jspreadsheet-ce": "5.0.4",
"@embroider/vite": "1.7.5"
},
"corrections": true,
diff --git a/app/assets/stylesheets/common.scss b/app/assets/stylesheets/common.scss
index 2817087e2cf..f8dddc01a03 100644
--- a/app/assets/stylesheets/common.scss
+++ b/app/assets/stylesheets/common.scss
@@ -22,7 +22,6 @@
@import "common/loading-slider";
@import "common/rich-editor";
@import "common/login/_index";
-@import "common/table-builder/_index";
@import "common/post-action-feedback";
@import "common/toolbar-popup-menu-options";
@import "common/nested-view";
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index 99848972a23..bb06eb7a0e1 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -2113,14 +2113,41 @@ html.discourse-no-touch .fullscreen-table-wrapper:hover {
opacity: 100%;
}
- &.--has-overflow,
- &.--editable {
+ &.--has-overflow {
box-shadow:
0 2px 5px 0 rgb(var(--always-black-rgb), 0.1),
0 2px 10px 0 rgb(var(--always-black-rgb), 0.1);
}
}
+.fullscreen-table-wrapper:hover .fullscreen-table-wrapper__buttons button {
+ opacity: 100%;
+}
+
+.fullscreen-table-wrapper {
+ .discourse-no-touch & {
+ &__buttons {
+ position: absolute;
+ top: 0.5rem;
+ right: 0.5rem;
+ }
+ }
+
+ .discourse-touch & {
+ @include viewport.until(xl) {
+ display: flex;
+ flex-direction: column-reverse;
+ padding-bottom: 0.5em;
+
+ .open-popup-link {
+ opacity: 100%;
+ left: 0;
+ margin: var(--space-2) 0 0;
+ }
+ }
+ }
+}
+
.read-state {
position: absolute;
diff --git a/app/assets/stylesheets/common/table-builder/_index.scss b/app/assets/stylesheets/common/table-builder/_index.scss
deleted file mode 100644
index 3e993c55e22..00000000000
--- a/app/assets/stylesheets/common/table-builder/_index.scss
+++ /dev/null
@@ -1,3 +0,0 @@
-@import "jspreadsheet-theme";
-@import "table-edit-decorator";
-@import "insert-table-modal";
diff --git a/app/assets/stylesheets/common/table-builder/insert-table-modal.scss b/app/assets/stylesheets/common/table-builder/insert-table-modal.scss
deleted file mode 100644
index 2a049fe14cb..00000000000
--- a/app/assets/stylesheets/common/table-builder/insert-table-modal.scss
+++ /dev/null
@@ -1,80 +0,0 @@
-.btn-insert-table {
- background: var(--tertiary);
- color: var(--secondary);
-
- .d-icon {
- color: var(--secondary);
- }
-
- .discourse-no-touch & {
- &:hover {
- background-color: var(--tertiary-hover);
- color: var(--secondary);
-
- .d-icon {
- color: var(--secondary);
- }
- }
- }
-}
-
-.insert-table-modal {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
-
- .d-modal__container {
- --modal-max-width: #{$reply-area-max-width};
- width: 100%;
- height: 100%;
- max-height: unset;
- display: grid;
- grid-template-rows: auto 1fr auto;
- border-radius: 0;
- }
-
- .d-modal__body {
- padding: 0 4px 0 0;
- }
-
- .d-modal__footer {
- justify-content: space-between;
-
- .primary-actions {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- }
-
- .secondary-actions {
- display: flex;
- align-items: center;
- gap: 0.5rem;
-
- .edit-reason {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- }
-
- .btn {
- margin-right: 0;
- }
-
- input {
- margin: 0;
- }
- }
-
- .secondary-actions .tippy-content {
- h4 {
- color: var(--primary);
- }
-
- li {
- margin-block: 0.25rem;
- color: var(--primary-high);
- }
- }
- }
-}
diff --git a/app/assets/stylesheets/common/table-builder/jspreadsheet-theme.scss b/app/assets/stylesheets/common/table-builder/jspreadsheet-theme.scss
deleted file mode 100644
index b9570649fac..00000000000
--- a/app/assets/stylesheets/common/table-builder/jspreadsheet-theme.scss
+++ /dev/null
@@ -1,270 +0,0 @@
-:root {
- --jss_header_color: var(--primary-high);
- --jss_header_color_highlighted: var(--primary-high);
- --jss_header_background: var(--primary-very-low);
- --jss_header_background_highlighted: var(--primary-low);
- --jss_content_color: var(--primary);
- --jss_content_color_highlighted: var(--primary-high);
- --jss_content_background: var(--secondary);
- --jss_content_background_highlighted: var(--tertiary-very-low);
- --jss_menu_background: var(--secondary);
- --jss_menu_background_highlighted: var(--secondary-very-high);
- --jss_menu_color: var(--primary-medium);
- --jss_menu_color_highlighted: var(--primary);
- --jss_border_color: var(--primary-low-mid);
- --jss_border_color_highlighted: var(--tertiary-high);
- --active_color: var(--primary-very-low);
- --active-color: var(--active_color);
-}
-
-.jss_worksheet {
- border-top: none;
- border-left: none;
- border-bottom: 1px solid var(--jss_border_color);
- border-right: transparent;
- background-color: transparent;
-}
-
-table.jss_worksheet > thead > tr > td {
- border-left: 1px solid transparent;
- padding: 10px;
- font-weight: bold;
- border-top: none;
- border-right: 1px solid var(--jss_border_color);
- border-bottom: 1px solid var(--jss_border_color);
- background-color: var(--jss_header_background);
-
- &:first-child {
- border-left: none;
- }
-}
-
-table.jss_worksheet > tbody > tr > td {
- padding: 8px;
- border-left: 1px solid transparent;
- border-right: 1px solid var(--jss_border_color);
-
- &:first-child {
- border-left: none;
- background-color: var(--jss_header_background);
- }
-}
-
-table.jss_worksheet {
- border-bottom: 1px solid var(--jss_border_color);
-}
-
-.jcontextmenu.jss_contextmenu hr {
- border-color: var(--jss_border_color);
-}
-
-.jss_container .jcontextmenu > div a {
- color: var(--jss_menu_color);
-}
-
-.jss_corner {
- background-color: var(--tertiary);
-}
-
-.jss_worksheet > tbody > tr > td,
-.jss_worksheet > thead > tr > td {
- border-top: 1px solid var(--jss_border_color);
- border-left: 1px solid var(--jss_border_color);
- background-color: var(--jss_content_background);
- color: var(--jss_content_color);
-
- &:first-child {
- border-left: none;
- }
-}
-
-.jss_worksheet > thead > tr > td {
- border-top: none;
-}
-
-.jss_worksheet > tbody > tr > td:first-child,
-.jss_worksheet > thead > tr > td {
- background-color: var(--jss_header_background);
- color: var(--jss_header_color);
-}
-
-.jss_worksheet > thead > tr > td.selected,
-.jss_worksheet > tbody > tr.selected > td:first-child {
- background-color: var(--jss_header_background_highlighted);
- color: var(--jss_header_color_highlighted);
-}
-
-table.jss_worksheet > tbody > tr.selected > td:first-child {
- background-color: var(--jss_header_background_highlighted);
-}
-
-.jss_worksheet > tbody > tr > td.jss_cursor a {
- color: var(--active-color);
-}
-
-.jss_pagination > div > div {
- color: var(--jss_header_color);
- background: var(--jss_header_background);
- border: 1px solid var(--jss_border_color);
-}
-
-.jss_page,
-.jss_container input,
-.jss_container select {
- color: var(--jss_header_color);
- background: var(--jss_header_background);
- border: 1px solid var(--jss_border_color);
-}
-
-.jss_contextmenu.jcontextmenu {
- border: 1px solid var(--jss_border_color);
- background: var(--jss_menu_background);
- color: var(--jss_menu_color);
- box-shadow: 0 12px 12px rgb(0, 0, 0, 0.15);
-}
-
-.jcontextmenu > div a {
- color: var(--jss_menu_color);
-}
-
-.jcontextmenu > div:not(.contextmenu-line):hover a {
- color: var(--jss_menu_color_highlighted);
-}
-
-.jcontextmenu > div:not(.contextmenu-line):hover {
- background: var(--jss_menu_background_highlighted);
-}
-
-.jss_dropdown .jdropdown-container,
-.jss_dropdown .jdropdown-content {
- background-color: var(--jss_content_background);
- color: var(--jss_content_color);
-}
-
-.jss_dropdown .jdropdown-item {
- color: var(--jss_content_color);
-}
-
-.jss_dropdown .jdropdown-item:hover,
-.jss_dropdown .jdropdown-selected,
-.jss_dropdown .jdropdown-cursor {
- background-color: var(--jss_content_background_highlighted);
- color: var(--jss_content_color_highlighted);
-}
-
-.jss_worksheet .jcalendar-content {
- background-color: var(--jss_header_background);
- color: var(--jss_header_color);
-}
-
-.jss_worksheet .jcalendar-content > table {
- background-color: var(--jss_content_background);
- color: var(--jss_content_color);
-}
-
-.jss_worksheet .jcalendar-weekday {
- background-color: var(--jss_content_background_highlighted);
- color: var(--jss_content_color_highlighted);
-}
-
-.jss_worksheet .jcalendar-sunday {
- color: var(--jss_header_color);
-}
-
-.jss_worksheet .jcalendar-selected {
- background-color: var(--jss_content_background_highlighted);
- color: var(--jss_content_color_highlighted);
-}
-
-.jss_toolbar i.jss_toolbar_item {
- color: var(--jss_content_color);
-}
-
-.jss_toolbar i.jss_toolbar_item:hover {
- background: var(--jss_content_background_highlighted);
- color: var(--jss_content_color_highlighted);
-}
-
-.jss_toolbar {
- background: var(--jss_header_background);
-}
-
-.jss_content::-webkit-scrollbar-track {
- background: var(--jss_background_head);
-}
-
-.jss_content::-webkit-scrollbar-thumb {
- background: var(--jss_background_head_highlighted);
-}
-
-.jss_border_main {
- border: 1px solid #000;
- border-color: var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .highlight {
- background-color: var(--jss_content_background_highlighted);
-}
-
-.jss_worksheet .highlight-bottom {
- border-bottom: 1px solid var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .highlight-right {
- border-right: 1px solid var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .highlight-left {
- border-left: 1px solid var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .highlight-top {
- border-top: 1px solid var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .copying-top {
- border-top-color: var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .copying-right {
- border-right-color: var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .copying-left {
- border-left-color: var(--jss_border_color_highlighted);
-}
-
-.jss_worksheet .copying-bottom {
- border-bottom-color: var(--jss_border_color_highlighted);
-}
-
-.jss_border_main,
-.jss_worksheet .highlight-top.highlight-left,
-.jss_worksheet .highlight-top,
-.jss_worksheet .highlight-left {
- box-shadow: unset;
-}
-
-table.jss_worksheet > thead > tr > td.selected {
- background-color: var(--jss_header_background_highlighted);
- color: var(--jss_header_color_highlighted);
-}
-
-// Hides about item in context menu
-.jcontextmenu > div:not(.contextmenu-line):last-child {
- display: none;
-}
-
-.jss_container {
- min-width: 100%;
- padding: 0;
-
- .jss_content {
- min-width: 100%;
- padding: 0;
-
- table.jss_worksheet {
- min-width: 100%;
- }
- }
-}
diff --git a/app/assets/stylesheets/common/table-builder/table-edit-decorator.scss b/app/assets/stylesheets/common/table-builder/table-edit-decorator.scss
deleted file mode 100644
index caa7f149d9f..00000000000
--- a/app/assets/stylesheets/common/table-builder/table-edit-decorator.scss
+++ /dev/null
@@ -1,34 +0,0 @@
-@use "lib/viewport";
-
-.btn-edit-table {
- -webkit-touch-callout: none;
- user-select: none;
-}
-
-.fullscreen-table-wrapper:hover .fullscreen-table-wrapper__buttons button {
- opacity: 100%;
-}
-
-.fullscreen-table-wrapper {
- .discourse-no-touch & {
- &__buttons {
- position: absolute;
- top: 0.5rem;
- right: 0.5rem;
- }
- }
-
- .discourse-touch & {
- @include viewport.until(xl) {
- display: flex;
- flex-direction: column-reverse;
- padding-bottom: 0.5em;
-
- .open-popup-link {
- opacity: 100%;
- left: 0;
- margin: var(--space-2) 0 0;
- }
- }
- }
-}
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 16892af0535..f0f1d3a0a07 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3904,6 +3904,7 @@ en:
show_preview: "Show preview"
table:
+ default_heading: "Column %{number}"
add_row: "Add row"
add_column: "Add column"
insert_row_above: "Insert above"
@@ -6732,63 +6733,6 @@ en:
pattern_mismatch: "Please match the requested format."
bad_input: "Please enter a valid input."
- table_builder:
- title: "Table Builder"
- modal:
- title: "Table Builder"
- create: "Build Table"
- help:
- title: "Using the Spreadsheet Editor"
- enter_key: "Enter"
- tab_key: "Tab"
- new_row: "at the end of a row to insert a new row."
- new_col: "at the end of a column to insert a new column."
- options: "Right-click on cells to access more options in a dropdown menu."
- confirm_close: "Are you sure you want to close the table builder? Any unsaved changes will be lost."
- edit:
- btn_edit: "Edit Table"
- modal:
- title: "Edit Table"
- cancel: "cancel"
- create: "Save"
- reason: "Why are you editing?"
- trigger_reason: "Add reason for edit"
- default_edit_reason: "Update Table with Table Editor"
- default_header:
- col_1: "Column 1"
- col_2: "Column 2"
- col_3: "Column 3"
- col_4: "Column 4"
- spreadsheet:
- no_records_found: "No records found"
- show: "Show"
- entries: "entries"
- about: "About"
- prompts:
- delete_selected_rows: "Are you sure you want to delete the selected rows?"
- delete_selected_cols: "Are you sure you want to delete the selected columns?"
- will_destroy_merged_cells: "This action will destroy any existing merged cells. Are you sure?"
- will_clear_search_results: "This action will destroy any existing merged cells. Are you sure?"
- conflicts_with_merged_cells: "There is a conflict with another merged cell"
- invalid_merge_props: "Invalid merged properties"
- cells_already_merged: "Cell already merged"
- no_cells_selected: "No cells selected"
- context_menu:
- row:
- before: "Insert a new row before"
- after: "Insert a new row after"
- delete: "Delete selected rows"
- col:
- before: "Insert a new column before"
- after: "Insert a new column after"
- delete: "Delete selected columns"
- rename: "Rename this column"
- order:
- ascending: "Order ascending"
- descending: "Order descending"
- copy: "Copy..."
- paste: "Paste..."
- save: "Save as..."
powered_by_discourse: "Powered by Discourse"
safari_15_warning: "Your browser will soon be incompatible with this community. To keep participating here, please upgrade your browser or <a href='%{url}'>learn more</a>."
diff --git a/frontend/discourse/app/components/modal/spreadsheet-editor.gjs b/frontend/discourse/app/components/modal/spreadsheet-editor.gjs
deleted file mode 100644
index 64c713af713..00000000000
--- a/frontend/discourse/app/components/modal/spreadsheet-editor.gjs
+++ /dev/null
@@ -1,441 +0,0 @@
-import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import { service } from "@ember/service";
-import { waitForPromise } from "@ember/test-waiters";
-import DTooltip from "discourse/float-kit/components/d-tooltip";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-import {
- arrayToTable,
- replaceTableRaw,
- tokenRange,
-} from "discourse/lib/utilities";
-import DButton from "discourse/ui-kit/d-button";
-import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
-import DModal from "discourse/ui-kit/d-modal";
-import DModalCancel from "discourse/ui-kit/d-modal-cancel";
-import DTextField from "discourse/ui-kit/d-text-field";
-import { i18n } from "discourse-i18n";
-
-export default class SpreadsheetEditor extends Component {
- @service dialog;
- @service keyboardShortcuts;
-
- @tracked showEditReason = false;
- @tracked loading = true;
-
- /** @type {HTMLElement | import("jspreadsheet-ce").WorksheetInstance | null} */
- spreadsheet = null;
- defaultColWidth = 150;
- isEditingTable = !!this.args.model.tableTokens;
-
- /** @type {("left" | "center" | "right" | null)[] | null} */
- alignments = null;
-
- /** @type {string | null} */
- initialSnapshot = null;
-
- constructor() {
- super(...arguments);
- this.loadJspreadsheet();
- this.keyboardShortcuts.pause();
- }
-
- willDestroy() {
- super.willDestroy(...arguments);
- this.keyboardShortcuts.unpause();
- }
-
- get modalAttributes() {
- if (this.isEditingTable) {
- return {
- title: "table_builder.edit.modal.title",
- insertTable: {
- title: "table_builder.edit.modal.create",
- icon: "pencil",
- },
- };
- } else {
- return {
- title: "table_builder.modal.title",
- insertTable: {
- title: "table_builder.modal.create",
- icon: "plus",
- },
- };
- }
- }
-
- get hasChanges() {
- return (
- this.initialSnapshot !== null &&
- this.captureSnapshot() !== this.initialSnapshot
- );
- }
-
- @action
- createSpreadsheet(spreadsheet) {
- this.spreadsheet = spreadsheet;
-
- if (this.isEditingTable) {
- this.buildPopulatedTable(this.args.model.tableTokens);
- } else {
- this.buildNewTable();
- }
-
- this.initialSnapshot = this.captureSnapshot();
- }
-
- @action
- showEditReasonField() {
- this.showEditReason = !this.showEditReason;
- }
-
- @action
- confirmClose() {
- if (!this.hasChanges) {
- return true;
- }
-
- return this.dialog.yesNoConfirm({
- message: i18n("table_builder.modal.confirm_close"),
- });
- }
-
- @action
- async cancelClose() {
- if (await this.confirmClose()) {
- this.args.closeModal();
- }
- }
-
- @action
- insertTable() {
- const updatedHeaders = this.spreadsheet
- .getHeaders()
- .split(",")
- .map((c) => c.trim()); // keys
- const updatedData = this.spreadsheet.getData(); // values
- const markdownTable = this.buildTableMarkdown(updatedHeaders, updatedData);
-
- if (!this.isEditingTable) {
- this.args.model.toolbarEvent.addText(markdownTable);
- return this.args.closeModal();
- } else {
- return this.updateTable(markdownTable);
- }
- }
-
- captureSnapshot() {
- return JSON.stringify({
- headers: this.spreadsheet.getHeaders(),
- data: this.spreadsheet.getData(),
- });
- }
-
- async loadJspreadsheet() {
- const [jspreadsheetModule] = await waitForPromise(
- Promise.all([
- import(/* dynamicChunkName: "jspreadsheet" */ "jspreadsheet-ce"),
- import("jspreadsheet-ce/dist/jspreadsheet.css"),
- import("jsuites/dist/jsuites.css"),
- ])
- );
-
- this.jspreadsheet = jspreadsheetModule.default;
- this.jspreadsheet.setDictionary(this.localeMapping());
- this.loading = false;
- }
-
- buildNewTable() {
- const data = [
- ["", "", ""],
- ["", "", ""],
- ["", "", ""],
- ["", "", ""],
- ["", "", ""],
- ["", "", ""],
- ];
-
- const columns = [
- {
- title: i18n("table_builder.default_header.col_1"),
- width: this.defaultColWidth,
- },
- {
- title: i18n("table_builder.default_header.col_2"),
- width: this.defaultColWidth,
- },
- {
- title: i18n("table_builder.default_header.col_3"),
-
- width: this.defaultColWidth,
- },
- {
- title: i18n("table_builder.default_header.col_4"),
-
- width: this.defaultColWidth,
- },
- ];
-
- return this.buildSpreadsheet(data, columns);
- }
-
- extractTableContent(data) {
- return data
- .flat()
- .filter((t) => t.type === "inline")
- .map((t) => t.content);
- }
-
- extractTableAlignments(data) {
- return data
- .flat()
- .filter((t) => t.type === "td_open")
- .map((t) => {
- for (const attr of t.attrs?.flat() ?? []) {
- switch (attr) {
- case "text-align:left":
- return "left";
- case "text-align:center":
- return "center";
- case "text-align:right":
- return "right";
- }
- }
- return null; // default
- });
- }
-
- buildPopulatedTable(tableTokens) {
- const tableOpen = tableTokens.find((t) => t.type === "table_open");
- this.tableLineRange = tableOpen?.map;
- const contentRows = tokenRange(tableTokens, "tr_open", "tr_close");
- const rows = [];
- let headings;
- const rowWidthFactor = 8;
-
- contentRows.forEach((row, index) => {
- if (index === 0) {
- // headings
- headings = this.extractTableContent(row).map((heading) => {
- return {
- title: heading || " ",
- width: Math.max(
- heading.length * rowWidthFactor,
- this.defaultColWidth
- ),
- };
- });
- } else {
- if (this.alignments == null) {
- this.alignments = this.extractTableAlignments(row);
- }
- // rows:
- rows.push(this.extractTableContent(row));
- }
- });
-
- headings.forEach((h, i) => {
- h.align = this.alignments?.[i] ?? "left";
- });
-
- return this.buildSpreadsheet(rows, headings);
- }
-
- buildSpreadsheet(data, columns, opts = {}) {
- const postNumber = this.args.model?.post_number;
- const exportFileName = postNumber
- ? `post-${postNumber}-table-export`
- : `post-table-export`;
-
- const worksheets = this.jspreadsheet(this.spreadsheet, {
- worksheets: [
- {
- data,
- columns,
- defaultColAlign: "left",
- wordWrap: true,
- csvFileName: exportFileName,
- ...opts,
- },
- ],
- });
-
- this.spreadsheet = worksheets[0];
- }
-
- buildUpdatedPost(tableIndex, raw, newRaw) {
- if (!this.tableLineRange) {
- return raw;
- }
- let editedTable = replaceTableRaw(raw, this.tableLineRange, newRaw);
- editedTable = editedTable.replace(/\0/g, "\ufffd");
- return editedTable;
- }
-
- updateTable(markdownTable) {
- const tableIndex = this.args.model.tableIndex;
- const postId = this.args.model.post.id;
- const newRaw = markdownTable;
-
- const editReason =
- this.editReason || i18n("table_builder.edit.default_edit_reason");
- const raw = this.args.model.post.raw;
- const newPostRaw = this.buildUpdatedPost(tableIndex, raw, newRaw);
-
- return this.sendTableUpdate(postId, newPostRaw, editReason);
- }
-
- sendTableUpdate(postId, raw, edit_reason) {
- return ajax(`/posts/${postId}.json`, {
- type: "PUT",
- data: {
- post: {
- raw,
- edit_reason,
- },
- },
- })
- .catch(popupAjaxError)
- .finally(() => {
- this.args.closeModal();
- });
- }
-
- buildTableMarkdown(headers, data) {
- const table = [];
- data.forEach((row) => {
- const result = {};
-
- headers.forEach((_key, index) => {
- const columnKey = `col${index}`;
- return (result[columnKey] = row[index]);
- });
- table.push(result);
- });
-
- return arrayToTable(table, headers, "col", this.alignments);
- }
-
- localeMapping() {
- return {
- noRecordsFound: prefixedLocale("no_records_found"),
- show: prefixedLocale("show"),
- entries: prefixedLocale("entries"),
- insertANewColumnBefore: prefixedLocale("context_menu.col.before"),
- insertANewColumnAfter: prefixedLocale("context_menu.col.after"),
- deleteSelectedColumns: prefixedLocale("context_menu.col.delete"),
- renameThisColumn: prefixedLocale("context_menu.col.rename"),
- orderAscending: prefixedLocale("context_menu.order.ascending"),
- orderDescending: prefixedLocale("context_menu.order.descending"),
- insertANewRowBefore: prefixedLocale("context_menu.row.before"),
- insertANewRowAfter: prefixedLocale("context_menu.row.after"),
- deleteSelectedRows: prefixedLocale("context_menu.row.delete"),
- copy: prefixedLocale("context_menu.copy"),
- paste: prefixedLocale("context_menu.paste"),
- saveAs: prefixedLocale("context_menu.save"),
- about: prefixedLocale("about"),
- areYouSureToDeleteTheSelectedRows: prefixedLocale(
- "prompts.delete_selected_rows"
- ),
- areYouSureToDeleteTheSelectedColumns: prefixedLocale(
- "prompts.delete_selected_cols"
- ),
- thisActionWillDestroyAnyExistingMergedCellsAreYouSure: prefixedLocale(
- "prompts.will_destroy_merged_cells"
- ),
- thisActionWillClearYourSearchResultsAreYouSure: prefixedLocale(
- "prompts.will_clear_search_results"
- ),
- thereIsAConflictWithAnotherMergedCell: prefixedLocale(
- "prompts.conflict_with_merged_cells"
- ),
- invalidMergeProperties: prefixedLocale("invalid_merge_props"),
- cellAlreadyMerged: prefixedLocale("cells_already_merged"),
- noCellsSelected: prefixedLocale("no_cells_selected"),
- };
- }
-
- <template>
- <DModal
- class="insert-table-modal"
- @beforeClose={{this.confirmClose}}
- @closeModal={{@closeModal}}
- @title={{i18n this.modalAttributes.title}}
- >
- <:body>
- <DConditionalLoadingSpinner @condition={{this.loading}}>
- <div
- class="jexcel_container"
- tabindex="1"
- {{didInsert this.createSpreadsheet}}
- ></div>
- </DConditionalLoadingSpinner>
- </:body>
-
- <:footer>
- {{#unless this.loading}}
- <div class="primary-actions">
- <DButton
- class="btn-insert-table"
- @action={{this.insertTable}}
- @icon={{this.modalAttributes.insertTable.icon}}
- @label={{this.modalAttributes.insertTable.title}}
- />
-
- <DModalCancel @close={{this.cancelClose}} />
- </div>
-
- <div class="secondary-actions">
- {{#if this.isEditingTable}}
- <div class="edit-reason">
- <DButton
- class="btn-edit-reason"
- @action={{this.showEditReasonField}}
- @icon="circle-info"
- @title="table_builder.edit.modal.trigger_reason"
- />
- {{#if this.showEditReason}}
- <DTextField
- @placeholderKey="table_builder.edit.modal.reason"
- @value={{this.editReason}}
- />
- {{/if}}
- </div>
- {{/if}}
- <DTooltip
- class="btn btn-icon no-text"
- @arrow={{false}}
- @icon="question"
- >
- <ul>
- <h4>{{i18n "table_builder.modal.help.title"}}</h4>
- <li>
- <kbd>
- {{i18n "table_builder.modal.help.enter_key"}}
- </kbd>
- {{i18n "table_builder.modal.help.new_row"}}
- </li>
- <li>
- <kbd>
- {{i18n "table_builder.modal.help.tab_key"}}
- </kbd>
- {{i18n "table_builder.modal.help.new_col"}}
- </li>
- <li>{{i18n "table_builder.modal.help.options"}}</li>
- </ul>
- </DTooltip>
- </div>
- {{/unless}}
-
- </:footer>
- </DModal>
- </template>
-}
-
-function prefixedLocale(localeString) {
- return i18n(`table_builder.spreadsheet.${localeString}`);
-}
diff --git a/frontend/discourse/app/instance-initializers/post-decorations.js b/frontend/discourse/app/instance-initializers/post-decorations.js
index 097909f5c1c..5b1f7d8cb07 100644
--- a/frontend/discourse/app/instance-initializers/post-decorations.js
+++ b/frontend/discourse/app/instance-initializers/post-decorations.js
@@ -1,8 +1,5 @@
import { schedule } from "@ember/runloop";
import FullscreenTableModal from "discourse/components/modal/fullscreen-table";
-import SpreadsheetEditor from "discourse/components/modal/spreadsheet-editor";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
import Columns from "discourse/lib/columns";
import highlightSyntax from "discourse/lib/highlight-syntax";
import { iconElement, iconHTML } from "discourse/lib/icon-library";
@@ -10,9 +7,7 @@ import setupImageGridCarousel from "discourse/lib/image-grid-carousel";
import { nativeLazyLoading } from "discourse/lib/lazy-load-images";
import lightbox from "discourse/lib/lightbox";
import { withPluginApi } from "discourse/lib/plugin-api";
-import { parseAsync } from "discourse/lib/text";
import { setTextDirections } from "discourse/lib/text-direction";
-import { tokenRange } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
export default {
@@ -160,69 +155,23 @@ export default {
});
}
- async function generateSpreadsheetModal() {
- const { postId, tableIndex } = this;
-
- try {
- const post = await ajax(`/posts/${postId}`, { type: "GET" });
- const tokens = await parseAsync(post.raw);
- const allTables = tokenRange(tokens, "table_open", "table_close");
- const tableTokens = allTables[tableIndex];
-
- modal.show(SpreadsheetEditor, {
- model: {
- post,
- tableIndex,
- tableTokens,
- },
- });
- } catch (error) {
- popupAjaxError(error);
- }
- }
-
function generatePopups(tables, post) {
- tables.forEach((table, index) => {
+ tables.forEach((table) => {
if (
table.parentNode.querySelector(".fullscreen-table-wrapper__buttons")
) {
return;
}
- const buttonWrapper = document.createElement("div");
- buttonWrapper.classList.add("fullscreen-table-wrapper__buttons");
-
- const tableEditorBtn = _createButton({
- classes: ["btn-edit-table"],
- title: "table_builder.edit.btn_edit",
- icon: {
- name: "pencil",
- class: "edit-table-icon",
- },
- });
-
- table.parentNode.setAttribute("data-table-index", index);
table.parentNode.classList.add("fullscreen-table-wrapper");
- if (post.can_edit) {
- table.parentNode.classList.add("--editable");
- buttonWrapper.append(tableEditorBtn);
- tableEditorBtn.addEventListener(
- "click",
- generateSpreadsheetModal.bind({
- postId: post.id,
- tableIndex: index,
- }),
- false
- );
- }
-
- table.parentNode.insertBefore(buttonWrapper, table);
-
if (site.mobileView || !isOverflown(table.parentNode)) {
return;
}
+ const buttonWrapper = document.createElement("div");
+ buttonWrapper.classList.add("fullscreen-table-wrapper__buttons");
+
table.parentNode.classList.add("--has-overflow");
const expandTableBtn = _createButton({
diff --git a/frontend/discourse/app/lib/utilities.js b/frontend/discourse/app/lib/utilities.js
index 0afac8ce296..2de62745892 100644
--- a/frontend/discourse/app/lib/utilities.js
+++ b/frontend/discourse/app/lib/utilities.js
@@ -713,54 +713,6 @@ export function getCaretPosition(element, options) {
return adjustedPosition;
}
-/**
- * Generate markdown table from an array of objects
- * Inspired by https://github.com/Ygilany/array-to-table
- *
- * @param {Array<Record<string, string | undefined>>} array Array of objects
- * @param {String[]} columns Column headings
- * @param {String} colPrefix Table column prefix
- * @param {("left" | "center" | "right" | null)[] | undefined} alignments Table alignments
- *
- * @return {String} Markdown table
- */
-export function arrayToTable(array, cols, colPrefix = "col", alignments) {
- const escapeCell = (value) =>
- String(value ?? "")
- .replace(/\r?\n|\r/g, " ")
- .replaceAll("|", "\\|");
-
- let table = "";
-
- table += "|";
- table += cols.map(escapeCell).join(" | ");
- table += "|\n|";
-
- const alignMap = {
- left: ":--",
- center: ":-:",
- right: "--:",
- };
-
- // Generate table header separator
- table += cols
- .map((_, index) => alignMap[String(alignments?.[index])] || "---")
- .join(" | ");
- table += "|\n";
-
- // Generate table body
- array.forEach(function (item) {
- table += "|";
-
- table +=
- cols
- .map((_key, index) => escapeCell(item[`${colPrefix}${index}`]))
- .join(" | ") + "|\n";
- });
-
- return table;
-}
-
/**
*
* @returns a regular expression finding all markdown tables
@@ -769,37 +721,6 @@ export function findTableRegex() {
return /((\r?){2}|^)(^\|[^\r\n]*(\r?\n)?)+(?=(\r?\n){2}|$)/gm;
}
-export function replaceTableRaw(raw, lineRange, newTableRaw) {
- const lines = raw.split("\n");
- const before = lines.slice(0, lineRange[0]);
- const after = lines.slice(lineRange[1]);
- return [...before, ...newTableRaw.trimEnd().split("\n"), ...after].join("\n");
-}
-
-export function tokenRange(tokens, start, end) {
- const contents = [];
- let startPushing = false;
- let items = [];
-
- tokens.forEach((token) => {
- if (token.type === start) {
- startPushing = true;
- }
-
- if (token.type === end) {
- contents.push(items);
- items = [];
- startPushing = false;
- }
-
- if (startPushing) {
- items.push(token);
- }
- });
-
- return contents;
-}
-
export function allowOnlyNumericInput(event, allowNegative = false) {
const ALLOWED_KEYS = [
"Enter",
diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.js
index 30fe6de398a..533a9411a0c 100644
--- a/frontend/discourse/app/services/composer.js
+++ b/frontend/discourse/app/services/composer.js
@@ -10,7 +10,6 @@ import { Promise } from "rsvp";
import ChangeReplyTo from "discourse/components/modal/change-reply-to";
import DiscardDraftModal from "discourse/components/modal/discard-draft";
import PostEnqueuedModal from "discourse/components/modal/post-enqueued";
-import SpreadsheetEditor from "discourse/components/modal/spreadsheet-editor";
import TopicReplyChoiceDialog from "discourse/components/topic-reply-choice-dialog";
import WrapAttributesModal from "discourse/components/wrap-attributes-modal";
import {
@@ -553,7 +552,7 @@ export default class ComposerService extends Service {
options.push(
this._setupPopupMenuOption({
name: "toggle-spreadsheet",
- action: "toggleSpreadsheet",
+ action: "insertTable",
icon: "table",
label: "composer.insert_table",
})
@@ -1017,13 +1016,19 @@ export default class ComposerService extends Service {
}
@action
- toggleSpreadsheet() {
- this.modal.show(SpreadsheetEditor, {
- model: {
- toolbarEvent: this.toolbarEvent,
- tableTokens: null,
- },
- });
+ insertTable() {
+ const headings = [1, 2, 3, 4].map((number) =>
+ i18n("composer.table.default_heading", { number })
+ );
+
+ this.appEvents.trigger(
+ "composer:insert-block",
+ [
+ `| ${headings.join(" | ")} |`,
+ `|${" --- |".repeat(headings.length)}`,
+ `|${" |".repeat(headings.length)}`,
+ ].join("\n")
+ );
}
@action
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index 9b8c41ea647..0cadb937b7d 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -77,7 +77,6 @@
"ember-source": "~7.3.0",
"highlight.js": "11.12.0",
"immer": "^11.1.21",
- "jspreadsheet-ce": "^5.0.4",
"minimasonry": "^1.3.2",
"moment": "2.31.0",
"moment-timezone": "0.6.5",
@@ -165,7 +164,6 @@
"expect-type": "^1.4.0",
"jquery": "^4.0.0",
"js-yaml": "^5.4.3",
- "jsuites": "^5.13.3",
"message-bus-client": "^4.6.0",
"pretender": "^3.4.7",
"qunit": "^3.0.0",
diff --git a/frontend/discourse/tests/acceptance/composer-insert-table-test.js b/frontend/discourse/tests/acceptance/composer-insert-table-test.js
new file mode 100644
index 00000000000..31921b87e59
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/composer-insert-table-test.js
@@ -0,0 +1,70 @@
+import { click, fillIn, find, visit, waitFor } from "@ember/test-helpers";
+import { test } from "qunit";
+import { USER_OPTION_COMPOSITION_MODES } from "discourse/lib/constants";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+const TABLE = [
+ "| Column 1 | Column 2 | Column 3 | Column 4 |",
+ "| --- | --- | --- | --- |",
+ "| | | | |",
+].join("\n");
+
+async function insertTable() {
+ await click(".toolbar-menu__options-trigger");
+ await click("button[data-name='toggle-spreadsheet']");
+}
+
+acceptance("Composer - Insert table | Markdown editor", function (needs) {
+ needs.user({
+ "user_option.composition_mode": USER_OPTION_COMPOSITION_MODES.markdown,
+ });
+
+ test("inserts a Markdown table into a reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+ await fillIn(".d-editor-input", "Some text");
+ await insertTable();
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `Some text\n\n${TABLE}\n`,
+ "the table starts on its own line, ready to edit"
+ );
+ });
+
+ test("inserts a Markdown table when editing a post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#post_1 .show-more-actions");
+ await click("#post_1 .edit");
+ await insertTable();
+
+ assert.true(
+ find(".d-editor-input").value.includes(TABLE),
+ "the table is added to the post's Markdown"
+ );
+ });
+});
+
+acceptance("Composer - Insert table | rich editor", function (needs) {
+ needs.user({
+ "user_option.composition_mode": USER_OPTION_COMPOSITION_MODES.rich,
+ });
+
+ test("inserts a table with editing controls", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await waitFor("#reply-control .ProseMirror");
+ await insertTable();
+
+ assert
+ .dom("#reply-control .ProseMirror table th")
+ .exists({ count: 4 }, "the table has four columns");
+ assert
+ .dom("#reply-control .ProseMirror table th")
+ .hasText("Column 1", "the columns have default headings");
+ assert
+ .dom("#reply-control .ProseMirror .composer-table__append")
+ .exists("the structural editing controls are available");
+ });
+});
diff --git a/frontend/discourse/tests/acceptance/table-builder-test.js b/frontend/discourse/tests/acceptance/table-builder-test.js
deleted file mode 100644
index 5b7c875d0d4..00000000000
--- a/frontend/discourse/tests/acceptance/table-builder-test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import { click, visit } from "@ember/test-helpers";
-import { test } from "qunit";
-import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-
-acceptance(`Table Builder`, function (needs) {
- needs.user();
-
- test("Can see table builder button when creating a topic", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await click(".toolbar-menu__options-trigger");
-
- assert
- .dom("button[data-name='toggle-spreadsheet']")
- .exists("it shows the builder button");
- });
-
- test("Can see table builder button when editing post", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#post_1 .show-more-actions");
- await click("#post_1 .edit");
- assert.dom("#reply-control").exists();
- await click(".toolbar-menu__options-trigger");
-
- assert
- .dom("button[data-name='toggle-spreadsheet']")
- .exists("it shows the builder button");
- });
-});
diff --git a/frontend/discourse/tests/fixtures/md-table.js b/frontend/discourse/tests/fixtures/md-table.js
deleted file mode 100644
index 5802a943703..00000000000
--- a/frontend/discourse/tests/fixtures/md-table.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export const mdTable = `|Make | Model | Year|\n|--- | --- | ---|\n|Toyota | Supra | 1998|\n|Nissan | Skyline | 1999|\n|Honda | S2000 | 2001|\n`;
-export const mdTableSpecialChars = `|Make | Model | Price|\n|--- | --- | ---|\n|Toyota | Supra | $50,000|\n| | Celica | $20,000|\n|Nissan | GTR | $80,000|\n`;
-export const mdTableNonUniqueHeadings = `|col1 | col2 | col1|\n|--- | --- | ---|\n|Col A | Col B | Col C|\n`;
diff --git a/frontend/discourse/tests/unit/lib/utilities-test.js b/frontend/discourse/tests/unit/lib/utilities-test.js
index 4144fea2e10..c393b15c83e 100644
--- a/frontend/discourse/tests/unit/lib/utilities-test.js
+++ b/frontend/discourse/tests/unit/lib/utilities-test.js
@@ -5,7 +5,6 @@ import { module, test } from "qunit";
import sinon from "sinon";
import { withSilencedDeprecations } from "discourse/lib/deprecated";
import {
- arrayToTable,
caretRowCol,
clipboardCopyAsync,
defaultHomepage,
@@ -17,7 +16,6 @@ import {
inCodeBlock,
initializeDefaultHomepage,
mergeSortedLists,
- replaceTableRaw,
selectedHTML,
setCaretPosition,
setDefaultHomepage,
@@ -27,11 +25,6 @@ import {
unicodeSlugify,
} from "discourse/lib/utilities";
import Site from "discourse/models/site";
-import {
- mdTable,
- mdTableNonUniqueHeadings,
- mdTableSpecialChars,
-} from "discourse/tests/fixtures/md-table";
import { chromeTest } from "discourse/tests/helpers/qunit-helpers";
import {
disableRaiseOnDeprecation,
@@ -494,155 +487,9 @@ module("Unit | Utilities | clipboard", function (hooks) {
);
});
-module("Unit | Utilities | table-builder", function (hooks) {
+module("Unit | Utilities | tables", function (hooks) {
setupTest(hooks);
- test("arrayToTable", function (assert) {
- const tableData = [
- {
- col0: "Toyota",
- col1: "Supra",
- col2: "1998",
- },
- {
- col0: "Nissan",
- col1: "Skyline",
- col2: "1999",
- },
- {
- col0: "Honda",
- col1: "S2000",
- col2: "2001",
- },
- ];
-
- assert.strictEqual(
- arrayToTable(tableData, ["Make", "Model", "Year"]),
- mdTable,
- "it creates a markdown table from an array of objects (with headers as keys)"
- );
-
- const specialCharsTableData = [
- {
- col0: "Toyota",
- col1: "Supra",
- col2: "$50,000",
- },
- {
- col0: "",
- col1: "Celica",
- col2: "$20,000",
- },
- {
- col0: "Nissan",
- col1: "GTR",
- col2: "$80,000",
- },
- ];
-
- assert.strictEqual(
- arrayToTable(specialCharsTableData, ["Make", "Model", "Price"]),
- mdTableSpecialChars,
- "it creates a markdown table with special characters in correct alignment"
- );
-
- const nonUniqueColumns = ["col1", "col2", "col1"];
-
- assert.strictEqual(
- arrayToTable(
- [{ col0: "Col A", col1: "Col B", col2: "Col C" }],
- nonUniqueColumns
- ),
- mdTableNonUniqueHeadings,
- "it does not suppress a column if heading is the same as another column"
- );
- });
- test("arrayToTable with custom column prefix", function (assert) {
- const tableData = [
- {
- A0: "hey",
- A1: "you",
- },
- {
- A0: "over",
- A1: "there",
- },
- ];
-
- assert.strictEqual(
- arrayToTable(tableData, ["Col 1", "Col 2"], "A"),
- `|Col 1 | Col 2|\n|--- | ---|\n|hey | you|\n|over | there|\n`,
- "it works"
- );
- });
-
- test("arrayToTable returns valid table with multiline cell data", function (assert) {
- const tableData = [
- {
- col0: "Jane\nDoe",
- col1: "Teri",
- },
- {
- col0: "Finch",
- col1: "Sami",
- },
- ];
-
- assert.strictEqual(
- arrayToTable(tableData, ["Col 1", "Col 2"]),
- `|Col 1 | Col 2|\n|--- | ---|\n|Jane Doe | Teri|\n|Finch | Sami|\n`,
- "it creates a valid table"
- );
- });
-
- test("arrayToTable with alignment specification", function (assert) {
- const tableData = [
- { col0: "left", col1: "center", col2: "right", col3: "unspecificated" },
- { col0: "111", col1: "222", col2: "333", col3: "444" },
- ];
- const alignment = ["left", "center", "right", null];
- assert.strictEqual(
- arrayToTable(
- tableData,
- ["Col 1", "Col 2", "Col 3", "Col 4"],
- "col",
- alignment
- ),
- "|Col 1 | Col 2 | Col 3 | Col 4|\n|:-- | :-: | --: | ---|\n|left | center | right | unspecificated|\n|111 | 222 | 333 | 444|\n",
- "it creates a valid table"
- );
- });
-
- test("arrayToTable escapes `|` in headings and cells", function (assert) {
- const tableData = [
- {
- col0: "`a|b`",
- col1: "![image|200x50](/images/discourse-logo-sketch.png)",
- col2: "",
- col3: "|",
- },
- { col0: "1|1", col1: "2|2", col2: "3|3", col3: "4|4" },
- ];
- assert.strictEqual(
- arrayToTable(tableData, ["Col | 1", "Col 2", "Col 3", "Col 4"]),
- "|Col \\| 1 | Col 2 | Col 3 | Col 4|\n|--- | --- | --- | ---|\n|`a\\|b` | ![image\\|200x50](/images/discourse-logo-sketch.png) | | \\||\n|1\\|1 | 2\\|2 | 3\\|3 | 4\\|4|\n",
- "it creates a valid table"
- );
- });
-
- test("replaceTableRaw", function (assert) {
- const raw = "Some text\n\nMaterial | Value\n--- | ---\nA | 1\n\nMore text";
- const result = replaceTableRaw(
- raw,
- [2, 5],
- "| Material | Value |\n| --- | --- |\n| A | 1 |"
- );
- assert.strictEqual(
- result,
- "Some text\n\n| Material | Value |\n| --- | --- |\n| A | 1 |\n\nMore text"
- );
- });
-
test("findTableRegex", function (assert) {
const oneTable = `|Make|Model|Year|\n|--- | --- | ---|\n|Toyota|Supra|1998|`;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a85dec1ca92..90d5a3c7f48 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -501,9 +501,6 @@ importers:
immer:
specifier: ^11.1.21
version: 11.1.21
- jspreadsheet-ce:
- specifier: ^5.0.4
- version: 5.0.4
minimasonry:
specifier: ^1.3.2
version: 1.3.2
@@ -760,9 +757,6 @@ importers:
js-yaml:
specifier: ^5.4.3
version: 5.4.3
- jsuites:
- specifier: ^5.13.3
- version: 5.13.3
message-bus-client:
specifier: ^4.6.0
version: 4.6.0
@@ -2464,9 +2458,6 @@ packages:
resolution: {integrity: sha512-Xo10c+q5pt6Zu2YKu0acSnarB+eZ3Qui0pE04I7ikA02m/78OwU4Vz3qso8mb74iYsf44SZgbZrwiptFyrnhzw==}
engines: {node: '>= 0.8.0'}
- '@jspreadsheet/[email protected]':
- resolution: {integrity: sha512-PDQYf9REQA53I7tVYkvkeyQxrd5jcjUeHgItYnRpjN2QiIQwawSqBDtGGEVQTSboTG+JwgGCuhvOpj7FxeKwew==}
-
resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==}
engines: {node: '>= 18'}
@@ -5802,12 +5793,6 @@ packages:
resolution: {integrity: sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==}
- resolution: {integrity: sha512-ra1JI1n+tEGgRMzTzNkPZjG0HZz8W6bFGAiTiHl+eYarXdRmS5qDc/ua3l2ev7oZ6Og9kjfrXYHVLUWiVc308w==}
-
- resolution: {integrity: sha512-je27Vu9Sl+jBnUQmyX+WWenK6ThSBP4NufDgOZhlZ7eRAHn6SdiB9dg5eMqCRkzhw2N4MywemYkx1B0aze8eSA==}
-
resolution: {integrity: sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw==}
@@ -10128,8 +10113,6 @@ snapshots:
dependencies:
core-js: 3.50.0
- '@jspreadsheet/[email protected]': {}
-
dependencies:
hashery: 1.5.1
@@ -14152,13 +14135,6 @@ snapshots:
- dependencies:
- '@jspreadsheet/formula': 2.0.2
- jsuites: 5.13.3
-
-
diff --git a/spec/system/composer_insert_table_spec.rb b/spec/system/composer_insert_table_spec.rb
new file mode 100644
index 00000000000..13f99b349e5
--- /dev/null
+++ b/spec/system/composer_insert_table_spec.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+describe "Composer insert table" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:post) { create_post(user: user, topic: topic, raw: <<~RAW) }
+ |Make | Model | Year|
+ |--- | --- | ---|
+ |Toyota | Supra | 1998|
+ RAW
+
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before { sign_in(user) }
+
+ def use_composition_mode(mode)
+ user.user_option.update!(composition_mode: UserOption.composition_mode_types[mode])
+ end
+
+ def insert_table
+ find(".toolbar-menu__options-trigger").click
+ find("button[data-name='toggle-spreadsheet']").click
+ end
+
+ context "with the Markdown editor" do
+ before { use_composition_mode(:markdown) }
+
+ it "inserts a Markdown table" do
+ visit("/latest")
+ find("#create-topic").click
+ composer.fill_content("Some text")
+ insert_table
+
+ expect(composer).to have_value(<<~MD)
+ Some text
+
+ | Column 1 | Column 2 | Column 3 | Column 4 |
+ | --- | --- | --- | --- |
+ | | | | |
+ MD
+ end
+ end
+
+ context "with the rich editor" do
+ before { use_composition_mode(:rich) }
+
+ it "inserts a table with structural editing controls" do
+ visit("/latest")
+ find("#create-topic").click
+ expect(composer).to have_rich_editor
+
+ insert_table
+
+ expect(composer.rich_editor).to have_css("table th", count: 4)
+ expect(composer.rich_editor).to have_css("table th", text: "Column 1")
+ expect(composer.rich_editor).to have_css(".composer-table__append", visible: :all)
+ end
+ end
+
+ it "does not offer to edit tables in published posts" do
+ topic_page.visit_topic(topic)
+
+ expect(topic_page).to have_post_content(post_number: 1, content: "Toyota")
+ expect(page).to have_no_css(".btn-edit-table", visible: :all)
+ end
+end
diff --git a/spec/system/page_objects/modals/insert_table.rb b/spec/system/page_objects/modals/insert_table.rb
deleted file mode 100644
index 81cb7187c68..00000000000
--- a/spec/system/page_objects/modals/insert_table.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-# frozen_string_literal: true
-
-module PageObjects
- module Modals
- class InsertTable < PageObjects::Modals::Base
- MODAL_SELECTOR = ".insert-table-modal"
- SPREADSHEET_TABLE_SELECTOR = "#{MODAL_SELECTOR} .jss_worksheet"
-
- def click_insert_table
- find("#{MODAL_SELECTOR} .btn-insert-table").click
- end
-
- def cancel
- click_button(I18n.t("js.cancel"))
- end
-
- def click_edit_reason
- find("#{MODAL_SELECTOR} .btn-edit-reason").click
- end
-
- def type_edit_reason(text)
- find("#{MODAL_SELECTOR} .edit-reason input").send_keys(text)
- end
-
- def find_cell(row, col)
- find("#{SPREADSHEET_TABLE_SELECTOR} tbody tr[data-y='#{row}'] td[data-x='#{col}']")
- end
-
- def select_cell(row, col)
- find_cell(row, col).double_click
- end
-
- def type_in_cell(row, col, text)
- select_cell(row, col)
- cell = find_cell(row, col).find("textarea")
- cell.send_keys(text, :return)
- end
-
- def has_content_in_cell?(row, col, content)
- find_cell(row, col).text == content
- end
- end
- end
-end
diff --git a/spec/system/table_builder_spec.rb b/spec/system/table_builder_spec.rb
deleted file mode 100644
index 47c7ef2458e..00000000000
--- a/spec/system/table_builder_spec.rb
+++ /dev/null
@@ -1,202 +0,0 @@
-# frozen_string_literal: true
-
-describe "Table Builder" do
- fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
- let(:composer) { PageObjects::Components::Composer.new }
- let(:insert_table_modal) { PageObjects::Modals::InsertTable.new }
- fab!(:topic) { Fabricate(:topic, user: user) }
- fab!(:topic2) { Fabricate(:topic, user: user) }
- fab!(:post1) { create_post(user: user, topic: topic, raw: <<~RAW) }
- |Make | Model | Year|
- |--- | --- | ---|
- |Toyota | Supra | 1998|
- |Nissan | Skyline | 1999|
- |Honda | S2000 | 2001|
- RAW
- fab!(:post2) { create_post(user: user, topic: topic2, raw: <<~RAW) }
- | | | |
- |--- | --- | ---|
- |Some | content | here|
- |1 | 2 | 3|
- RAW
-
- let(:topic_page) { PageObjects::Pages::Topic.new }
-
- before { sign_in(user) }
-
- def normalize_value(content)
- content.strip.gsub(/\s+/, " ").gsub(/\r\n/, "\n")
- end
-
- context "when creating a new table" do
- it "adds spreadsheet table items to the composer" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.type_in_cell(0, 1, "Item 2")
- insert_table_modal.type_in_cell(0, 2, "Item 3")
- insert_table_modal.type_in_cell(0, 3, "Item 4")
- insert_table_modal.click_insert_table
-
- created_table = <<~TABLE
- |Column 1 | Column 2 | Column 3 | Column 4|
- |--- | --- | --- | ---|
- |Item 1 | Item 2 | Item 3 | Item 4|
- | | | | |
- | | | | |
- | | | | |
- | | | | |
- | | | | |
- TABLE
-
- expect(normalize_value(composer.composer_input.value)).to eq(normalize_value(created_table))
- end
-
- context "when cancelling table creation" do
- it "closes the modal when nothing changed" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
- end
-
- it "warns about unsaved changes" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
- end
- end
- end
-
- context "when editing a table" do
- it "prefills the spreadsheet from the post's Markdown table" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
-
- expected_table_content = [
- %w[Toyota Supra 1998],
- %w[Nissan Skyline 1999],
- %w[Honda S2000 2001],
- ]
-
- expected_table_content.each_with_index do |row, row_index|
- row.each_with_index do |content, col_index|
- expect(insert_table_modal).to have_content_in_cell(row_index, col_index, content)
- end
- end
- end
-
- it "updates the post with the new table content" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_insert_table
-
- updated_post = <<~RAW
- |Make | Model | Year|
- |--- | --- | ---|
- |Toyota | Supra | 1998|
- |Nissan | Skyline GTR | 1999|
- |Honda | S2000 | 2001|
- RAW
-
- expect(normalize_value(post1.reload.raw)).to eq(normalize_value(updated_post))
- end
-
- it "preserves an empty table header" do
- topic_page.visit_topic(topic2)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(0, 0, " updated")
- insert_table_modal.click_insert_table
-
- updated_post = <<~RAW
- | | | |
- |--- | --- | ---|
- |Some updated | content | here|
- |1 | 2 | 3|
- RAW
-
- expect(normalize_value(post2.reload.raw)).to eq(normalize_value(updated_post))
- end
-
- context "when adding an edit reason" do
- it "adds the edit reason to the revision history" do
- edit_reason = "Updated Nissan model"
-
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_edit_reason
- insert_table_modal.type_edit_reason(edit_reason)
- insert_table_modal.click_insert_table
- wait_for { post1.reload.edit_reason == edit_reason }
- expect(post1.reload.edit_reason).to eq(edit_reason)
- end
- end
-
- context "when cancelling table creation" do
- it "closes the modal when nothing changed" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
- end
-
- it "closes the modal if there are no changes in a table with empty headers" do
- topic_page.visit_topic(topic2)
- topic_page.find(".btn-edit-table", visible: :all).click
- insert_table_modal.cancel
-
- expect(page).to have_no_css(".insert-table-modal")
- end
-
- it "warns about unsaved changes" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
- end
- end
-
- it "ignores default Discourse keyboard shortcuts" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- insert_table_modal.find_cell(0, 0)
- insert_table_modal.send_keys(:shift, "s")
- expect(page).to have_css(".insert-table-modal")
- expect(page).to have_no_css(".share-topic-modal")
- end
-
- it "does not show duplicate edit buttons on quoted tables" do
- raw = <<~MD
- [quote="#{user.username}, post:#{post1.post_number}, topic:#{topic.id}"]
- |Make | Model | Year|
- | - | - | - |
- | Toyota | Supra | 1998 |
- [/quote]
- MD
-
- quoting_post = create_post(user:, topic:, raw:)
- topic_page.visit_topic(topic)
-
- within "#post_#{quoting_post.post_number}" do
- expect(page).to have_css(".btn-edit-table", count: 1, visible: :all)
- end
- end
- end
-end