mensa 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/.shipkit.yml +1 -1
  3. data/CHANGELOG.md +26 -0
  4. data/Gemfile.lock +1 -1
  5. data/README.md +129 -0
  6. data/app/assets/stylesheets/mensa/application.css +2 -0
  7. data/app/components/mensa/cells/component.css +47 -0
  8. data/app/components/mensa/cells/component_controller.js +406 -0
  9. data/app/components/mensa/table/component.css +22 -0
  10. data/app/components/mensa/table/component.html.erb +18 -5
  11. data/app/components/mensa/table/component.rb +6 -1
  12. data/app/components/mensa/table/component_controller.js +52 -0
  13. data/app/components/mensa/table_row/component.rb +7 -3
  14. data/app/components/mensa/tree/component.css +28 -0
  15. data/app/components/mensa/tree/component_controller.js +99 -0
  16. data/app/components/mensa/view/component.html.erb +3 -5
  17. data/app/components/mensa/view/component.rb +22 -0
  18. data/app/controllers/concerns/mensa/table_from_request.rb +37 -0
  19. data/app/controllers/mensa/tables/commands_controller.rb +30 -0
  20. data/app/controllers/mensa/tables/rows_controller.rb +28 -0
  21. data/app/controllers/mensa/tables_controller.rb +3 -22
  22. data/app/javascript/mensa/controllers/index.js +6 -0
  23. data/app/tables/mensa/base.rb +37 -0
  24. data/app/tables/mensa/cell.rb +51 -2
  25. data/app/tables/mensa/column.rb +55 -0
  26. data/app/tables/mensa/command.rb +57 -0
  27. data/app/tables/mensa/config/column_dsl.rb +3 -0
  28. data/app/tables/mensa/config/command_dsl.rb +19 -0
  29. data/app/tables/mensa/config/editable_dsl.rb +27 -0
  30. data/app/tables/mensa/config/table_dsl.rb +18 -0
  31. data/app/tables/mensa/grouping.rb +2 -1
  32. data/app/tables/mensa/row.rb +24 -0
  33. data/app/tables/mensa/scope.rb +9 -0
  34. data/app/tables/mensa/tree.rb +157 -0
  35. data/app/tables/mensa/tree_paging.rb +38 -0
  36. data/app/views/mensa/tables/rows/update.turbo_stream.erb +3 -0
  37. data/config/locales/en.yml +4 -0
  38. data/config/locales/nl.yml +4 -0
  39. data/config/routes.rb +2 -0
  40. data/lib/mensa/configuration.rb +2 -0
  41. data/lib/mensa/version.rb +1 -1
  42. metadata +14 -1
@@ -46,3 +46,25 @@
46
46
  .mensa-table__search-container {
47
47
  @apply flex flex-1 min-w-0 items-stretch h-8 rounded-md bg-white dark:bg-gray-800;
48
48
  }
49
+
50
+ /* The rows, and with pane: true something drawn beside them (mensa:rows),
51
+ which takes the width the rows leave */
52
+ .mensa-table__body {
53
+ @apply block;
54
+ }
55
+
56
+ .mensa-table__body--with-pane {
57
+ @apply flex items-stretch;
58
+
59
+ > .mensa-table__rows {
60
+ @apply flex-none max-w-[60%] overflow-x-auto;
61
+ }
62
+
63
+ > .mensa-table__rows table {
64
+ @apply w-auto;
65
+ }
66
+
67
+ > .mensa-table__pane {
68
+ @apply relative min-w-0 flex-1 border-l border-gray-200 dark:border-gray-600;
69
+ }
70
+ }
@@ -12,6 +12,7 @@
12
12
  data-controller="mensa-table"
13
13
  <% end %>
14
14
  data-mensa-table-storage-key-value="<%= table.storage_key %>"
15
+ data-mensa-table-name-value="<%= table.name %>"
15
16
  data-action="click@document->mensa-table#saveDropdownOutsideHandler"
16
17
  data-mensa-table-mensa-filter-pill-list-outlet="#mensa-filter-pill-list-<%= table.table_id %>"
17
18
  data-mensa-table-mensa-column-customizer-outlet="#table-<%= table.table_id %> [data-controller='mensa-column-customizer']">
@@ -31,9 +32,21 @@
31
32
  <%= render Mensa::ControlBar::Component.new(table: table) %>
32
33
  </div>
33
34
  <%= render Mensa::Search::Component.new(table: table) %>
34
- <turbo-frame id="<%= table.table_id %>"
35
- target="_top"
36
- data-mensa-table-target="turboFrame"
37
- data-action="turbo:frame-load->mensa-table#captureNavigation turbo:before-frame-render->mensa-table#beforeFrameRender turbo:before-fetch-request->mensa-table#captureScrollPosition click->mensa-table#captureScrollPosition:capture turbo:frame-load->mensa-table#restoreScrollPosition"
38
- data-turbo-permanent></turbo-frame>
35
+ <%# The rows' frame is the table's own child, as apps style it; with a pane both are in a body beside each other %>
36
+ <% frame = capture do %>
37
+ <turbo-frame id="<%= table.table_id %>"
38
+ class="mensa-table__rows"
39
+ target="_top"
40
+ data-mensa-table-target="turboFrame"
41
+ data-action="turbo:frame-load->mensa-table#captureNavigation turbo:before-frame-render->mensa-table#beforeFrameRender turbo:before-fetch-request->mensa-table#captureScrollPosition click->mensa-table#captureScrollPosition:capture turbo:frame-load->mensa-table#restoreScrollPosition"
42
+ data-turbo-permanent></turbo-frame>
43
+ <% end %>
44
+ <% if pane? %>
45
+ <div class="mensa-table__body mensa-table__body--with-pane">
46
+ <%= frame %>
47
+ <div class="mensa-table__pane" data-mensa-table-target="pane"></div>
48
+ </div>
49
+ <% else %>
50
+ <%= frame %>
51
+ <% end %>
39
52
  </div>
@@ -8,8 +8,11 @@ module Mensa
8
8
  attr_reader :table
9
9
  attr_reader :params
10
10
 
11
- def initialize(table_name, params: {}, **options)
11
+ # pane: true leaves room beside the rows for something drawn against
12
+ # them (a timeline), see the mensa:rows event
13
+ def initialize(table_name, params: {}, pane: false, **options)
12
14
  @params = params
15
+ @pane = pane
13
16
  config = {params: params}
14
17
  view_lookup_table = Mensa.for_name(table_name, config)
15
18
  view = view_lookup_table.default_system_view
@@ -20,6 +23,8 @@ module Mensa
20
23
  @table.original_view_context = options[:original_view_context]
21
24
  @table.component = self
22
25
  end
26
+
27
+ def pane? = @pane
23
28
  end
24
29
  end
25
30
  end
@@ -19,6 +19,7 @@ export default class TableComponentController extends ApplicationController {
19
19
  "saveSimple",
20
20
  "saveSplit",
21
21
  "eyeButton",
22
+ "pane",
22
23
  ];
23
24
  static outlets = ["mensa-filter-pill-list", "mensa-column-customizer"];
24
25
  static values = {
@@ -28,6 +29,7 @@ export default class TableComponentController extends ApplicationController {
28
29
  viewsUrl: String,
29
30
  exportsUrl: String,
30
31
  storageKey: String,
32
+ name: String,
31
33
  };
32
34
 
33
35
  connect() {
@@ -35,6 +37,14 @@ export default class TableComponentController extends ApplicationController {
35
37
 
36
38
  this.frameLoadFallback = setTimeout(() => this.loadFrame(), 100);
37
39
  this.scrollLeft = 0;
40
+
41
+ // The rows' places, for what's drawn against them (mensa:rows)
42
+ this.layoutHandler = () => this.scheduleRowsEvent();
43
+ this.element.addEventListener("mensa:layout", this.layoutHandler);
44
+ if (typeof ResizeObserver === "function" && this.hasTurboFrameTarget) {
45
+ this.resizeObserver = new ResizeObserver(() => this.scheduleRowsEvent());
46
+ this.resizeObserver.observe(this.turboFrameTarget);
47
+ }
38
48
  }
39
49
 
40
50
  disconnect() {
@@ -42,6 +52,47 @@ export default class TableComponentController extends ApplicationController {
42
52
  clearTimeout(this.frameLoadFallback);
43
53
  this.frameLoadFallback = null;
44
54
  }
55
+ this.element.removeEventListener("mensa:layout", this.layoutHandler);
56
+ this.resizeObserver?.disconnect();
57
+ }
58
+
59
+ // --- The rows' places (mensa:rows) ---
60
+
61
+ scheduleRowsEvent() {
62
+ if (this.rowsEventFrame) return;
63
+ this.rowsEventFrame = requestAnimationFrame(() => {
64
+ this.rowsEventFrame = null;
65
+ this.dispatchRowsEvent();
66
+ });
67
+ }
68
+
69
+ // Tells what's beside the rows (a pane) where each row is: its id, top
70
+ // and height in pixels from the top of the rows' table (its header
71
+ // included), its depth in a tree, and whether it's hidden (folded away)
72
+ dispatchRowsEvent() {
73
+ if (!this.hasTurboFrameTarget) return;
74
+ const table = this.turboFrameTarget.querySelector("table");
75
+ if (!table) return;
76
+
77
+ const origin = table.getBoundingClientRect().top;
78
+ const header = table.querySelector("thead");
79
+ const rows = Array.from(table.querySelectorAll("tbody tr[data-mensa-id]")).map((row) => {
80
+ const rect = row.getBoundingClientRect();
81
+ const hidden = row.classList.contains("hidden") || row.offsetParent === null;
82
+ return {
83
+ id: row.dataset.mensaId,
84
+ top: hidden ? null : rect.top - origin,
85
+ height: hidden ? 0 : rect.height,
86
+ depth: parseInt(row.dataset.mensaDepth || "0", 10),
87
+ hidden,
88
+ };
89
+ });
90
+
91
+ this.triggerEvent(this.element, "mensa:rows", {
92
+ table: this.nameValue,
93
+ rows,
94
+ headerHeight: header ? header.getBoundingClientRect().height : 0,
95
+ });
45
96
  }
46
97
 
47
98
  saveDropdownOutsideHandler(event) {
@@ -383,6 +434,7 @@ export default class TableComponentController extends ApplicationController {
383
434
  // The rendered view carries the grouping the server applied, keep the
384
435
  // group-by popover in sync with it (e.g. after selecting a view).
385
436
  viewTargetConnected(element) {
437
+ this.scheduleRowsEvent();
386
438
  let aggregates = {};
387
439
  try {
388
440
  aggregates = JSON.parse(element.dataset.aggregates || "{}");
@@ -18,9 +18,13 @@ module Mensa
18
18
  end
19
19
 
20
20
  def row_attributes
21
- return row.link_attributes unless group
22
-
23
- row.link_attributes.deep_merge(data: {mensa_groups_target: "row", group_key: group.key})
21
+ attributes = row.link_attributes.deep_merge(data: {mensa_id: row.id})
22
+ attributes = attributes.deep_merge(data: {mensa_groups_target: "row", group_key: group.key}) if group
23
+ if table.tree?
24
+ attributes = attributes.deep_merge(data: {mensa_tree_target: "row", mensa_depth: row.depth})
25
+ attributes[:class] = "mensa-table__row--context" if row.context?
26
+ end
27
+ attributes
24
28
  end
25
29
  end
26
30
  end
@@ -0,0 +1,28 @@
1
+ /* A tree's first column: indented by the row's depth, with a toggle to fold
2
+ its children */
3
+ .mensa-tree__indent {
4
+ @apply inline-flex items-center align-middle mr-1;
5
+ padding-left: calc(var(--mensa-tree-depth, 0) * 1.25rem);
6
+ }
7
+
8
+ .mensa-tree__toggle,
9
+ .mensa-tree__leaf {
10
+ @apply inline-flex h-5 w-5 items-center justify-center;
11
+ }
12
+
13
+ .mensa-tree__toggle {
14
+ @apply rounded text-xs text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer transition-transform;
15
+
16
+ &[aria-expanded="false"] i {
17
+ @apply -rotate-90;
18
+ }
19
+
20
+ i {
21
+ @apply transition-transform;
22
+ }
23
+ }
24
+
25
+ /* An ancestor shown only for a match below it */
26
+ .mensa-table tbody tr.mensa-table__row--context td {
27
+ @apply text-gray-400 dark:text-gray-500;
28
+ }
@@ -0,0 +1,99 @@
1
+ import ApplicationController from "mensa/controllers/application_controller";
2
+
3
+ // Folds a tree's rows (`tree` tables): a row's toggle hides the rows below it
4
+ // that are deeper, which are its descendants as rows come depth first. Folded
5
+ // rows are remembered per table, by their ids.
6
+ export default class TreeController extends ApplicationController {
7
+ static targets = ["row"];
8
+
9
+ get storageKey() {
10
+ return `mensa:folded_rows:${this.tableStorageKey}`;
11
+ }
12
+
13
+ connect() {
14
+ super.connect();
15
+ this.folded = new Set(this._load());
16
+ this.apply();
17
+ }
18
+
19
+ toggle(event) {
20
+ // Not the row's link
21
+ event.preventDefault();
22
+ event.stopPropagation();
23
+ const row = event.currentTarget.closest("tr");
24
+ this.setFolded(row, !this.folded.has(row.dataset.mensaId));
25
+ }
26
+
27
+ setFolded(row, folded) {
28
+ if (!row || !row.querySelector(".mensa-tree__toggle")) return;
29
+
30
+ const id = row.dataset.mensaId;
31
+ if (folded) {
32
+ this.folded.add(id);
33
+ } else {
34
+ this.folded.delete(id);
35
+ }
36
+ this._save();
37
+ this.apply();
38
+ }
39
+
40
+ isFolded(row) {
41
+ return this.folded.has(row.dataset.mensaId);
42
+ }
43
+
44
+ hasChildren(row) {
45
+ return !!row.querySelector(".mensa-tree__toggle");
46
+ }
47
+
48
+ // The row it's under, the nearest one before it that is less deep
49
+ parentOf(row) {
50
+ const depth = this._depth(row);
51
+ let previous = row.previousElementSibling;
52
+ while (previous) {
53
+ if (previous.dataset.mensaDepth !== undefined && this._depth(previous) < depth) return previous;
54
+ previous = previous.previousElementSibling;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ apply() {
60
+ let foldedAt = null;
61
+ this.rowTargets.forEach((row) => {
62
+ const depth = this._depth(row);
63
+ if (foldedAt !== null && depth > foldedAt) {
64
+ row.classList.add("hidden");
65
+ return;
66
+ }
67
+ foldedAt = null;
68
+ row.classList.remove("hidden");
69
+
70
+ const toggle = row.querySelector(".mensa-tree__toggle");
71
+ const folded = toggle && this.folded.has(row.dataset.mensaId);
72
+ if (toggle) toggle.setAttribute("aria-expanded", (!folded).toString());
73
+ if (folded) foldedAt = depth;
74
+ });
75
+ this.triggerEvent(this.element, "mensa:layout", {});
76
+ }
77
+
78
+ _depth(row) {
79
+ return parseInt(row.dataset.mensaDepth || "0", 10);
80
+ }
81
+
82
+ _load() {
83
+ try {
84
+ return JSON.parse(window.localStorage.getItem(this.storageKey) || "[]");
85
+ } catch (e) {
86
+ return [];
87
+ }
88
+ }
89
+
90
+ _save() {
91
+ try {
92
+ if (this.folded.size > 0) {
93
+ window.localStorage.setItem(this.storageKey, JSON.stringify([...this.folded]));
94
+ } else {
95
+ window.localStorage.removeItem(this.storageKey);
96
+ }
97
+ } catch (e) { }
98
+ }
99
+ }
@@ -1,4 +1,5 @@
1
1
  <div data-mensa-table-target="view"
2
+ <%= tag.attributes(data: {mensa_select_id: table.select_id, mensa_edit: (table.edit_selected ? "first" : nil)}) %>
2
3
  data-group-by="<%= table.group_column&.name %>"
3
4
  data-aggregates="<%= table.current_aggregates.to_json %>">
4
5
  <div class="overflow-y-auto relative"
@@ -34,11 +35,8 @@
34
35
  </div>
35
36
  </div>
36
37
  <% end %>
37
- <table class="w-full"
38
- <% if table.grouped? %>
39
- data-controller="mensa-groups"
40
- data-mensa-groups-column-value="<%= table.group_column.name %>"
41
- <% end %>>
38
+ <table class="w-full<%= " mensa-table--tree" if table.tree? %><%= " mensa-table--keyboard" if table.keyboard? %>"
39
+ <%= tag.attributes(table_attributes) %>>
42
40
  <% if table.show_header? %>
43
41
  <thead>
44
42
  <tr>
@@ -12,6 +12,28 @@ module Mensa
12
12
  @table = table
13
13
  end
14
14
 
15
+ # The table element's attributes: its controllers, for grouping, the
16
+ # tree's folding and the keyboard (editing cells, commands)
17
+ def table_attributes
18
+ controllers = []
19
+ data = {}
20
+ if table.grouped?
21
+ controllers << "mensa-groups"
22
+ data[:mensa_groups_column_value] = table.group_column.name
23
+ end
24
+ controllers << "mensa-tree" if table.tree?
25
+ if table.keyboard?
26
+ controllers << "mensa-cells"
27
+ data[:action] = "keydown->mensa-cells#keydown click->mensa-cells#click:capture dblclick->mensa-cells#doubleClick"
28
+ data[:mensa_cells_rows_url_value] = table.path_with_params(helpers.mensa.table_path(table.name) + "/rows")
29
+ data[:mensa_cells_commands_url_value] = table.path_with_params(helpers.mensa.table_path(table.name) + "/commands")
30
+ data[:mensa_cells_commands_value] = table.commands.map { |command| {name: command.name, key: command.key} }.to_json
31
+ data[:mensa_cells_texts_value] = {not_saved: I18n.t("mensa.editing.not_saved")}.to_json
32
+ end
33
+ data[:controller] = controllers.join(" ") if controllers.any?
34
+ {data: data, tabindex: (table.keyboard? ? 0 : nil)}
35
+ end
36
+
15
37
  # "orders", "users", etc. — used in the paging info line.
16
38
  def model_name_plural
17
39
  table.model.model_name.human(count: 2)
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mensa
4
+ # Builds a table as the browser shows it, from what a request sends: its
5
+ # view, filters, search, order, page, columns and the table's params. For
6
+ # the table's own page and for endpoints that render it again.
7
+ module TableFromRequest
8
+ extend ActiveSupport::Concern
9
+
10
+ private
11
+
12
+ def table_from_request(name)
13
+ filters_provided = params.key?(:filters)
14
+ config = params.permit(:format, :query, :id, :page, :table_view_id, :turbo_frame_id, :group_by, order: {}, column_order: [], hidden_columns: [], params: {}, filters: {}, aggregates: {}).to_h
15
+ config.delete("id")
16
+ config[:filters] = {} if filters_provided && !config.key?(:filters)
17
+ # aggregates= (blank) means none, also when the view has some
18
+ config[:aggregates] = {} if params.key?(:aggregates) && !config.key?(:aggregates)
19
+
20
+ view_lookup_table = Mensa.for_name(name, config)
21
+ @view = if params[:table_view_id].present?
22
+ Mensa::TableView.find_by(table_name: name, id: params[:table_view_id]) ||
23
+ view_lookup_table.system_views.find { |v| v.id == params[:table_view_id].to_sym }
24
+ else
25
+ view_lookup_table.default_system_view
26
+ end
27
+
28
+ config = (@view&.config&.deep_transform_keys(&:to_sym) || {}).merge(config.deep_symbolize_keys)
29
+
30
+ table = Mensa.for_name(name, config)
31
+ table.request = request
32
+ table.table_view = @view
33
+ table.original_view_context = helpers
34
+ table
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mensa
4
+ module Tables
5
+ # Runs a command (a key on the selected row) with its record, and renders
6
+ # the table's rows again with the row it gives selected. Only records the
7
+ # table shows, and only when the command's show allows it.
8
+ class CommandsController < ::Mensa::ApplicationController
9
+ include Mensa::TableFromRequest
10
+
11
+ def create
12
+ @table = table_from_request(params[:table_id])
13
+ command = @table.commands.find { |c| c.name.to_s == params[:name].to_s }
14
+ record = @table.scope.find_by(@table.model.primary_key => params[:record_id])
15
+ return head :not_found unless command && record && command.show?(record)
16
+
17
+ selected = command.perform(record, helpers)
18
+ if selected.respond_to?(:id) && selected.persisted?
19
+ response.headers["X-Mensa-Select"] = selected.id.to_s
20
+ @table.select_id = selected.id
21
+ end
22
+ if command.edit?
23
+ response.headers["X-Mensa-Edit"] = "true"
24
+ @table.edit_selected = true
25
+ end
26
+ render "mensa/tables/rows/update", formats: :turbo_stream
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mensa
4
+ module Tables
5
+ # Saves a value edited in a cell (an editable column) with the table's
6
+ # update, and renders the table's rows again, as one change may change
7
+ # others. Only records the table shows, and only cells that may be edited.
8
+ class RowsController < ::Mensa::ApplicationController
9
+ include Mensa::TableFromRequest
10
+
11
+ def update
12
+ @table = table_from_request(params[:table_id])
13
+ column = @table.columns.find { |c| c.name.to_s == params[:column].to_s }
14
+ record = @table.scope.find_by(@table.model.primary_key => params[:id])
15
+ return head :not_found unless column && record && column.editable_for?(record)
16
+
17
+ result = @table.update_cell(record, column, params[:value], helpers)
18
+ if result == true
19
+ response.headers["X-Mensa-Select"] = record.id.to_s
20
+ @table.select_id = record.id
21
+ render "mensa/tables/rows/update", formats: :turbo_stream
22
+ else
23
+ render json: {errors: result}, status: :unprocessable_content
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -1,28 +1,9 @@
1
1
  module Mensa
2
2
  class TablesController < ApplicationController
3
- def show
4
- filters_provided = params.key?(:filters)
5
- config = params.permit(:format, :query, :id, :page, :table_view_id, :turbo_frame_id, :group_by, order: {}, column_order: [], hidden_columns: [], params: {}, filters: {}, aggregates: {}).to_h
6
- config[:filters] = {} if filters_provided && !config.key?(:filters)
7
- # aggregates= (blank) means none, also when the view has some
8
- config[:aggregates] = {} if params.key?(:aggregates) && !config.key?(:aggregates)
9
-
10
- @table = Mensa.for_name(params[:id], config)
11
-
12
- view_lookup_table = Mensa.for_name(params[:id], config)
13
- @view = if params[:table_view_id]
14
- Mensa::TableView.find_by(table_name: params[:id], id: params[:table_view_id]) ||
15
- view_lookup_table.system_views.find { |v| v.id == params[:table_view_id].to_sym }
16
- else
17
- view_lookup_table.default_system_view
18
- end
19
-
20
- config = (@view&.config&.deep_transform_keys(&:to_sym) || {}).merge(config)
3
+ include Mensa::TableFromRequest
21
4
 
22
- @table = Mensa.for_name(params[:id], config)
23
- @table.request = request
24
- @table.table_view = @view
25
- @table.original_view_context = helpers
5
+ def show
6
+ @table = table_from_request(params[:id])
26
7
 
27
8
  respond_to do |format|
28
9
  format.turbo_stream # Used for filtering
@@ -39,6 +39,12 @@ application.register("mensa-group-by", GroupByComponentController);
39
39
  import GroupHeaderComponentController from "mensa/components/group_header/component_controller";
40
40
  application.register("mensa-groups", GroupHeaderComponentController);
41
41
 
42
+ import TreeComponentController from "mensa/components/tree/component_controller";
43
+ application.register("mensa-tree", TreeComponentController);
44
+
45
+ import CellsComponentController from "mensa/components/cells/component_controller";
46
+ application.register("mensa-cells", CellsComponentController);
47
+
42
48
  import CopyableComponentController from "mensa/components/copyable/component_controller";
43
49
  application.register("mensa-copyable", CopyableComponentController);
44
50
 
@@ -8,6 +8,9 @@ module Mensa
8
8
 
9
9
  attr_writer :original_view_context
10
10
  attr_accessor :component, :name, :table_view, :request
11
+ # The row to select when the rows are rendered again (after an edit or a
12
+ # command), and whether to start editing it
13
+ attr_accessor :select_id, :edit_selected
11
14
 
12
15
  config_reader :params
13
16
  config_reader :model
@@ -131,6 +134,40 @@ module Mensa
131
134
  config[:actions].present?
132
135
  end
133
136
 
137
+ # The block saving a value edited in a cell (`update`)
138
+ def update_block
139
+ config[:update]
140
+ end
141
+
142
+ # Saves the value edited in the column's cell of the record: true, or the
143
+ # errors as an array
144
+ def update_cell(record, column, value, view_context = nil)
145
+ args = [record, column.name, value]
146
+ result = view_context ? view_context.instance_exec(*args, &update_block) : update_block.call(*args)
147
+ return true if result == true
148
+
149
+ errors = Array(result).flatten.compact_blank.map(&:to_s)
150
+ errors.presence || [I18n.t("mensa.editing.not_saved")]
151
+ end
152
+
153
+ def editable?
154
+ display_columns.any?(&:editable?)
155
+ end
156
+
157
+ def commands
158
+ @commands ||= (config[:commands] || {}).map { |name, command_config| Mensa::Command.new(name, config: command_config, table: self) }
159
+ end
160
+
161
+ def commands?
162
+ commands.any?
163
+ end
164
+
165
+ # Whether it has a selected cell, moved with the keyboard: with editable
166
+ # cells or commands
167
+ def keyboard?
168
+ editable? || commands?
169
+ end
170
+
134
171
  def actions
135
172
  return @actions if @actions
136
173
 
@@ -36,9 +36,46 @@ module Mensa
36
36
  def render(format)
37
37
  content = render_content(format)
38
38
  return content unless format.to_sym == :html
39
- return content if td?(content)
40
39
 
41
- content_tag(:td, content)
40
+ attributes = td_attributes
41
+ prefix = tree_prefix
42
+ return content_tag(:td, safe_join([prefix, content].compact), **attributes) unless td?(content)
43
+ return content if attributes.empty? && prefix.nil?
44
+
45
+ merge_into_td(content, attributes, prefix)
46
+ end
47
+
48
+ # The td's attributes: its column, and for a cell that may be edited how
49
+ def td_attributes
50
+ return {} unless row
51
+
52
+ attributes = {}
53
+ attributes[:data] = {mensa_column: column.name} if row.table.keyboard?
54
+ if column.editable_for?(row.record)
55
+ attributes[:class] = "mensa-table__cell--editable"
56
+ attributes[:data].merge!(
57
+ mensa_editable: true,
58
+ mensa_edit_as: column.edit_as,
59
+ mensa_edit_value: column.edit_value(row.record, value)
60
+ )
61
+ attributes[:data][:mensa_edit_collection] = column.edit_collection.to_json if column.edit_as == :select
62
+ end
63
+ attributes
64
+ end
65
+
66
+ # In a tree's first column: indented by its depth, with a button to fold
67
+ # its children
68
+ def tree_prefix
69
+ return unless row&.table&.tree? && row.table.display_columns.first == column
70
+
71
+ toggle = if row.children?
72
+ content_tag(:button, content_tag(:i, "", class: Mensa.config.icons[:tree_toggle] || "fa-solid fa-chevron-down"),
73
+ type: "button", class: "mensa-tree__toggle", aria: {expanded: true, label: I18n.t("mensa.tree.toggle")},
74
+ data: {action: "click->mensa-tree#toggle"})
75
+ else
76
+ content_tag(:span, "", class: "mensa-tree__leaf")
77
+ end
78
+ content_tag(:span, toggle, class: "mensa-tree__indent", style: "--mensa-tree-depth: #{row.depth}")
42
79
  end
43
80
 
44
81
  private
@@ -48,6 +85,18 @@ module Mensa
48
85
  content.html_safe? && content.to_s.lstrip.match?(/\A<td[\s>]/i)
49
86
  end
50
87
 
88
+ # A render block's own td, with the cell's attributes and prefix added
89
+ def merge_into_td(content, attributes, prefix)
90
+ fragment = Nokogiri::HTML::DocumentFragment.parse(content.to_s)
91
+ td = fragment.at_css("td")
92
+ return content unless td
93
+
94
+ attributes.fetch(:data, {}).each { |key, val| td["data-#{key.to_s.dasherize}"] = val.to_s }
95
+ td["class"] = [td["class"], attributes[:class]].compact.join(" ") if attributes[:class]
96
+ td.prepend_child(Nokogiri::HTML::DocumentFragment.parse(prefix.to_s)) if prefix
97
+ fragment.to_html.html_safe
98
+ end
99
+
51
100
  def render_content(format)
52
101
  proc = column.config.dig(:render, format.to_sym)
53
102
  if proc