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

knowledgepixels / nanodash / 43179589270

12 Nov 2026 08:01AM UTC coverage: 55.967% (+0.06%) from 55.903%
43179589270

push

github

web-flow
Merge pull request #913 from knowledgepixels/fix/crawler-500

fix(crawler): don't fail on internal links in view data when crawled

6785 of 12988 branches covered (52.24%)

Branch coverage included in aggregate %.

11715 of 20067 relevant lines covered (58.38%)

9.68 hits per line

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

64.6
src/main/java/com/knowledgepixels/nanodash/QueryResult.java
1
package com.knowledgepixels.nanodash;
2

3
import com.knowledgepixels.nanodash.component.NanodashLink;
4
import com.knowledgepixels.nanodash.component.QueryResultComponentFactory;
5
import com.knowledgepixels.nanodash.component.menu.ViewDisplayMenu;
6
import com.knowledgepixels.nanodash.domain.AbstractResourceWithProfile;
7
import com.knowledgepixels.nanodash.page.NanodashPage;
8
import com.knowledgepixels.nanodash.page.PublishPage;
9
import com.knowledgepixels.nanodash.page.UserPage;
10
import org.apache.wicket.Component;
11
import org.apache.wicket.markup.ComponentTag;
12
import org.apache.wicket.markup.MarkupStream;
13
import org.apache.wicket.markup.html.WebMarkupContainer;
14
import org.apache.wicket.markup.html.basic.Label;
15
import org.apache.wicket.markup.html.panel.Panel;
16
import org.apache.wicket.request.cycle.RequestCycle;
17
import org.apache.wicket.request.mapper.parameter.PageParameters;
18
import org.apache.wicket.util.string.Strings;
19
import org.nanopub.extra.services.ApiResponse;
20
import org.nanopub.extra.services.QueryRef;
21

22
import java.io.Serializable;
23
import java.util.ArrayList;
24
import java.util.List;
25
import java.util.Objects;
26
import java.util.function.UnaryOperator;
27
import java.util.regex.Matcher;
28
import java.util.regex.Pattern;
29

30
/**
31
 * Abstract base class for displaying query results in different formats.
32
 */
33
public abstract class QueryResult extends Panel {
34

35
    /**
36
     * Leaves the description out, for a view rendered without its title row: the paragraph
37
     * explains a titled view, and on its own above bare results it reads as content.
38
     */
39
    protected void hideDescription() {
40
        descriptionLabel.setVisible(false);
×
41
    }
×
42

43
    /**
44
     * A view-level action, shown as a top entry of the view's dropdown menu.
45
     *
46
     * @param label     the menu entry's text
47
     * @param pageClass the page the entry links to
48
     * @param params    the parameters passed to that page
49
     */
50
    public record MenuAction(String label, Class<? extends NanodashPage> pageClass, PageParameters params) implements Serializable {
36 ✔
51
    }
52

53
    /**
54
     * The note shown where a view has no results to show.
55
     */
56
    protected static final String NOTHING_FOUND_NOTE = "(nothing found)";
57

58
    protected final List<MenuAction> menuActions = new ArrayList<>();
15 ✔
59
    protected String contextId;
60
    protected String partId;
61
    protected String postPublishTab;
62
    // The ref (root definition) this view is pinned to (?root=), used to scope per-entry
63
    // action visibility to the claimant being viewed. Null = the resource's representative
64
    // ref. See docs/space-ref-identity.md.
65
    protected String refRoot;
66
    protected boolean finalized = false;
9 ✔
67
    protected final QueryRef queryRef;
68
    protected final ViewDisplay viewDisplay;
69
    protected final ApiResponse response;
70
    protected AbstractResourceWithProfile resourceWithProfile;
71
    protected AbstractResourceWithProfile pageResource;
72
    protected boolean showViewDisplayMenu = true;
9 ✔
73
    protected final GrlcQuery grlcQuery;
74

75
    /**
76
     * The view's description, shown below its title. See {@link #hideDescription()}.
77
     */
78
    private final Label descriptionLabel;
79

80
    /**
81
     * Constructor for QueryResult.
82
     *
83
     * @param markupId    the markup ID
84
     * @param queryRef    the query reference
85
     * @param response    the API response
86
     * @param viewDisplay the view display
87
     */
88
    public QueryResult(String markupId, QueryRef queryRef, ApiResponse response, ViewDisplay viewDisplay) {
89
        super(markupId);
9 ✔
90
        this.queryRef = queryRef;
9 ✔
91
        this.viewDisplay = viewDisplay;
9 ✔
92
        this.response = response;
9 ✔
93
        this.grlcQuery = GrlcQuery.get(queryRef);
12 ✔
94

95
        // Every view carries an id in the rendered page, so that it can be replaced on its
96
        // own over Ajax — which is how "refresh now" updates one view without re-rendering
97
        // the page. Without it the replacement would be written under an id the browser has
98
        // never seen, leaving the old markup (and its now-removed links) in place.
99
        setOutputMarkupId(true);
12 ✔
100

101
        // The spinner shown beside the title while this view's results are being brought up
102
        // to date; hidden until someone turns it on (see RefreshingResultPanel). It lives in
103
        // the title row, right after the title, where the row's own layout keeps it clear of
104
        // everything — see the .refresh-spinner rules in style.css.
105
        //
106
        // When the results are older than a refresh that failed, the same spot holds a short
107
        // note saying so instead (issue #889). Results from the cache look current otherwise,
108
        // and the query may keep failing for a while.
109
        refreshFailed = response != null && ApiCache.lastAttemptFailed(queryRef);
30 !
110
        refreshIndicator = new WebMarkupContainer("refresh-indicator") {
42 ✔
111

112
            @Override
113
            protected void onConfigure() {
114
                super.onConfigure();
6 ✔
115
                setVisible(refreshing || refreshFailed);
42 ✔
116
            }
3 ✔
117

118
            @Override
119
            protected void onComponentTag(ComponentTag tag) {
120
                super.onComponentTag(tag);
9 ✔
121
                if (!refreshing) {
12 ✔
122
                    tag.put("class", "refresh-failed");
12 ✔
123
                    tag.put("title", "The query failed when it was last run. These results are from an earlier run.");
12 ✔
124
                }
125
            }
3 ✔
126

127
            @Override
128
            public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
129
                if (refreshing) {
12 ✔
130
                    super.onComponentTagBody(markupStream, openTag);
15 ✔
131
                } else {
132
                    replaceComponentTagBody(markupStream, openTag, REFRESH_FAILED_NOTE);
15 ✔
133
                }
134
            }
3 ✔
135

136
        };
137
        refreshIndicator.setOutputMarkupPlaceholderTag(true);
15 ✔
138
        add(refreshIndicator);
30 ✔
139

140
        // The view's explaining paragraph, below its title (issue #735). Every view kind
141
        // shows it the same way, so it is added here rather than in each of them; a view
142
        // that declares none, and one rendered without its title row, show nothing (see
143
        // hideDescription).
144
        String description = viewDisplay == null ? null : viewDisplay.getDescription();
15 !
145
        // Markup is allowed and was sanitized when the view was read, as elsewhere.
146
        descriptionLabel = new Label("description", description);
21 ✔
147
        descriptionLabel.setEscapeModelStrings(false);
15 ✔
148
        descriptionLabel.setVisible(description != null && !description.isBlank());
21 !
149
        add(descriptionLabel);
30 ✔
150
    }
3 ✔
151

152
    private final WebMarkupContainer refreshIndicator;
153
    private boolean refreshing = false;
9 ✔
154
    private boolean refreshFailed;
155

156
    /**
157
     * The note shown beside the title of a view whose results are older than a refresh that
158
     * failed.
159
     */
160
    public static final String REFRESH_FAILED_NOTE = "Couldn't refresh, showing older results";
161

162
    /**
163
     * The query reference this view's results come from.
164
     *
165
     * @return the query reference
166
     */
167
    public QueryRef getQueryRef() {
168
        return queryRef;
×
169
    }
170

171
    /**
172
     * The results this view is showing. Available to the action-link builder, which runs
173
     * after the response has arrived, so a view-level action can take a value from the rows
174
     * (see {@link com.knowledgepixels.nanodash.component.ViewActionMappings}).
175
     *
176
     * @return the API response
177
     */
178
    public ApiResponse getApiResponse() {
179
        return response;
9 ✔
180
    }
181

182
    /**
183
     * The version of the view definition this view display is showing, as the id to hand to
184
     * {@link View#refreshLatestVersion(String)} when checking for a newer one.
185
     *
186
     * @return the shown view's id, or null if this result has no view behind it
187
     */
188
    public String getShownViewId() {
189
        View view = (viewDisplay == null ? null : viewDisplay.getView());
×
190
        return view == null ? null : view.getId();
×
191
    }
192

193
    /**
194
     * Shows or hides the spinner beside this view's title.
195
     *
196
     * @param refreshing true while the view's results are being brought up to date
197
     */
198
    public void setRefreshing(boolean refreshing) {
199
        this.refreshing = refreshing;
9 ✔
200
    }
3 ✔
201

202
    /**
203
     * Sets whether this view's results are older than a refresh that failed, which puts a
204
     * short note beside the title while no spinner is showing there.
205
     *
206
     * @param refreshFailed true if the latest refresh of these results failed or timed out
207
     */
208
    public void setRefreshFailed(boolean refreshFailed) {
209
        this.refreshFailed = refreshFailed;
9 ✔
210
    }
3 ✔
211

212
    /**
213
     * The spinner component itself (or the note in its place), so a caller that changes it
214
     * over Ajax can repaint just that instead of the whole view.
215
     *
216
     * @return the refresh indicator
217
     */
218
    public Component getRefreshIndicator() {
219
        return refreshIndicator;
9 ✔
220
    }
221

222
    /**
223
     * Builds this view again from the current state of the cache, as a component that can
224
     * take this one's place. Used to refresh a single view where it stands (see the "refresh
225
     * now" entry of its menu) instead of re-rendering the page around it.
226
     * <p>
227
     * With the view's results just marked as outdated, the rebuild comes back as the results
228
     * that are on screen now plus a spinner, which swaps in the new ones by itself once the
229
     * query has run.
230
     *
231
     * @param markupId the id the replacement must take, i.e. that of the component it replaces
232
     * @return the replacement component
233
     */
234
    public Component rebuild(String markupId) {
235
        // The part id is only set when it differs from the context; otherwise the view is
236
        // shown for the context resource itself.
237
        String id = partId != null ? partId : contextId;
×
238
        Component rebuilt = QueryResultComponentFactory.build(markupId, queryRef, viewDisplay,
×
239
                resourceWithProfile, id, contextId, refRoot);
240
        if (rebuilt != null) rebuilt.setOutputMarkupId(true);
×
241
        return rebuilt;
×
242
    }
243

244
    @Override
245
    protected void onBeforeRender() {
246
        if (!finalized) {
9 !
247
            // View-level actions used to render as a button strip in the header here;
248
            // they now live as the top entries of the view's dropdown menu instead.
249
            add(new Label("buttons").setVisible(false));
42 ✔
250
            if (showViewDisplayMenu) {
9 !
251
                if (viewDisplay.getNanopubId() != null || !menuActions.isEmpty()) {
24 !
252
                    add(new ViewDisplayMenu("np", viewDisplay, queryRef, pageResource, menuActions));
×
253
                } else {
254
                    add(new Label("np").setVisible(false));
42 ✔
255
                }
256
            }
257
            finalized = true;
9 ✔
258
        }
259
        super.onBeforeRender();
6 ✔
260
    }
3 ✔
261

262
    /**
263
     * The view-level actions to render as top entries of the view's dropdown menu.
264
     *
265
     * @return the collected view-level menu actions
266
     */
267
    public List<MenuAction> getMenuActions() {
268
        return menuActions;
9 ✔
269
    }
270

271
    /**
272
     * Set the resource with profile for this component.
273
     *
274
     * @param resourceWithProfile The resource with profile to set.
275
     */
276
    public void setResourceWithProfile(AbstractResourceWithProfile resourceWithProfile) {
277
        this.resourceWithProfile = resourceWithProfile;
×
278
    }
×
279

280
    public void setPageResource(AbstractResourceWithProfile pageResource) {
281
        this.pageResource = pageResource;
9 ✔
282
    }
3 ✔
283

284
    /**
285
     * Set the context ID for this component.
286
     *
287
     * @param contextId The context ID to set.
288
     */
289
    public void setContextId(String contextId) {
290
        this.contextId = contextId;
9 ✔
291
    }
3 ✔
292

293
    /**
294
     * Set the part ID when this view is shown on a part page (e.g. paper collection).
295
     * Used for redirect-after-publish to return to the part page.
296
     *
297
     * @param partId The part ID to set, or null when on the main context page.
298
     */
299
    public void setPartId(String partId) {
300
        this.partId = partId;
×
301
    }
×
302

303
    /**
304
     * Set the tab to return to after publishing one of this view's action
305
     * buttons (e.g. {@code "about"} so a space's About-tab views send the user
306
     * back to About instead of the default Content tab). Null leaves the
307
     * post-publish redirect on its default tab.
308
     *
309
     * @param postPublishTab the tab name, or null for the default
310
     */
311
    public void setPostPublishTab(String postPublishTab) {
312
        this.postPublishTab = postPublishTab;
×
313
    }
×
314

315
    /**
316
     * Set the ref (root definition) this view is pinned to, so per-entry action visibility
317
     * is gated against that claimant's authority rather than the resource's representative
318
     * ref. Null = representative ref. See docs/space-ref-identity.md.
319
     *
320
     * @param refRoot the ref's root nanopub, or null
321
     */
322
    public void setRefRoot(String refRoot) {
323
        this.refRoot = refRoot;
×
324
    }
×
325

326
    /**
327
     * @return the tab to return to after publishing via an action button, or null for the default
328
     */
329
    public String getPostPublishTab() {
330
        return postPublishTab;
9 ✔
331
    }
332

333
    // A view-level action button; collected here and rendered as a top entry of the
334
    // view's dropdown menu (see ViewDisplayMenu).
335
    public void addButton(String label, Class<? extends NanodashPage> pageClass, PageParameters parameters) {
336
        if (parameters == null) {
6 !
337
            parameters = new PageParameters();
×
338
        }
339
        if (contextId != null) {
9 !
340
            parameters.set("context", contextId);
×
341
        }
342
        menuActions.add(new MenuAction(label, pageClass, parameters));
30 ✔
343
    }
3 ✔
344

345
    /**
346
     * The navigation context to stamp on links in result cells: this view's context
347
     * resource if bound to one, else the page's navigation context. Only usable at
348
     * render time (needs the page). Visible to the view types that build their links
349
     * as URLs rather than components (see the network view).
350
     *
351
     * @return the context id, or null if neither is set
352
     */
353
    protected String renderContextId() {
354
        if (contextId != null) return contextId;
18 ✔
355
        if (getPage() instanceof NanodashPage nanodashPage) return nanodashPage.getContextId();
18 !
356
        return null;
6 ✔
357
    }
358

359
    /**
360
     * The resource part to stamp on links in result cells, next to
361
     * {@link #renderContextId()}: the part this view is bound to, else the part the page
362
     * was reached under. A part only travels together with its own context (issue #697),
363
     * so it is dropped when the links carry a different one. Only usable at render time.
364
     *
365
     * @return the part id, or null if none applies
366
     */
367
    private String renderPartId() {
368
        if (partId != null) return partId;
9 !
369
        if (getPage() instanceof NanodashPage nanodashPage
18 !
370
                && Objects.equals(renderContextId(), nanodashPage.getIncomingContextId())) {
×
371
            return nanodashPage.getPartId();
×
372
        }
373
        return null;
6 ✔
374
    }
375

376
    /**
377
     * The label to carry along with {@link #renderPartId()}, so the target page's
378
     * back-link can name the part. Only known where the page is the part's own.
379
     *
380
     * @return the part label, or null if none is known
381
     */
382
    private String renderPartLabel() {
383
        if (getPage() instanceof NanodashPage nanodashPage
18 !
384
                && Objects.equals(renderPartId(), nanodashPage.getPartId())) {
×
385
            return nanodashPage.getPartLabel();
×
386
        }
387
        return null;
6 ✔
388
    }
389

390
    /**
391
     * A page reference for a result row's own resource part, reached from this view: the
392
     * part page of the given IRI under this view's navigation context, carrying the given
393
     * label as the page title where the part declares none, plus the part this page was
394
     * reached under so the target's back-link can name it (issue #697). Only usable at
395
     * render time (needs the page).
396
     *
397
     * @param partId the row's resource IRI
398
     * @param label  the label to show for it, or null to fall back to its short name
399
     * @return the page reference, or null when no navigation context is known (a part
400
     * page cannot resolve a part without its maintaining resource)
401
     */
402
    protected NanodashPageRef partPageRef(String partId, String label) {
403
        String ctx = renderContextId();
9 ✔
404
        NanodashPageRef ref = NavigationContext.getPartPageRef(partId, label, ctx);
15 ✔
405
        if (ref == null) return null;
12 ✔
406
        NavigationContext.withPart(ref.getParameters(), renderPartId(), renderPartLabel(), ctx);
27 ✔
407
        return ref;
6 ✔
408
    }
409

410
    /**
411
     * The navigation parameters to append to a hand-built app-internal link in a result
412
     * cell: the {@code &context=...} suffix, plus the resource part the page was reached
413
     * under where that applies (issue #697). Empty string when no context is set. Only
414
     * usable at render time (needs the page).
415
     *
416
     * @param url the link the parameters are appended to, or null if not known yet
417
     * @return the URL parameter suffix, possibly empty
418
     */
419
    protected String linkNavParams(String url) {
420
        // Not for a crawler: these say where the visitor came from, and adding them makes
421
        // one target page a different URL per route, which is a crawl of the cross-product
422
        // (issue #804). A link that needs its context to resolve at all -- a resource part,
423
        // which cannot be found without its maintaining resource -- is not built here but
424
        // through NavigationContext.getPartPageRef, and keeps it.
425
        if (CrawlerRequest.isCrawler()) return "";
6 !
426
        String ctx = renderContextId();
9 ✔
427
        if (ctx == null) return "";
12 !
428
        StringBuilder params = new StringBuilder("&context=").append(Utils.urlEncode(ctx));
×
429
        String part = renderPartId();
×
430
        // Not on a link to the part itself, nor on one up to the resource maintaining
431
        // it: the part is then either the destination or behind the user.
432
        if (part != null && !namesResource(url, part) && !namesResource(url, ctx)) {
×
433
            params.append("&part=").append(Utils.urlEncode(part));
×
434
            String partLabel = renderPartLabel();
×
435
            if (partLabel != null && !partLabel.isBlank()) {
×
436
                params.append("&part-label=").append(Utils.urlEncode(partLabel));
×
437
            }
438
        }
439
        return params.toString();
×
440
    }
441

442
    /**
443
     * The URL for a result row's agent cell: the person's part page under this view's
444
     * navigation context where that context shows something about people, else their own
445
     * page. Carries the name the row already resolved, so the part page is titled with it
446
     * rather than with the bare ORCID number.
447
     * <p>
448
     * A cell naming a person is built as a plain {@code href} rather than through
449
     * {@link NanodashLink}, so neither its routing nor the navigation-parameter behaviors
450
     * reach it. That is why a space's own listings -- its organizers, its programme
451
     * committee -- led to the general profile while the same person clicked in an ordinary
452
     * IRI cell led to their page in that space (issue #822).
453
     *
454
     * @param agentIri the person's IRI
455
     * @param label    the name shown for them, or null if none was resolved
456
     * @return the cell link's URL, navigation parameters included
457
     */
458
    protected String agentCellUrl(String agentIri, String label) {
459
        if (NanodashLink.leadsToAgentPartPage(agentIri, renderContextId())) {
×
460
            NanodashPageRef partRef = partPageRef(agentIri, label);
×
461
            if (partRef != null) {
×
462
                return RequestCycle.get().urlFor(partRef.getPageClass(), partRef.getParameters()).toString();
×
463
            }
464
        }
465
        String url = UserPage.MOUNT_PATH + "?id=" + Utils.urlEncode(agentIri);
×
466
        return url + linkNavParams(url);
×
467
    }
468

469
    /**
470
     * Whether the given app-internal link points at the given resource, i.e. carries it
471
     * as its {@code id}. The sanitizer writes "=" as "&#61;", so both spellings count.
472
     *
473
     * @param url        the link to check, or null
474
     * @param resourceId the resource id to look for
475
     * @return true if the link's id is that resource
476
     */
477
    static boolean namesResource(String url, String resourceId) {
478
        if (url == null) return false;
12 ✔
479
        String encoded = Utils.urlEncode(resourceId);
9 ✔
480
        return url.contains("id=" + encoded) || url.contains("id&#61;" + encoded);
42 ✔
481
    }
482

483
    private static final Pattern INTERNAL_HREF_PATTERN = Pattern.compile("href=\"(/[^\"]*)\"");
9 ✔
484

485
    /**
486
     * Appends the navigation context, and the resource part where one applies, to
487
     * app-internal links ({@code href="/..."}) inside sanitized result-cell HTML, so
488
     * ready-made links coming from the query data itself (e.g. template or query links
489
     * emitted by the SPARQL) also lead back to where the user came from. Links already
490
     * carrying a context are left alone.
491
     *
492
     * @param sanitizedHtml the sanitized cell HTML, or null
493
     * @return the HTML with context-enriched internal links
494
     */
495
    protected String withNavParamsInHtmlLinks(String sanitizedHtml) {
496
        if (renderContextId() == null || sanitizedHtml == null) return sanitizedHtml;
21 !
497
        return withNavParamsInHtmlLinks(sanitizedHtml, this::linkNavParams);
15 ✔
498
    }
499

500
    /**
501
     * The rewriting behind {@link #withNavParamsInHtmlLinks(String)}, apart from the page
502
     * it takes the parameters from.
503
     *
504
     * @param sanitizedHtml the sanitized cell HTML
505
     * @param navParams     gives the parameter suffix for a link: empty, or starting with "&amp;"
506
     * @return the HTML with the suffix appended to its internal links
507
     */
508
    static String withNavParamsInHtmlLinks(String sanitizedHtml, UnaryOperator<String> navParams) {
509
        Matcher m = INTERNAL_HREF_PATTERN.matcher(sanitizedHtml);
12 ✔
510
        StringBuilder sb = new StringBuilder();
12 ✔
511
        while (m.find()) {
9 ✔
512
            String url = m.group(1);
12 ✔
513
            String replacement = m.group();
9 ✔
514
            // The sanitizer escapes "=" as "&#61;", so check both spellings.
515
            if (!url.contains("context=") && !url.contains("context&#61;")) {
24 !
516
                String suffix = navParams.apply(url);
15 ✔
517
                // Nothing to append for a crawler, whose links carry no navigation
518
                // parameters at all (issue #804): the link stays as the data has it.
519
                if (!suffix.isEmpty()) {
9 ✔
520
                    String separator = url.contains("?") ? "&amp;" : "?";
24 ✔
521
                    // The suffix starts with "&", which the separator replaces.
522
                    replacement = "href=\"" + url + separator + suffix.substring(1).replace("&", "&amp;") + "\"";
30 ✔
523
                }
524
            }
525
            m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
18 ✔
526
        }
3 ✔
527
        m.appendTail(sb);
12 ✔
528
        return sb.toString();
9 ✔
529
    }
530

531
    // An "<a ...>" start tag in sanitized cell HTML, with its attribute part.
532
    private static final Pattern ANCHOR_TAG_PATTERN = Pattern.compile("<a\\b([^>]*)>", Pattern.CASE_INSENSITIVE);
12 ✔
533
    private static final Pattern HREF_ATTRIBUTE_PATTERN = Pattern.compile("href=\"([^\"]*)\"");
12 ✔
534

535
    // The look given to publish links in result content: the small transparent button
536
    // used for secondary actions elsewhere in the app.
537
    private static final String PUBLISH_BUTTON_CLASSES = "smallbutton button light";
538

539
    /**
540
     * Prepares raw HTML coming from query data for display in result content: it is
541
     * sanitized, its app-internal links get the navigation context, and its links to
542
     * the publish form are turned into buttons.
543
     *
544
     * @param rawHtml the raw HTML from the query data, or null
545
     * @return the sanitized and enriched HTML
546
     */
547
    protected String cellHtml(String rawHtml) {
548
        return withPublishLinksAsButtons(withNavParamsInHtmlLinks(Utils.sanitizeHtml(rawHtml)));
18 ✔
549
    }
550

551
    /**
552
     * Shows links to the publish form as buttons, so that the actions a view offers
553
     * stand out from the links to content. Only links that don't bring their own class
554
     * are styled.
555
     *
556
     * @param sanitizedHtml the sanitized cell HTML, or null
557
     * @return the HTML with publish links marked as buttons
558
     */
559
    protected static String withPublishLinksAsButtons(String sanitizedHtml) {
560
        if (sanitizedHtml == null) return null;
12 ✔
561
        Matcher m = ANCHOR_TAG_PATTERN.matcher(sanitizedHtml);
12 ✔
562
        StringBuilder sb = new StringBuilder();
12 ✔
563
        while (m.find()) {
9 ✔
564
            String attributes = m.group(1);
12 ✔
565
            String replacement = m.group();
9 ✔
566
            Matcher hrefMatcher = HREF_ATTRIBUTE_PATTERN.matcher(attributes);
12 ✔
567
            if (hrefMatcher.find() && isPublishLink(hrefMatcher.group(1)) && !attributes.contains("class=")) {
36 !
568
                replacement = "<a class=\"" + PUBLISH_BUTTON_CLASSES + "\"" + attributes + ">";
9 ✔
569
            }
570
            m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
18 ✔
571
        }
3 ✔
572
        m.appendTail(sb);
12 ✔
573
        return sb.toString();
9 ✔
574
    }
575

576
    /**
577
     * Whether the given value is a link to the publish form, i.e. the app-internal
578
     * {@code /publish} path, with or without query parameters. Only the path is
579
     * checked, so the sanitizer's escaping inside the parameters (it writes "=" as
580
     * "&#61;") makes no difference.
581
     *
582
     * @param value the value to check, or null
583
     * @return true if the value is a publish link
584
     */
585
    public static boolean isPublishLink(String value) {
586
        if (value == null) return false;
12 ✔
587
        return value.split("[?#]", 2)[0].equals(PublishPage.MOUNT_PATH);
27 ✔
588
    }
589

590
    /**
591
     * The content for a publish link that comes as a plain cell value: a button
592
     * carrying the label from the sibling label column where there is one, and a
593
     * generic label otherwise.
594
     *
595
     * @param url   the publish link
596
     * @param label the label from the sibling label column, or null
597
     * @return the HTML for the button
598
     */
599
    protected String publishButtonHtml(String url, String label) {
600
        String text = (label == null || label.isBlank() || label.equals(url)) ? "publish…" : label;
×
601
        String inner = Utils.looksLikeHtml(text) ? text : Strings.escapeMarkup(text).toString();
×
602
        return cellHtml("<a href=\"" + Strings.escapeMarkup(url) + "\">" + inner + "</a>");
×
603
    }
604

605
    /**
606
     * Whether all result rows fit on the first page, so no pagination is needed
607
     * and the filter textfield can be hidden. Also true when the page size is
608
     * unlimited ({@code < 1}).
609
     *
610
     * @return true if all entries fit on the first page
611
     */
612
    protected boolean fitsOnFirstPage() {
613
        int pageSize = viewDisplay.getPageSize();
15 ✔
614
        return pageSize < 1 || response.getData().size() <= pageSize;
36 !
615
    }
616

617
    /**
618
     * Whether the empty state should point the viewer to the view-level actions:
619
     * the underlying response (not just a filtered view of it) has no rows, and
620
     * there is at least one action the viewer is entitled to.
621
     *
622
     * @return true if the empty-state call-to-action buttons should show
623
     */
624
    protected boolean hasEmptyStateActions() {
625
        return response.getData().isEmpty() && !menuActions.isEmpty();
33 !
626
    }
627

628
    /**
629
     * Whether this view has nothing at all to put on the page: no rows, and no action to
630
     * offer in their place. A view display marked {@link ViewDisplay#hiddenWhenEmpty()}
631
     * leaves the page in that case instead of printing the empty note.
632
     *
633
     * @return true if there is neither a row nor an action to show
634
     */
635
    public boolean hasNothingToShow() {
636
        return response != null && response.getData().isEmpty() && !hasEmptyStateActions();
45 !
637
    }
638

639
    /**
640
     * The note to print in place of the results. A view display may override it (see
641
     * {@link ViewDisplay#withEmptyMessage(String)}), but only for a genuinely empty
642
     * result: the same note also covers "the filter matched no row", where a message
643
     * written to speak for the whole page would be a lie.
644
     *
645
     * @return the note to show instead of results
646
     */
647
    protected String emptyNote() {
648
        String message = viewDisplay.getEmptyMessage();
12 ✔
649
        if (message != null && response != null && response.getData().isEmpty()) return message;
36 !
650
        return NOTHING_FOUND_NOTE;
6 ✔
651
    }
652

653
    /**
654
     * Populate the component with the query results.
655
     */
656
    protected abstract void populateComponent();
657

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