CloudCannon / pagefind

Static low-bandwidth search at scale
https://pagefind.app
MIT License
3.41k stars 108 forks source link

offer a `<page-find-ui>` custom element #363

Open bennypowers opened 1 year ago

bennypowers commented 1 year ago

The PagefindUI object is great if someone wants to write javascript, but how much nicer would it be to offer a web component?

before:

<link href="/_pagefind/pagefind-ui.css" rel="stylesheet">
<script src="/_pagefind/pagefind-ui.js" type="text/javascript"></script>

<div id="search"></div>
<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({ element: "#search" });
    });
</script>

after:

<script type="module" src="/_pagefind/page-find.js"></script>

<page-find></page-find>

Options could be exposed as attibutes or children. function options could be set as DOM properties, or modified in events

<page-find
    data-i18n-placeholder="Search my website"
    data-i18n-zero-results="Couldn't find [SEARCH_TERM]"
    no-show-images
    show-empty-filters
    reset-styles
    bundle-path="/subpath/_pagefind/"
    debounce-timeout-ms="500"></page-find>
const pf = document.querySelector('page-find')
      pf.addEventListener('term', function(event) {
        pf.term = event.term.replace(/aa/g, 'ā');
      });
      pf.addEventListener('result', function (event) {
        event.result.meta.image = someCustomFunction(event.result.meta.image);
      });

Would that be an interesting PR to review?

bglw commented 1 year ago

That's a great idea. I'd be more than happy to review a PR for this 😄

Some initial thoughts on naming/structure:

bennypowers commented 1 year ago

Your naming preferences are fine by me.

About APIs, if it'd be up to me, I'd have the script become a module which exports the constructor but also registers the tag name as a side effect. Changing from a script to w module would be a breaking change, but worth it IMO, so perhaps it's best to vend a script as well, at least initially. Scripts can import modules but only as promises so it might be awkward to try and straddle the fence.

bglw commented 1 year ago

Oh yup that makes sense. I'm pretty firm on no breaking changes, but I'm happy to change the recommended/documented flows. So that sounds good to me! I think anything further could be handled in reviewing a PR 🙂

Looking at the default UI, you'll see that it currently builds out to multiple targets — including a module build that is published to https://www.npmjs.com/package/@pagefind/default-ui, so there's potentially something you could tap into there, or another ESM build for web added, etc.