1.3.0 • Published 3 years ago

mithril-infinite v1.3.0

Weekly downloads
94
License
MIT
Repository
github
Last release
3 years ago

Infinite Scroll for Mithril

A component to handle scrolling of an "infinite" list or grid, while only drawing what is on screen (plus a bit of pre-fetching), so safe to use on mobiles.

Compatible with Mithril 1.x.

Examples

Examples

Features

  • Natural scrolling using browser defaults.
  • Fast and fluent (on desktop and modern mobiles).
  • Can be used for lists, grids and table-like data.
  • Items that are out of sight are removed, so only a fraction of the total content is drawn on the screen. This is good for speed and memory consumption.
  • Support for unequal content heights and dynamic resizing of content elements.
  • As more data is loaded, the scroll view increases in size, so that the scrollbar can be used to go back to a specific point on the page.
  • Items are handled per "page", which is a normal way of handling batches of search results from the server.
  • Pages can contain an arbitrary and unequal amount of items.
  • Pre-fetches data of the current page, the page before and after (or n pages ahead).
  • When there is room on the page to show more data: automatic detection of "loadable space" (so no loading area detection div is needed).
  • Optionally use previous/next paging buttons.
  • Supports dynamic content (for instance when filtering results).

Not included (by design):

  • Special support for older mobile browsers: no touch layer, requestAnimationFrame, absolute positioning or speed/deceleration calculations.

Installation

Use as npm module:

npm install --save mithril-infinite

or download/clone from Github.

For working with the examples, see the examples documentation.

Usage

Note: The parent of "scroll-view" must have a height. Also make sure that html has a height (typically set to 100%).

Handling data

Data can be provided:

  • With pageUrl for referencing URLs
  • With pageData for server requests

Using pageUrl for referencing URLs

An example using data files:

import infinite from "mithril-infinite"

m(infinite, {
  maxPages: 16,
  pageUrl: pageNum => `data/page-${pageNum}.json`,
  item
})

With these options we are:

  • limiting the number of pages to 16
  • passing a function to generate a JSON data URL
  • passing a function that should return a Mithril element

A simple item function:

const item = (data, opts, index) => 
  m(".item", [
    m("h2", data.title),
    m("div", data.body)
  ])

The item function passes 3 parameters:

  1. data contains the loaded data from pageUrl.
  2. opts contains: isScrolling: Bool, pageId: String, pageNum: Number, pageSize: Number
  3. index: the item index

Data file structure

Data is handled per "results" page. You are free to use any data format.

You could use a JSON data object for each page, containing a list of items. For example:

[
  {
    "src": "cat.jpg",
    "width": 500,
    "height": 375
  }
]

Or:

[
  ["red", "#ff0000"],
]

Using pageData for server requests

In most real world situations an API server will provide the data. So while passing file URLs with pageUrl is a handy shortcut, we preferably use data requests.

With m.request
import infinite from "mithril-infinite"

const pageData = pageNum => 
  m.request({
    method: "GET",
    dataType: "jsonp",
    url: dataUrl(pageNum)
  })

m(infinite, {
  pageData,
  item
})

Demo tip: in the example "Grid" we use jsonplaceholder.typicode.com to fetch our images:

const PAGE_ITEMS = 10

const dataUrl = pageNum =>
  `http://jsonplaceholder.typicode.com/photos?_start=${(pageNum - 1) * PAGE_ITEMS}&_end=${pageNum * PAGE_ITEMS}`

With async
import infinite from "mithril-infinite"

const asyncPageData = async function(pageNum) {
  try {
    const response = await fetch(dataUrl(pageNum))
    return response.json()
  } catch (ex) {
    //console.log('parsing failed', ex)
  }
}

m(infinite, {
  pageData: asyncPageData,
  item
})

Returning data directly
import infinite from "mithril-infinite"

const returnData = () =>
  [{ /* some data */ }]

m(infinite, {
  pageData: returnData,
  item
})

Returning data as a Promise
import infinite from "mithril-infinite"

const returnDelayedData = () =>
  new Promise(resolve =>
    setTimeout(() =>
      resolve(data)
    , 1000)
  )

m(infinite, {
  pageData: returnDelayedData,
  item
})

Handling dynamic data

In situations where the Infinite component needs to show different items - for instance when filtering or sorting search results - we must provide a unique key for each page. The key will enable Mithril to properly distinguish the pages.

Use option pageKey to provide a function that returns a unique identifying string. For example:

import infinite from "mithril-infinite"
import stream from "mithril/stream"

const query = stream("")

const Search = {
  view: () =>
    m("div", 
      m("input", {
        oninput: e => query(e.target.value),
        value: query()
      })
    )
}

const MyComponent = {
  view: () => {
    const queryStr = query()
    return m(infinite, {
      before: m(Search),
      pageKey: pageNum => `${pageNum}-${queryString}`,
      // other options
    })
  }
}

Advanced item function example

To enhance the current loading behavior, we:

  • Load images when they are visible in the viewport
  • Stop loading images when the page is scrolling. This makes a big difference in performance, but it will not always result in a good user experience - the page will seem "dead" when during the scrolling. So use with consideration.

The item function can now look like this:

const item = (data, opts) =>
  m("a.grid-item",
    m(".image-holder",
      m(".image", {
        oncreate: vnode => maybeShowImage(vnode, data, opts.isScrolling),
        onupdate: vnode => maybeShowImage(vnode, data, opts.isScrolling)
      })
    )
  )

// Don't load the image if the page is scrolling
const maybeShowImage = (vnode, data, isScrolling) => {
  if (isScrolling || vnode.state.inited) {
    return
  }
  // Only load the image when visible in the viewport
  if (infinite.isElementInViewport({ el: vnode.dom })) {
    showImage(vnode.dom, data.thumbnailUrl)
    vnode.state.inited = true
  }
el.style.backgroundImage = `url(${url})`

Getting the total page count

How the total page count is delivered will differ per server. jsonplaceholder.typicode.com passes the info in the request header.

Example "Fixed" shows how to get the total page count from the request, and use that to calculate the total content height.

We place the pageData function in the oninit function so that we have easy access to the state.pageCount variable:

const state = vnode.state
state.pageCount = 1

state.pageData = pageNum => 
  m.request({
    method: "GET",
    dataType: "jsonp",
    url: dataUrl(pageNum),
    extract: xhr => (
      // Read the total count from the header
      state.pageCount = Math.ceil(parseInt(xhr.getResponseHeader("X-Total-Count"), 10) / PAGE_ITEMS),
      JSON.parse(xhr.responseText)
    )
  })

Then pass state.pageData to infinite:

m(infinite, {
  pageData: state.pageData,
  maxPages: state.pageCount,
  ...
})

Using images

For a better loading experience (and data usage), images should be loaded only when they appear on the screen. To check if the image is in the viewport, you can use the function infinite.isElementInViewport({ el }). For example:

if (infinite.isElementInViewport({ el: vnode.dom })) {
  loadImage(vnode.dom, data.thumbnailUrl)
}

Images should not be shown with the <img/> tag: while this works fine on desktop browsers, this causes redrawing glitches on iOS Safari. The solution is to use background-image. For example:

el.style.backgroundImage = `url(${url})`

Using table data

Using <table> tags causes reflow problems. Use divs instead, with CSS styling for table features. For example:

.page {
  display: table;
  width: 100%;
}
.list-item {
  width: 100%;
  display: table-row;
}
.list-item > div {
  display: table-cell;
}

Pagination

See the "Paging" example.

Configuration options

Appearance options

ParameterMandatoryTypeDefaultDescription
scrollViewoptionalSelector StringPass an element's selector to assign another element as scrollView
classoptionalStringExtra CSS class appended to mithril-infinite__scroll-view
contentTagoptionalString"div"HTML tag for the content element
pageTagoptionalString"div"HTML tag for the page element; note that pages have class mithril-infinite__page plus either mithril-infinite__page--odd or mithril-infinite__page--even
maxPagesoptionalNumberNumber.MAX_VALUEMaximum number of pages to draw
preloadPagesoptionalNumber1Number of pages to preload when the app starts; if room is available, this number will increase automatically
axisoptionalString"y"The scroll axis, either "y" or "x"
autoSizeoptionalBooleantrueSet to false to not set the width or height in CSS
beforeoptionalMithril template or componentContent shown before the pages; has class mithril-infinite__before
afteroptionalMithril template or componentContent shown after the pages; has class mithril-infinite__after; will be shown only when content exists and the last page is in view (when maxPages is defined)
contentSizeoptionalNumber (pixels)Use when you know the number of items to display and the height of the content, and when predictable scrollbar behaviour is desired (without jumps when content is loaded); pass a pixel value to set the size (height or width) of the scroll content, thereby overriding the dynamically calculated height; use together with pageSize
setDimensionsoptionalFunction ({scrolled: Number, size: Number})Sets the initial size and scroll position of scrollView; this function is called once

Callback functions

ParameterMandatoryTypeDefaultDescription
pageUrleither pageData or pageUrlFunction (page: Number) => StringFunction that accepts a page number and returns a URL String
pageDataeither pageData or pageUrlFunction (page: Number) => PromiseFunction that fetches data; accepts a page number and returns a promise
itemrequiredFunction (data: Array, options: Object, index: Number) => Mithril TemplateFunction that creates a Mithril element from received data
pageSizeoptionalFunction (content: Array) => NumberPass a pixel value to set the size (height or width) of each page; the function accepts the page content and returns the size
pageChangeoptionalFunction (page: Number)Get notified when a new page is shown
processPageDataoptionalFunction (data: Array, options: Object) => ArrayFunction that maps over the page data and returns an item for each
getDimensionsoptionalFunction () => {scrolled: Number, size: Number}Returns an object with state dimensions of scrollView: scrolled (either scrollTop or scrollLeft) and size (either height or width); this function is called on each view update
pageKeyoptionalFunction (page: Number) => Stringkey is based on page numberFunction to provide a unique key for each Page component; use this when showing dynamic page data, for instance based on sorting or filtering

Paging options

ParameterMandatoryTypeDefaultDescription
currentPageoptionalNumberSets the current page
fromoptionalNumberNot needed when only one page is shown (use currentPage); use page data from this number and higher
tooptionalNumberNot needed when only one page is shown (use currentPage); Use page data to this number and lower

Options for infinite.isElementInViewport

All options are passed in an options object: infinite.isElementInViewport({ el, leeway })

ParameterMandatoryTypeDefaultDescription
elrequiredHTML ElementThe element to check
axisoptionalString"y"The scroll axis, either "y" or "x"
leewayoptionalNumber300The extended area; by default the image is already fetched when it is 100px outside of the viewport; both bottom and top leeway are calculated

Styling

Note: The parent of "scroll-view" must have a height. Also make sure that html has a height (typically set to 100%).

Styles are added using j2c. This library is also used in the examples.

CSS classes

ElementKeyClass
Scroll viewscrollViewmithril-infinite__scroll-view
Scroll contentscrollContentmithril-infinite__scroll-content
Content containercontentmithril-infinite__content
Pages containerpagesmithril-infinite__pages
Pagepagemithril-infinite__page
Content beforebeforemithril-infinite__before
Content afteraftermithril-infinite__after
StateKeyClass
Scroll view, x axisscrollViewXmithril-infinite__scroll-view--x
Scroll view, y axisscrollViewYmithril-infinite__scroll-view--y
Even numbered pagepageEvenmithril-infinite__page--even
Odd numbered pagepageOddmithril-infinite__page--odd
Page, now placeholderplaceholdermithril-infinite__page--placeholder

Fixed scroll and overflow-anchor

Some browsers use overflow-anchor to prevent content from jumping as the page loads more data above the viewport. This may conflict how Infinite inserts content in "placeholder slots".

To prevent miscalculations of content size, the "scroll content" element has style overflow-anchor: none.

Size

Minified and gzipped: ~ 3.9 Kb

Dependencies

Licence

MIT

1.3.0

3 years ago

1.2.11

4 years ago

1.2.10

4 years ago

1.2.9

4 years ago

1.2.8

5 years ago

1.2.7

5 years ago

1.2.6

5 years ago

1.2.5

5 years ago

1.2.4

6 years ago

1.2.0

6 years ago

1.1.6

6 years ago

1.1.5

6 years ago

1.1.4

6 years ago

1.1.3

7 years ago

1.1.2

7 years ago

0.6.3

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.6.2

7 years ago

0.6.1

7 years ago

0.6.0

7 years ago

0.5.6

8 years ago

0.5.5

8 years ago

0.5.4

8 years ago

0.5.3

8 years ago

0.5.2

8 years ago

0.5.1

8 years ago

0.5.0

8 years ago

0.4.0

8 years ago

0.3.1

8 years ago

0.3.0

8 years ago

0.2.14

8 years ago

0.2.13

8 years ago

0.2.12

8 years ago

0.2.11

9 years ago

0.2.10

9 years ago

0.2.9

9 years ago

0.2.8

9 years ago

0.2.7

9 years ago

0.2.6

9 years ago

0.2.5

9 years ago

0.2.4

9 years ago

0.2.3

9 years ago

0.2.2

9 years ago

0.2.1

9 years ago

0.2.0

9 years ago

0.1.13

9 years ago

0.1.12

9 years ago

0.1.11

9 years ago

0.1.10

9 years ago

0.1.8

9 years ago

0.1.7

9 years ago

0.1.6

9 years ago

0.1.5

9 years ago

0.1.4

9 years ago

0.1.3

9 years ago

0.1.2

9 years ago

0.1.1

9 years ago

0.1.0

9 years ago