swup / fragment-plugin

A swup plugin for dynamically replacing containers based on rules 🧩
https://swup-fragment-plugin.netlify.app
MIT License
15 stars 1 forks source link

Allow default scrolling behavior on fragment visits #34

Closed daun closed 1 year ago

daun commented 1 year ago

Describe the problem

Describe the proposed solution

Alternatives considered

How important is this feature to you?

hirasso commented 1 year ago

Great idea! And should be easily achievable. Another name for the rule option could preserveScroll with a default of true, to keep defaults to positive values.

daun commented 1 year ago

What about allowing a fragment id #list as a value of the scroll option? Some fragment visits might require scrolling to a specific element, e.g. the result list of a filter UI.

hirasso commented 1 year ago

Interesting idea! But I feel like we should leave this to the implementors. With the simplification of the fragmentVisit object it would now be very simple to implement custom logic:

swup.hooks.on('content:replace', async (visit) => {
  if (visit.fragmentVisit?.name === 'my-fragment-visit') {
    visit.scroll.reset = true;
  }
});

or

swup.hooks.on('content:replace', async (visit) => {
  if (visit.fragmentVisit?.name === 'my-fragment-visit') {
    visit.scroll.target = '#list';
  }
});

Do you think we still need this as a rule option then?

hirasso commented 1 year ago

If we go with a new rule option, is this what you were imagining?

{
  scroll: boolean | string
}

Where scroll would be false for each rule if not customized. Options would be

  1. scroll to the top if the rule matches:
{
  scroll: true
}
  1. scroll to the first matching element if the rule matches:
{
  scroll: '#list'
}

I actually like this a lot, will create a PR.