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

feat : `rule.if` #47

Closed hirasso closed 7 months ago

hirasso commented 11 months ago

On Hold

The issue was solvable by making sure that all fragments in a rule must match an element in the document. I'll keep this PR around and in sync with master, should we need it sometime.

Description

Adds a new property if to fragment rules, to only run rules if they match the callback:

{
  rules: [
    {
      from: '/users/:filter?',
      to: '/users/:filter?', 
      containers: ['#users'],
      if: () => new Date().getHours() > 20 // only do this after 8pm 👾
    }
  ];
}

Or:

{
  rules: [
    {
      from: '/users/:filter?',
      to: '/users/:filter?', 
      containers: ['#users'],
      if: (visit) => visit.to.url !== '/users/my-exception/' // Don't do this for an exact match with '/users/my-exception'/
    }
  ];
}

The real use case I'm using it for:

const rules: Rule[] = [
    /** Home, Projects & Filters <---> Single Project */
    {
        from: ['/', '/projects', '/projects/filter/:filter'],
        to: '/projects/:slug',
        containers: ['#project'],
    },
    {
        from: '/projects/:slug',
        to: ['/'],
        containers: ['#project'],
    },
    {
        from: '/projects/:slug',
        to: ['/projects', '/projects/filter/:filter'],
        containers: ['#project', '#projectslist'],
        name: 'from-project-to-projects',
        if: () => !Boolean(document.querySelector('.page.home'))
    },
    /** Projects & Filters <---> Projects & Filters */
    {
        from: ['/projects', '/projects/filter/:filter'],
        to: ['/projects', '/projects/filter/:filter'],
        containers: ['#projectslist', '#page-header'],
        name: 'projectslist',
        focus: false,
    },
];

Checks

hirasso commented 11 months ago

My reasoning behind putting this on hold is that if I would have have had it on my fingertips before implementing this feature, I very likely would have missed the opportunity to think about the root issue I had. I'm still very much open to merge this the day we find an issue that is absolutely not fixable with the declarative API.

daun commented 11 months ago

Sounds like a plan!

hirasso commented 7 months ago

Actually, I just realized that too many things have changed in master and merging this would be a nightmare. I'll close this PR, we can always get back to it and extract the functionality back into master should we end up needing it sometime in the future.