• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanodash / 33625200928

02 Sep 2026 11:33AM UTC coverage: 41.305% (+0.2%) from 41.108%
33625200928

Pull #675

github

web-flow
Merge 8c20503a2 into ed01f6487
Pull Request #675: fix(view tables): make ordering by a column visible and correct

3803 of 9947 branches covered (38.23%)

Branch coverage included in aggregate %.

6943 of 16069 relevant lines covered (43.21%)

6.85 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
src/main/java/com/knowledgepixels/nanodash/component/QueryResultTable.java
1
package com.knowledgepixels.nanodash.component;
2

3
import com.knowledgepixels.nanodash.*;
4
import com.knowledgepixels.nanodash.component.menu.EntryActionMenu;
5
import com.knowledgepixels.nanodash.page.ExplorePage;
6
import com.knowledgepixels.nanodash.page.NanodashPage;
7
import com.knowledgepixels.nanodash.page.PublishPage;
8
import org.apache.wicket.Component;
9
import org.apache.wicket.ajax.AjaxRequestTarget;
10
import org.apache.wicket.behavior.AttributeAppender;
11
import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackHeadersToolbar;
12
import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxNavigationToolbar;
13
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
14
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
15
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
16
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
17
import org.apache.wicket.extensions.markup.html.repeater.data.table.IStyledColumn;
18
import org.apache.wicket.markup.html.WebMarkupContainer;
19
import org.apache.wicket.markup.html.basic.Label;
20
import org.apache.wicket.markup.html.form.TextField;
21
import org.apache.wicket.markup.html.link.AbstractLink;
22
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
23
import org.apache.wicket.markup.html.list.ListItem;
24
import org.apache.wicket.markup.html.list.ListView;
25
import org.apache.wicket.markup.repeater.Item;
26
import org.apache.wicket.model.IModel;
27
import org.apache.wicket.model.Model;
28
import org.apache.wicket.model.util.ListModel;
29
import org.apache.wicket.request.mapper.parameter.PageParameters;
30
import org.apache.wicket.util.string.Strings;
31
import org.nanopub.extra.services.ApiResponse;
32
import org.nanopub.extra.services.ApiResponseEntry;
33
import org.nanopub.extra.services.QueryRef;
34
import org.slf4j.Logger;
35
import org.slf4j.LoggerFactory;
36

37
import java.util.ArrayList;
38
import java.util.Collections;
39
import java.util.List;
40
import java.util.Set;
41

42
/**
43
 * Component for displaying query results in a table format.
44
 */
45
public class QueryResultTable extends QueryResult {
46

47
    private static final Logger logger = LoggerFactory.getLogger(QueryResultTable.class);
×
48

49
    private Model<String> errorMessages = Model.of("");
×
50
    private DataTable<ApiResponseEntry, String> table;
51
    private Label noRecordsLabel;
52
    private Label errorLabel;
53
    private FilteredQueryResultDataProvider filteredDataProvider;
54
    private Model<String> filterModel = Model.of("");
×
55
    // The source-nanopub column ("np"/"nps"), folded into the per-row actions dropdown.
56
    private String sourceColumnKey;
57

58
    QueryResultTable(String id, QueryRef queryRef, ApiResponse response, ViewDisplay viewDisplay, boolean plain) {
59
        super(id, queryRef, response, viewDisplay);
×
60

61
        if (plain) {
×
62
            add(new Label("label").setVisible(false));
×
63
            add(new Label("np").setVisible(false));
×
64
            showViewDisplayMenu = false;
×
65
        } else {
66
            String label = grlcQuery.getLabel();
×
67
            if (viewDisplay.getTitle() != null) {
×
68
                label = viewDisplay.getTitle();
×
69
            }
70
            add(new Label("label", label).setVisible(label != null && !label.isEmpty()));
×
71
        }
72

73
        errorLabel = new Label("error-messages", errorMessages);
×
74
        errorLabel.setVisible(false);
×
75
        add(errorLabel);
×
76

77
        TextField<String> filterField = new TextField<>("filter", filterModel);
×
78
        filterField.setOutputMarkupId(true);
×
79
        filterField.add(new FilterUpdatingBehavior() {
×
80
            @Override
81
            protected void onUpdate(AjaxRequestTarget target) {
82
                if (filteredDataProvider != null && table != null) {
×
83
                    filteredDataProvider.setFilterText(filterModel.getObject());
×
84
                    target.add(table);
×
85
                    if (noRecordsLabel != null) {
×
86
                        target.add(noRecordsLabel);
×
87
                    }
88
                }
89
            }
×
90
        });
91
        filterField.setVisible(!fitsOnFirstPage());
×
92
        add(filterField);
×
93

94
        populateComponent();
×
95
    }
×
96

97
    private void addErrorMessage(String errorMessage) {
98
        String s = errorMessages.getObject();
×
99
        if (s.isEmpty()) {
×
100
            s = "Error: " + errorMessage;
×
101
        } else {
102
            s += ", " + errorMessage;
×
103
        }
104
        errorMessages.setObject(s);
×
105
        errorLabel.setVisible(true);
×
106
        if (table != null) {
×
107
            table.setVisible(false);
×
108
        }
109
    }
×
110

111
    @Override
112
    protected void populateComponent() {
113
        List<IColumn<ApiResponseEntry, String>> columns = new ArrayList<>();
×
114
        QueryResultDataProvider dataProvider;
115
        try {
116
            // Columns that only feed action query mappings (conditional targets, the
117
            // local-key bundle) carry action data, not row content — don't render them.
118
            Set<String> hiddenColumns = viewDisplay.getView() != null
×
119
                    ? viewDisplay.getView().getActionMappingSourceColumns() : Collections.emptySet();
×
120
            // The source-nanopub column ("np"/"nps") is no longer rendered as its own
121
            // column; it becomes the "source" entry of this row's actions dropdown.
122
            sourceColumnKey = null;
×
123
            for (String h : response.getHeader()) {
×
124
                if (h.equals("np") || h.equals("nps")) {
×
125
                    sourceColumnKey = h;
×
126
                }
127
            }
128
            // Whether any rendered column carries a visible header label. If none do
129
            // (every column is "_noheader"), the entire header row is dropped — see the
130
            // gated addTopToolbar below.
131
            boolean anyHeaderShown = false;
×
132
            for (String h : response.getHeader()) {
×
133
                if (h.endsWith("_label") || h.endsWith("_label_multi")
×
134
                    || hiddenColumns.contains(h) || h.equals(sourceColumnKey)) {
×
135
                    continue;
×
136
                }
137
                // A trailing "_noheader" hides this column's header label while still
138
                // rendering the column. It is stripped first to recover the logical
139
                // column key, so every other rule (type suffix, _label companion,
140
                // action mappings) operates unchanged on the unmarked name.
141
                boolean noHeader = h.endsWith("_noheader");
×
142
                String key = noHeader ? h.substring(0, h.length() - "_noheader".length()) : h;
×
143
                String displayLabel = key;
×
144
                if (displayLabel.endsWith("_multi_iri")) {
×
145
                    displayLabel = displayLabel.substring(0, displayLabel.length() - "_multi_iri".length());
×
146
                } else if (displayLabel.endsWith("_multi_val")) {
×
147
                    displayLabel = displayLabel.substring(0, displayLabel.length() - "_multi_val".length());
×
148
                } else if (displayLabel.endsWith("_multi")) {
×
149
                    displayLabel = displayLabel.substring(0, displayLabel.length() - "_multi".length());
×
150
                } else if (displayLabel.endsWith("_iri")) {
×
151
                    displayLabel = displayLabel.substring(0, displayLabel.length() - "_iri".length());
×
152
                }
153
                String columnHeader = displayLabel.replaceAll("_", " ");
×
154
                if (noHeader) {
×
155
                    columns.add(new Column("", h, key, null));
×
156
                } else {
157
                    anyHeaderShown = true;
×
158
                    columns.add(new Column(columnHeader, h, key, null));
×
159
                }
160
            }
161
            // A single trailing dropdown column bundling this row's entry-level actions
162
            // and its "source" link, shown whenever either is present.
163
            boolean hasEntryActions = viewDisplay.getView() != null
×
164
                                      && !viewDisplay.getView().getViewEntryActionList().isEmpty();
×
165
            if (hasEntryActions || sourceColumnKey != null) {
×
166
                columns.add(new Column("", Column.ACTIONS, "cell-right"));
×
167
            }
168
            dataProvider = new QueryResultDataProvider(response.getData());
×
169
            filteredDataProvider = new FilteredQueryResultDataProvider(dataProvider, response);
×
170
            // The whole table (header included) is hidden when there is nothing to show;
171
            // a "(nothing found)" note is shown instead. No NoRecordsToolbar, since that
172
            // would leave the header row visible.
173
            table = new DataTable<>("table", columns, filteredDataProvider, viewDisplay.getPageSize() < 1 ? Integer.MAX_VALUE : viewDisplay.getPageSize()) {
×
174
                @Override
175
                protected void onConfigure() {
176
                    super.onConfigure();
×
177
                    setVisible(errorMessages.getObject().isEmpty() && filteredDataProvider.size() > 0);
×
178
                }
×
179
            };
180
            table.setOutputMarkupPlaceholderTag(true);
×
181
            // Marker class so nanodash.js can wrap emoji in body cells with the same
182
            // monochrome .emoji styling used for headings (e.g. the ✅/⚠️ key-approval
183
            // annotations in the "keys" column).
184
            table.add(new AttributeAppender("class", "result-table"));
×
185
            table.addBottomToolbar(new AjaxNavigationToolbar(table));
×
186
            // Drop the header row entirely when no column has a visible header label.
187
            if (anyHeaderShown) {
×
188
                table.addTopToolbar(new AjaxFallbackHeadersToolbar<String>(table, dataProvider));
×
189
            }
190
            add(table);
×
191
            // Hidden when the empty-actions line below shows instead, which carries
192
            // its own "Nothing here yet:" text; this note still covers the case of
193
            // the filter text matching no row.
194
            noRecordsLabel = new Label("no-records", "(nothing found)") {
×
195
                @Override
196
                protected void onConfigure() {
197
                    super.onConfigure();
×
198
                    setVisible(errorMessages.getObject().isEmpty() && filteredDataProvider.size() == 0 && !hasEmptyStateActions());
×
199
                }
×
200
            };
201
            noRecordsLabel.setOutputMarkupPlaceholderTag(true);
×
202
            add(noRecordsLabel);
×
203
            // When the result is genuinely empty (not merely filtered down to zero
204
            // rows), the view-level actions are promoted from the dropdown menu to
205
            // visible buttons in the empty state, pointing e.g. a space admin to
206
            // "add preset..." as the next step. menuActions only ever contains
207
            // actions the viewer is entitled to (see QueryResultTableBuilder), so
208
            // everyone else just gets the plain note. The same actions stay in the
209
            // dropdown menu, which remains their place once the table has content.
210
            WebMarkupContainer emptyActions = new WebMarkupContainer("empty-actions") {
×
211
                @Override
212
                protected void onConfigure() {
213
                    super.onConfigure();
×
214
                    setVisible(errorMessages.getObject().isEmpty() && hasEmptyStateActions());
×
215
                }
×
216
            };
217
            // menuActions is filled by the builder after construction, so the list
218
            // is wrapped as a live model rather than copied here.
219
            emptyActions.add(new ListView<MenuAction>("actions", new ListModel<>(menuActions)) {
×
220
                @Override
221
                protected void populateItem(ListItem<MenuAction> item) {
222
                    MenuAction action = item.getModelObject();
×
223
                    AbstractLink link = new BookmarkablePageLink<NanodashPage>("link", action.pageClass(), action.params());
×
224
                    link.setBody(Model.of(action.label()));
×
225
                    item.add(link);
×
226
                }
×
227
            });
228
            add(emptyActions);
×
229
        } catch (Exception ex) {
×
230
            logger.error("Error creating table for query {}", grlcQuery.getQueryId(), ex);
×
231
            add(new Label("table", "").setVisible(false));
×
232
            add(new Label("no-records", "").setVisible(false));
×
233
            add(new Label("empty-actions", "").setVisible(false));
×
234
            addErrorMessage(ex.getMessage());
×
235
        }
×
236
    }
×
237

238
    private class Column extends AbstractColumn<ApiResponseEntry, String> implements IStyledColumn<ApiResponseEntry, String> {
239

240
        private String key;
241
        // The actual response-column name to read row data from. Differs from the
242
        // logical key only for "_noheader" columns, whose marker is kept here but
243
        // stripped from key so all name-matching uses the unmarked name.
244
        private String dataKey;
245
        private String cssClass;
246
        public static final String ACTIONS = "*actions*";
247

248
        public Column(String title, String key) {
249
            this(title, key, key, null);
×
250
        }
×
251

252
        public Column(String title, String key, String cssClass) {
253
            this(title, key, key, cssClass);
×
254
        }
×
255

256
        public Column(String title, String dataKey, String key, String cssClass) {
×
257
            // Only a column with a header label is sortable: an empty header is nothing to
258
            // click, and the actions column would otherwise offer to order the table by a
259
            // property no row has, giving a round trip that changes nothing (issue #673).
260
            super(new Model<String>(title), Strings.isEmpty(title) ? null : dataKey);
×
261
            this.key = key;
×
262
            this.dataKey = dataKey;
×
263
            this.cssClass = cssClass;
×
264
        }
×
265

266
        @Override
267
        public String getCssClass() {
268
            return cssClass;
×
269
        }
270

271
        @Override
272
        public void populateItem(Item<ICellPopulator<ApiResponseEntry>> cellItem, String componentId, IModel<ApiResponseEntry> rowModel) {
273
            try {
274
                View view = viewDisplay.getView();
×
275
                if (key.equals(ACTIONS)) {
×
276
                    List<AbstractLink> links = ViewActionMappings.buildEntryActionLinks(view, rowModel.getObject(),
×
277
                            queryRef, resourceWithProfile, contextId, partId, refRoot, postPublishTab);
×
278
                    // The former "^" source link joins the same dropdown, as a "source" entry.
279
                    if (sourceColumnKey != null) {
×
280
                        String sourceUri = rowModel.getObject().get(sourceColumnKey);
×
281
                        if (sourceUri != null && !sourceUri.isBlank()) {
×
282
                            AbstractLink sourceLink = new BookmarkablePageLink<NanodashPage>("link", ExplorePage.class,
×
283
                                    new PageParameters().set("id", sourceUri));
×
284
                            sourceLink.add(NavigationContext.pageContextFallback());
×
285
                            sourceLink.setBody(Model.of("<span class=\"actionmenu-icon\">↗︎</span>source")).setEscapeModelStrings(false);
×
286
                            links.add(sourceLink);
×
287
                        }
288
                    }
289
                    if (links.isEmpty()) {
×
290
                        cellItem.add(new Label(componentId).setVisible(false));
×
291
                    } else {
292
                        cellItem.add(new EntryActionMenu(componentId, links));
×
293
                    }
294
                } else {
×
295
                    String value = rowModel.getObject().get(dataKey);
×
296
                    if (key.endsWith("_multi_iri")) {
×
297
                        String labelKey = key.substring(0, key.length() - "_multi_iri".length()) + "_label_multi";
×
298
                        String labelValue = rowModel.getObject().get(labelKey);
×
299
                        String[] uris = (value == null || value.isBlank()) ? new String[0] : value.split("\\s+");
×
300
                        String[] labels = labelValue != null ? labelValue.split("\n", -1) : null;
×
301
                        List<Component> links = new ArrayList<>();
×
302
                        for (int i = 0; i < uris.length; i++) {
×
303
                            String uri = uris[i];
×
304
                            if (uri.isBlank()) {
×
305
                                continue;
×
306
                            }
307
                            String rawLabel = (labels != null && i < labels.length && !labels[i].isBlank()) ? Utils.unescapeMultiValue(labels[i]) : null;
×
308
                            // SPARQL coalesce often falls back to the URI string itself; treat that as no label
309
                            // so NanodashLink can derive a short name from the URI.
310
                            if (rawLabel != null && rawLabel.equals(uri)) {
×
311
                                rawLabel = null;
×
312
                            }
313
                            links.add(new NanodashLink("component", uri, null, null, rawLabel, contextId));
×
314
                        }
315
                        cellItem.add(new ComponentSequence(componentId, ", ", links));
×
316
                    } else if (key.endsWith("_multi_val")) {
×
317
                        String labelKey = key.substring(0, key.length() - "_multi_val".length()) + "_label_multi";
×
318
                        String labelValue = rowModel.getObject().get(labelKey);
×
319
                        String[] parts = (value == null) ? new String[0] : value.split("\n", -1);
×
320
                        String[] labels = labelValue != null ? labelValue.split("\n", -1) : null;
×
321
                        List<Component> components = new ArrayList<>();
×
322
                        for (int i = 0; i < parts.length; i++) {
×
323
                            String part = parts[i];
×
324
                            String rawLabel = (labels != null && i < labels.length && !labels[i].isBlank()) ? Utils.unescapeMultiValue(labels[i]) : null;
×
325
                            if (isPublishLink(part)) {
×
326
                                components.add(new Label("component", publishButtonHtml(part, rawLabel)).setEscapeModelStrings(false));
×
327
                            } else if (Utils.isUriValue(part)) {
×
328
                                if (rawLabel != null && rawLabel.equals(part)) {
×
329
                                    rawLabel = null;
×
330
                                }
331
                                components.add(new NanodashLink("component", part, null, null, rawLabel, contextId));
×
332
                            } else {
333
                                String label = rawLabel;
×
334
                                String unescaped = Utils.unescapeMultiValue(part);
×
335
                                if (label == null && Utils.isDate(unescaped)) {
×
336
                                    // Friendly relative time, matching single-value cells.
337
                                    components.add(new Label("component", Utils.friendlyDateHtml(unescaped, unescaped)).setEscapeModelStrings(false));
×
338
                                } else {
339
                                    String display = label != null ? label : unescaped;
×
340
                                    if (Utils.looksLikeHtml(display)) {
×
341
                                        components.add(new Label("component", cellHtml(display))
×
342
                                                .setEscapeModelStrings(false)
×
343
                                                .add(new AttributeAppender("class", "cell-data-html")));
×
344
                                    } else {
345
                                        components.add(new Label("component", display));
×
346
                                    }
347
                                }
348
                            }
349
                        }
350
                        cellItem.add(new ComponentSequence(componentId, ", ", components));
×
351
                    } else if (key.endsWith("_multi")) {
×
352
                        String labelKey = key.substring(0, key.length() - "_multi".length()) + "_label_multi";
×
353
                        String labelValue = rowModel.getObject().get(labelKey);
×
354
                        String[] parts = (value == null) ? new String[0] : value.split("\n", -1);
×
355
                        String[] labels = labelValue != null ? labelValue.split("\n", -1) : null;
×
356
                        List<Component> components = new ArrayList<>();
×
357
                        for (int i = 0; i < parts.length; i++) {
×
358
                            boolean hasLabel = labels != null && i < labels.length && !labels[i].isBlank();
×
359
                            String display = hasLabel ? Utils.unescapeMultiValue(labels[i]) : Utils.unescapeMultiValue(parts[i]);
×
360
                            if (!hasLabel && Utils.isDate(display)) {
×
361
                                // Friendly relative time, matching single-value cells.
362
                                components.add(new Label("component", Utils.friendlyDateHtml(display, display)).setEscapeModelStrings(false));
×
363
                            } else if (Utils.looksLikeHtml(display)) {
×
364
                                components.add(new Label("component", cellHtml(display))
×
365
                                        .setEscapeModelStrings(false)
×
366
                                        .add(new AttributeAppender("class", "cell-data-html")));
×
367
                            } else {
368
                                components.add(new Label("component", display));
×
369
                            }
370
                        }
371
                        cellItem.add(new ComponentSequence(componentId, ", ", components));
×
372
                    } else if (key.endsWith("template_iri")) {
×
373
                        String label = rowModel.getObject().get(key + "_label");
×
374
                        if (label == null || label.isBlank()) {
×
375
                            label = truncateLabel(value);
×
376
                        }
377
                        String templateUrl = PublishPage.MOUNT_PATH + "?template=" + Utils.urlEncode(value) + "&template-version=latest" + templateLinkContextParam();
×
378
                        String html = "<a href=\"" + Strings.escapeMarkup(templateUrl) + "\">" + Strings.escapeMarkup(label) + "</a>";
×
379
                        cellItem.add(new Label(componentId, html).setEscapeModelStrings(false));
×
380
                    } else if (isPublishLink(value)) {
×
381
                        // A ready-made link to the publish form: an action the view offers,
382
                        // shown as a button rather than as a link to content.
383
                        String label = rowModel.getObject().get(key + "_label");
×
384
                        cellItem.add(new Label(componentId, publishButtonHtml(value, label)).setEscapeModelStrings(false));
×
385
                    } else if (Utils.isUriValue(value)) {
×
386
                        String label = rowModel.getObject().get(key + "_label");
×
387
                        cellItem.add(new NanodashLink(componentId, value, null, null, label, contextId));
×
388
                    } else {
×
389
                        String litLabel = rowModel.getObject().get(key + "_label");
×
390
                        if (litLabel != null && !litLabel.isBlank() && !litLabel.equals(value)) {
×
391
                            // Separate display label for a (non-IRI) literal value; the full
392
                            // literal is shown on hover via the standard styled tooltip.
393
                            String labelHtml = Utils.looksLikeHtml(litLabel) ? cellHtml(litLabel) : Strings.escapeMarkup(litLabel).toString();
×
394
                            String html = "<span class=\"tooltip\"><span class=\"tooltiptext tooltiptext-auto\">" + Strings.escapeMarkup(value) + "</span>" + labelHtml + "</span>";
×
395
                            cellItem.add(new Label(componentId, html).setEscapeModelStrings(false));
×
396
                        } else if (key.startsWith("pubkey")) {
×
397
                            cellItem.add(new Label(componentId, value).add(new AttributeAppender("style", "overflow-wrap: anywhere;")));
×
398
                        } else if (Utils.isDate(value)) {
×
399
                            // Show a friendly relative time (client-side); raw ISO value stays as no-script fallback.
400
                            cellItem.add(new Label(componentId, Utils.friendlyDateHtml(value, value)).setEscapeModelStrings(false));
×
401
                        } else {
402
                            Label cellLabel;
403
                            if (Utils.looksLikeHtml(value)) {
×
404
                                cellLabel = (Label) new Label(componentId, cellHtml(value))
×
405
                                        .setEscapeModelStrings(false)
×
406
                                        .add(new AttributeAppender("class", "cell-data-html"));
×
407
                            } else {
408
                                cellLabel = new Label(componentId, value);
×
409
                            }
410
                            cellItem.add(cellLabel);
×
411
                        }
412
                    }
413
                }
414
            } catch (Exception ex) {
×
415
                logger.error("Failed to populate table column: ", ex);
×
416
                cellItem.add(new Label(componentId).setVisible(false));
×
417
                addErrorMessage(ex.getMessage());
×
418
            }
×
419
        }
×
420

421
    }
422

423
    private static String truncateLabel(String label) {
424
        return Utils.truncateLabel(label);
×
425
    }
426

427
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc