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

knowledgepixels / nanodash / 29574247112

17 Jul 2026 10:40AM UTC coverage: 28.791% (-0.6%) from 29.361%
29574247112

Pull #560

github

web-flow
Merge b16ec84aa into 809bff55b
Pull Request #560: Show dates in a consistent format

1960 of 7501 branches covered (26.13%)

Branch coverage included in aggregate %.

3818 of 12568 relevant lines covered (30.38%)

4.55 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
            super(new Model<String>(title), dataKey);
×
258
            this.key = key;
×
259
            this.dataKey = dataKey;
×
260
            this.cssClass = cssClass;
×
261
        }
×
262

263
        @Override
264
        public String getCssClass() {
265
            return cssClass;
×
266
        }
267

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

413
    }
414

415
    private static String truncateLabel(String label) {
416
        return Utils.truncateLabel(label);
×
417
    }
418

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

© 2026 Coveralls, Inc