6.9.128 • Published 11 months ago

@patrtorg/maiores-adipisci-maxime v6.9.128

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

@patrtorg/maiores-adipisci-maxime v1.1.12 npm.io

An ambitious light-weight react module written in TypeScript for tracking scroll progress in a performant way. Developed for use with spring based animation libraries such as react-spring, but can be used with or without any library.

Live demo / Code examples

Live demo: https://olarsson.github.io/@patrtorg/maiores-adipisci-maxime-examples/

Code examples: https://github.com/patrtorg/maiores-adipisci-maxime-examples/tree/master/src

Repository

URL: https://github.com/patrtorg/maiores-adipisci-maxime

Installation

npm i @patrtorg/maiores-adipisci-maxime

Usage

Here is a very basic example that tracks the scroll progress of the document.

import { ScrollTrackerDocument, ScrollTracker } from "@patrtorg/maiores-adipisci-maxime";

import { ScrollData, ScrollObject } from "@patrtorg/maiores-adipisci-maxime/dist/types";

import { useRef } from "react";

function App() {
  const refPageProgress = useRef(null);

  return (
    <ScrollTrackerDocument scrollThrottle={33}> // 1000 ms/30 fps = 33ms, limits the triggered events to 30 fps, optional
      {({ scrollData }: ScrollData) => {
        return (
          <ScrollTracker
            scrollData={scrollData}
            elem={refPageProgress}
            settings={{
              duration: {
                distance: 100,
                unit: "%",
                basedOn: "doc",
              },
            }}>
            {({ scrollObject }: ScrollObject) => {
              return <h1 ref={refPageProgress}>Here is the scroll progress: {scrollObject.progress}</h1>;
            }}
          </ScrollTracker>
        );
      }}
    </ScrollTrackerDocument>
  );
}

export default App;

Usage without TypeScript

You don't use TypeScript? No problem, it's not a requirement. Simply remove the type declarations and it will work just fine. For example:

      {({ scrollData }: ScrollData) => {
        return (...);
      }}

becomes:

      {({ scrollData }) => {
        return (...);
      }}

Components

<ScrollTrackerDocument />

Sets the document as the main scrolling container. This or ScrollTrackerCustom must always be the parent of a ScrollTracker component.

Configuration and properties:

  • scrollThrottle - (number) throttles the recalculations in ms to this value when the document is scrolled.
  • resizeThrottle - (number) throttles the recalculations in ms to this value when the document is resized.

Creates a function which returns a scrollData object as such:

  • scrollData - (object, immutable) data returned from the component.
    • scrollTop - (number, px) the scroll position from the top.
    • containerHeight - (number, px) height of the container.
    • element - (number, px) the tracked element for scrolling (document).
    • percentProgress - (number, %) scroll progress in percent expressed as a number between 0 to 1.
    • scrollHeight - (number, px) the total scrollable height of the document.
<ScrollTrackerDocument>
  {({ scrollData }: ScrollData) => {
    return (
      // ScrollTracker components and other components can go inside here
    );
  }}
</ScrollTrackerDocument>

<ScrollTrackerCustom />

Sets a custom element as the main scrolling container. This or ScrollTrackerDocument must always be the parent of a ScrollTracker component.

Configuration and properties:

  • scrollThrottle - (number) throttles the recalculations to this value in ms when the element is scrolled.
  • resizeThrottle - (number) throttles the recalculations to this value in ms when the element is resized.
  • scrollingElement - (string, required) the selector for the main scrollable element to track scroll progress of.

Creates a function which returns a scrollData object as such:

  • scrollData - (object, immutable) data returned from the component.
    • scrollTop - (number, px) the scroll position from the top.
    • containerHeight - (number, px) height of the container.
    • element - (number, px) the tracked element for scrolling (custom element).
    • percentProgress - (number, %) scroll progress in percent expressed as a number between 0 to 1.
    • scrollHeight - (number, px) the total scrollable height of the document.
<ScrollTrackerCustom
  key={active.toString()} // forces a rerender of the tracker, use this if you for example hide the element with 'display: none'
  scrollingElement='#custom-scroll-container'>
  {({ scrollData }: ScrollData) => {
    return (
      // ScrollTracker components and other components can go inside here
    );
  }}
</ScrollTrackerCustom>

<ScrollTracker />

A specific DOM element and its progress based on its duration and offsets will be managed by this component.

Configuration and properties:

  • elem - (ref, required) sets the element reference to use when tracking scroll progress.
  • settings - (object, required)
    • trigger - ('onEnter' | 'onLeave', optional) when the calculations should be begin, defaults to 'onEnter'. is only used when 'basedOn' is set to 'elem' or 'vp'. 'onEnter' means the trigger is when the element enters the vp, 'onLeave' is when the element start to leave the vp.
    • duration - (object, required)
      • distance - (number, required) how long of the tracked elements duration calculations should be active for.
      • unit - ('px' | '%', required) unit the distance should be measured in.
      • basedOn - ('doc' | 'elem' | 'vp', required) the duration will be calculated based on distance + unit and what you chose here. 'doc' is the document, 'elem' is the element, 'vp' is the viewport height.
    • offsetTop - (object, optional)
      • ... - same props as the duration.
    • offsetBottom - (object, optional)
      • ... - same props as the duration.
  • onStart - (function, optional) callback to run when scroll progress begins.
  • onEnd - (function, optional) callback to run when scroll progress ends.

Creates a function which returns a scrollObject object as such:

  • scrollObject (object, immutable) - data returned from the component.
    • scrollData - (object, immutable) inherited from the main component.
    • progress - (number, %) scroll progress in percent expressed as a number between 0 to 1.
    • start - (number, px) the start position in pixels when scroll progress calculation should begin.
    • end - (number, px) the end position in pixels when scroll progress calculation should end.
<ScrollTracker
  scrollData={scrollData} // the scrollData object returned by either ScrollTrackerDocument or ScrollTrackerCustom
  elem={refElem}
  settings={{
    trigger: 'onLeave',
    duration: {
      distance: 100,
      unit: "%",
      basedOn: "elem",
    },
    offsetTop: {
      distance: 25,
      unit: "%",
      basedOn: "vp",
    },
    offsetBottom: {
      distance: -200,
      unit: "px",
      basedOn: "", // when using px this can be left empty
    },
  }}>
  {({ scrollObject }: ScrollObject) => {
    return (
      // return for example the scrollObject.progress to reflect progress, and any other elements/components that you wish
    )
  }}
</ScrollTracker>

Next.js

If you load @patrtorg/maiores-adipisci-maxime as a dynamic component it will work out of the box, if you want it to work with SSR then you need to change your next config accordingly:

const nextConfig = {
  transpilePackages: ['@patrtorg/maiores-adipisci-maxime']
};

If it still doesnt work then change the import string in the following fashion: import { ScrollTrackerDocument, ScrollTracker } from "node_modules/@patrtorg/maiores-adipisci-maxime/dist/@patrtorg/maiores-adipisci-maxime.es";

Todo

  • Implement the scroll logic for horizontal scrolling
  • Refactor the ScrollTrackerCustom to handle both React refs and HTML elements
indicatorsortedES2017fastifyexecutablekey valueECMAScript 2019matchAlldescriptortextrapidcommanderdefinePropertyArray.prototype.containsmodulesassertionworkspace:*sequencecodesapollodataviewrequestreduxpromises256deep-cloneprotoviewfast-deep-copyshamstyledynamodbremoveelasticachemapcall-boundArray.prototype.findLastIndexreact animationbeanstalkyupstartTypeScriptobjectidairbnbfixed-widthES2016urlschromiumECMAScript 2022eslintpluginBigUint64Arraypackage managerdeep-copyprunetoStringTagreact-hook-formansilogMicrosoftfastES2019typescriptfast-clonethreeimmerStyleSheetregexcolorsfunctionJSONdateiepersistentkeyelbcryptovarsvalidtyped arrayprotocol-bufferspopmotionoptimistperformancecompilerformatcolourgetPrototypeOfnegativedependenciesdefinetapReactiveXartwaittoArraybundlingchannelroute53eventEmitterhookformdebuggergesturesexpressconcatpackagesfilehelpersschemefindLastIndexObject.entriescommandstructuredClonegetteri18nprefixenvvaluestypedgenericswordbreakchildoptimizerlinkruntimeregular expressionscoerciblethroatURLefficientcallboundtoolkitUint32Arraynodepathoptiontc39ECMAScript 2016ES3asciishellperformantvisualissetxdg-openfastcloneoffsetdefaultcolumnsObject.valuesimportexporthooksconcurrencyiconvdeletetakebusyqsstoragegatewayarraybuffereventDispatcherguidcolumnwhatwghigher-orderes-shim APIRFC-6455jasminecommand-linedataViewECMAScript 2018es7pushformstdlibopenistanbulsomesuperagentcall-bindutil.inspectdescriptionsyntaxaccessorcollectioncore-jsdom-testing-libraryObject.definePropertyhashrateTypeBoxfast-copysortfindLastmergereusevalidationbuffersbundlerUint8ArrayObservablesbreakfetchargumentsArrayBuffer.prototype.slicecachedirectoryes2016dayjsmake direxpressionECMAScript 6chaitostringtagwafextendlockfilereal-timeInt8ArrayinferencekarmagroupjsonpathunicodedeepcloneRegExp#flagstslibWeakSetlintcliquoteglacierfind-upobjwidthswfcloudwatchassertslimitedclass-validatorSymbol.toStringTagiterationlengthminimalObservablees-abstracttoobjectfinduploggerURLSearchParamssuperstructjsonrfc4122languageES2021starterES7identifierscomputed-typesCSSStyleDeclarationpreserve-symlinksstreamcloudtrail0styled-componentsworkflowkoreanmove[[Prototype]]String.prototype.trimSetvalidatepatchapirm -rfparsinglaunchcreateconvertStreamtypanionstyleguideimportmimetypesserializerfast-deep-cloneajvarraysArray.prototype.findLastbyteicutraverse_.extendcircularpackage.jsonmapreducergbrequireprettyxtermflagbluebirdfile cacheiteratorObject.keysUint16ArrayexeTypedArrayautoprefixertaskfilterbannerhelperlastdotenvECMAScript 2023functionalserializecurlECMAScript 3valuefunctionssymbolsterminalidleArrayBufferreact poseopenscomparetesterbrowserlistgetOwnPropertyDescriptorBigInt64Arrayeslintagentajaxsearchsettereventsspeedredirectposesharednpmfile systemiamnumberpostcssarrayqueueMicrotaskmkdirpmobileemitcss-in-jsjsenvironmentstrimLeftzeronamebrowserslistgdprreadableeast-asian-widtharktype$.extendloadbalancingpipetelephonePushformsCSSinstrumentationhttpincludesECMAScript 2017sharedarraybuffertype-0sameValueZerosymbolownqueuelazyextensionjapanesejesttypeofutilitiesdeterministiccallbindregularaccessibilityanimationresolvea11ybufferconsolerobusttypedarraywebsiteObjectnegative zeromkdirmime-dbautoscalinglookargvassignrangeerrorfsArrayBuffer#slicedropsymlinksArray.prototype.flattenkey parequalAsyncIteratorform-validationclonewalkforEachObject.assignchinesestatelesstypedarrayspackagemimeasyncvpcsimple cachecorejsxreduceexecendpointjson cachestylingnamesstringifierlocationloadingentriesPromiseisConcatSpreadablebyteOffsetString.prototype.matchAllio-tsstringifyESloggingmodulepnpm9hasOwninstallerserializationuninstallenderparseprogressseseditorESnextsetImmediateECMAScript 2015globalsES2015duplextrimmonorepofastcopymetadataes6datastructures3esIteratormrujoispecFloat64ArrayutilityutilRxenvironmentmatchratelimiteslint-plugintddMapspinneres-shimswordwrapuuidcallbackcolorregexpJSON-Schemaebsbddponyfillpostcss-pluginassert@@toStringTaginstalll10nbindfiglethas-owntestprotobufdomtapesafeframersnsprivate dataqueryhasweakmapasttoolsopenertouchavafullscheme-validationworkeres20153dpropertyzodredactinputreact-testing-libraryxdguptypeerrorstreams2mochaInt16ArraymomentES2020routejQueryphonenativeurlInt32ArrayconfigflattenschemadebugxhrproxypropfromHyBivestintsiterateWebSocketscmdECMAScript 7clientspinnersbyteLengthsidetrimStartES6awaitES2023shiminvariantArray.prototype.flatquerystringYAMLespreedescriptorsStreamscloudformationtoSortedec2flatECMAScript 5everyWeakMapintrinsicUint8ClampedArraythrottlejsdomoncepropertiesawesomesaucelook-updiffescapeconfigurablermdirObject.is__proto__cloudfrontpolyfilldeepwhichES2022listenerscontainshttpssymlinkroutingsyntaxerrorformattingdependency managerlibphonenumbereslintconfiggetintrinsicequalitycensorReactiveExtensionsfolderES5globalboundES2018reactes2017flagsWebSocketoutputcssrm -fres2018trimEndRxJSinspectmakeprototypesettingsredux-toolkitspawnemrtrimRightFloat32ArrayextrapyyamlargsjshinttypesRegExp.prototype.flagsslotcollection.es6awsestreelruObject.fromEntriesemojitypesafecharsetcharactersECMAScript 2020function.lengthrecursivefull-widthjsdiffSymbolshrinkwrapdirnopeamazonjavascriptArray.prototype.flatMapECMAScript 2021Function.prototype.namees5browsererrorttyspringconcatMaphasOwnPropertyslicekeysdeepcopyargumentimmutableparserdatainternalhardlinksapptestingweaksetstringchromegetoptparentreact-hooksgroupByregular expressionlinewrapsetPrototypeOfObject.getPrototypeOfprivatetimekinesisenumerablefullwidthstylesstreamsrandomes8shebangcharacterES8termreadablestreamyamlcode pointswrite.envpluginbatchrdsArray.prototype.includeswrapsqspromiseflatMapReflect.getPrototypeOfUnderscorepicomatchwritablecjkreadwgetparentsecmascriptwaapimkdirsomitlimitcheckvariablesreducerprocesscloudsearchArray.prototype.filterArrayconsumecallstablematchesgetglobmulti-packagenodejswarningcopydragrmcoverageelectroninternal slotsimpledbgraphqlwalkingpositivefind
6.9.128

11 months ago

6.9.127

11 months ago

6.9.126

11 months ago

2.4.70

1 year ago

4.9.105

12 months ago

4.9.106

11 months ago

4.9.107

11 months ago

4.9.108

11 months ago

4.9.109

11 months ago

4.7.99

12 months ago

3.5.94

12 months ago

3.5.93

12 months ago

2.4.75

1 year ago

2.4.72

1 year ago

2.4.71

1 year ago

2.4.74

1 year ago

2.4.73

1 year ago

4.9.113

11 months ago

4.7.100

12 months ago

4.9.114

11 months ago

4.7.101

12 months ago

4.9.115

11 months ago

4.9.110

11 months ago

4.9.111

11 months ago

4.9.112

11 months ago

2.3.39

1 year ago

2.3.38

1 year ago

2.3.35

1 year ago

2.3.37

1 year ago

2.3.36

1 year ago

1.2.16

1 year ago

1.2.17

1 year ago

1.2.14

1 year ago

1.2.15

1 year ago

4.5.94

12 months ago

2.3.46

1 year ago

1.3.31

1 year ago

2.3.45

1 year ago

1.3.32

1 year ago

2.3.47

1 year ago

1.3.30

1 year ago

2.3.42

1 year ago

1.3.35

1 year ago

2.3.41

1 year ago

2.3.44

1 year ago

1.3.33

1 year ago

2.3.43

1 year ago

1.3.34

1 year ago

2.3.40

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

5.9.117

11 months ago

5.9.116

11 months ago

5.9.119

11 months ago

5.9.118

11 months ago

5.9.115

11 months ago

3.4.83

1 year ago

3.4.84

1 year ago

3.4.85

1 year ago

3.4.86

1 year ago

3.4.87

1 year ago

3.4.88

1 year ago

3.4.89

1 year ago

4.8.101

12 months ago

4.8.102

12 months ago

4.8.105

12 months ago

3.4.80

1 year ago

4.8.103

12 months ago

3.4.81

1 year ago

4.8.104

12 months ago

3.4.82

1 year ago

5.9.120

11 months ago

5.9.122

11 months ago

5.9.121

11 months ago

3.4.90

1 year ago

2.4.47

1 year ago

1.3.20

1 year ago

3.4.91

1 year ago

1.3.21

1 year ago

3.4.92

12 months ago

2.4.49

1 year ago

3.4.93

12 months ago

2.4.48

1 year ago

1.3.24

1 year ago

1.3.25

1 year ago

1.3.22

1 year ago

1.3.23

1 year ago

1.3.28

1 year ago

1.3.29

1 year ago

1.3.26

1 year ago

1.3.27

1 year ago

1.2.18

1 year ago

1.2.19

1 year ago

2.4.58

1 year ago

2.4.57

1 year ago

1.2.20

1 year ago

2.4.59

1 year ago

2.4.54

1 year ago

2.4.53

1 year ago

2.4.56

1 year ago

2.4.55

1 year ago

2.4.50

1 year ago

2.4.52

1 year ago

2.4.51

1 year ago

3.4.75

1 year ago

4.6.95

12 months ago

3.4.76

1 year ago

4.6.96

12 months ago

3.4.77

1 year ago

3.4.78

1 year ago

4.6.94

12 months ago

3.4.79

1 year ago

6.9.125

11 months ago

4.6.99

12 months ago

6.9.124

11 months ago

6.9.123

11 months ago

4.6.97

12 months ago

6.9.122

11 months ago

4.6.98

12 months ago

2.4.69

1 year ago

2.4.68

1 year ago

2.4.65

1 year ago

2.4.64

1 year ago

2.4.67

1 year ago

2.4.66

1 year ago

2.4.61

1 year ago

2.4.60

1 year ago

2.4.63

1 year ago

2.4.62

1 year ago

1.1.12

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago