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

knowledgepixels / nanodash / 28899187612

07 Jul 2026 09:14PM UTC coverage: 28.105% (-0.4%) from 28.465%
28899187612

Pull #543

github

web-flow
Merge 39c9ede0f into f1a7efda7
Pull Request #543: feat: query-form views (gen:QueryFormView) with view-results page

1813 of 7309 branches covered (24.81%)

Branch coverage included in aggregate %.

3717 of 12367 relevant lines covered (30.06%)

4.46 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.*;
15
import org.apache.wicket.markup.html.WebMarkupContainer;
16
import org.apache.wicket.markup.html.basic.Label;
17
import org.apache.wicket.markup.html.form.TextField;
18
import org.apache.wicket.markup.html.link.AbstractLink;
19
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
20
import org.apache.wicket.markup.html.list.ListItem;
21
import org.apache.wicket.markup.html.list.ListView;
22
import org.apache.wicket.util.string.Strings;
23
import org.apache.wicket.markup.repeater.Item;
24
import org.apache.wicket.model.IModel;
25
import org.apache.wicket.model.Model;
26
import org.apache.wicket.model.util.ListModel;
27
import org.apache.wicket.request.mapper.parameter.PageParameters;
28
import org.eclipse.rdf4j.model.IRI;
29
import org.nanopub.extra.services.ApiResponse;
30
import org.nanopub.extra.services.ApiResponseEntry;
31
import org.nanopub.extra.services.QueryRef;
32
import org.slf4j.Logger;
33
import org.slf4j.LoggerFactory;
34

35
import java.util.ArrayList;
36
import java.util.Collections;
37
import java.util.List;
38
import java.util.Set;
39

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

45
    private static final Logger logger = LoggerFactory.getLogger(QueryResultTable.class);
×
46

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

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

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

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

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

90
        populateComponent();
×
91
    }
×
92

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

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

230
    private class Column extends AbstractColumn<ApiResponseEntry, String> implements IStyledColumn<ApiResponseEntry, String> {
231

232
        private String key;
233
        // The actual response-column name to read row data from. Differs from the
234
        // logical key only for "_noheader" columns, whose marker is kept here but
235
        // stripped from key so all name-matching uses the unmarked name.
236
        private String dataKey;
237
        private String cssClass;
238
        public static final String ACTIONS = "*actions*";
239

240
        public Column(String title, String key) {
241
            this(title, key, key, null);
×
242
        }
×
243

244
        public Column(String title, String key, String cssClass) {
245
            this(title, key, key, cssClass);
×
246
        }
×
247

248
        public Column(String title, String dataKey, String key, String cssClass) {
×
249
            super(new Model<String>(title), dataKey);
×
250
            this.key = key;
×
251
            this.dataKey = dataKey;
×
252
            this.cssClass = cssClass;
×
253
        }
×
254

255
        @Override
256
        public String getCssClass() {
257
            return cssClass;
×
258
        }
259

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

397
    }
398

399
    private static String truncateLabel(String label) {
400
        return Utils.truncateLabel(label);
×
401
    }
402

403
}
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