2.3.1 • Published 9 months ago

@appello/web-kit v2.3.1

Weekly downloads
-
License
ISC
Repository
bitbucket
Last release
9 months ago

Web kit frontend library of hooks for web environmental

How to use it

Install package from npm:

npm i @appello/web-kit

Import modules you need in your code:

import { useClickAway, useIntersectionObserver } from '@appello/web-kit';

Development guide

For developers

Each new functionality must be added to the folder and exported from the root! This is necessary to simplify the import of the necessary functionality:

import { useClickAway, useIntersectionObserver, ... } from '@appello/web-kit';

If you need to create a new module, remember to add index.ts with exports.

Hooks

useBlobObjectUrl

import { useBlobObjectUrl } from '@appello/web-kit';

Converting a Blob object to base64 encoded text.

API:

import { useBlobObjectUrl } from "@appello/web-kit";

const Component = () => {
  const url = useBlobObjectUrl(file);
  
  return (
    <div>{url}</div>
  );
};

Params:

PropertyDescriptionTypeDefault
blobBlob object.Blob / File / string / nullRequired

Return:

PropertyDescriptionType
urlReturn string url.string / null

useClickAway

import { useClickAway } from '@appello/web-kit';

Hook for handling when user click outside element.

API:

import { useClickAway } from '@appello/web-kit';

const Component = () => {
  const { ref } = useClickAway(() => {
    console.log('click away');
  });

  return <div ref={ref}></div>;
}

Params:

PropertyDescriptionTypeDefault
onClickAwayCallback which called when click away from element.() => voidRequired
optionsCustom options.UseClickAwayPropsOptional

Return:

PropertyDescriptionType
refRef off element.Ref

useCopyToClipboard

import { useCopyToClipboard } from '@appello/web-kit';

Hook for emulate copy to clipboard.

API:

import { useCopyToClipboard } from '@appello/web-kit';

const Component = () => {
  const [copiedTest, copy] = useCopyToClipboard()

  return (
    <>
      <div>{copiedTest}</div>
      <button onClick={copy}>Copy text</button>
    </>
  )
}

Return:

PropertyDescriptionType
copiedTest, copyState with copied text and callback for call copy event.array

useElementSize

import { useElementSize } from '@appello/web-kit';

Hook for getting element size.

API:

import { useElementSize } from '@appello/web-kit';
import { useState } from "react";

const Component = () => {
  const [customWidth, setCustomWidth] = useState();
  const ref = useRef();
  const { width, height } = useElementSize({
    ref,
  })

  return (
    <>
      <div ref={ref} style={{ width: `${customWidth}px` }}>{width} {height}</div>
      <button onClick={() => setCustomWidth(prev => prev + 100)}>Add witdh</button>
    </>
  )
}

Params:

PropertyDescriptionTypeDefault
refRef of element.RefRequired
onResizeCallback on resize element.() => voidOptional
boxType The box model to use for the ResizeObserver.'border-box' / 'content-box' / 'device-pixel-content-box'content-box

Return:

PropertyDescriptionType
widthWidth of resize element.number
heightHeight of resize element.number

useEventListener

import { useEventListener } from '@appello/web-kit';

Hook for handling events "dblclick" | "drag" | "dragend" etc.

API:

import { useEventListener } from '@appello/web-kit';

const Component = () => {
  const buttonRef = useRef<HTMLButtonElement>(null)
  const documentRef = useRef<Document>(document)

  const onScroll = (event: Event) => {
    console.log('window scrolled!', event)
  }

  const onClick = (event: Event) => {
    console.log('button clicked!', event)
  }

  const onVisibilityChange = (event: Event) => {
    console.log('doc visibility changed!', {
      isVisible: !document.hidden,
      event,
    })
  }

  useEventListener('scroll', onScroll)
  useEventListener('visibilitychange', onVisibilityChange, documentRef)
  useEventListener('click', onClick, buttonRef)

  return (
    <div style={{ minHeight: '200vh' }}>
      <button ref={buttonRef}>Click me</button>
    </div>
  )
}

Params:

PropertyDescriptionTypeDefault
eventNameThe name of the event to listen for."copy" / "change" / "drop" / "dblclick"Required
handlerThe event handler function.() => voidRequired
elementThe DOM element or media query list to attach the event listener to.RefObject<T>Optional
optionsAn options object that specifies characteristics about the event listener.boolean / AddEventListenerOptionsOptional

useGeolocation

import { useGeolocation } from '@appello/web-kit';

Hook for handling geolocation.

API:

import { useGeolocation } from '@appello/web-kit';

const Component = () => {
  const { latitude, longitude } = useGeolocation()

  return (
    <div>
      {latitude} {longitude}
    </div>
  )
}

Types:

interface PositionOptions {
    enableHighAccuracy?: boolean;
    maximumAge?: number;
    timeout?: number;
}

interface GeolocationCoordinates {
  accuracy: number;
  altitude: number | null;
  altitudeAccuracy: number | null;
  heading: number | null;
  latitude: number;
  longitude: number;
  speed: number | null;
}

export interface GeolocationState extends GeolocationCoordinates {
  loading: boolean;
  error?: Nullable<GeolocationPositionError>;
}

Params:

PropertyDescriptionTypeDefault
optionsOptions for geolocation.PositionOptionsOptional

Return:

PropertyDescriptionType
State of geolocation.Options for getCurrentPosition and watchPosition events.GeolocationState

useIdle

import { useIdle } from '@appello/web-kit';

Hook to check user activity.

API:

import { useIdle } from '@appello/web-kit';

const Component = () => {
  const isActive = useIdle()

  return (
    <div>{isActive}</div>
  )
}

Params:

PropertyDescriptionTypeDefault
optionsOptions for geolocation.PositionOptionsOptional

Return:

PropertyDescriptionType
state of geolocationOptions.GeolocationState

useInfiniteScroll

import { useInfiniteScroll } from '@appello/web-kit';

Hook for working with infinite scroll.

API:

import { useInfiniteScroll } from '@appello/web-kit';
import { useUpdateEffect } from "@appello/common";

const Component = () => {
  const [data, setData] = useState<number[]>([1, 2, 3, 4, 5, 6, 7]);
  const [loading, setLoading] = useState(false);
  const [hasNextPage, setHasNextPage] = useState(true);

  const [ref, { rootRef }] = useInfiniteScroll({
    hasNextPage: hasNextPage,
    rootMargin: '0px 0px 400px 0px',
    loading,
    onLoadMore: () => {
      setLoading(true);
      setTimeout(() => {
        setData(prv => [...prv, ...[1, 2, 3, 4]])
        setLoading(false);
      }, 400)
    }
  })

  useUpdateEffect(() => {
    if (data.length > 50) {
      setHasNextPage(false)
    }
  }, [data.length])

  return (
    <div
      ref={rootRef}
      style={{
        height: 400,
        overflowY: 'scroll',
        display: "flex",
        flexDirection: "column-reverse",
      }}
    >
      {data.map((item, index) => (
        <div 
          key={index} 
          style={{
            width: 100,
            height: 200,
            margin: 10,
            backgroundColor: '#000'
          }}
        >{index} - {item}</div>
      ))}
      
      {(loading || hasNextPage) && (
        <div ref={ref as any}>LOADING...</div>
      )}
    </div>
  );
}

Params:

PropertyDescriptionTypeDefault
loadingLoading content.booleanRequired
hasNextPageLoading content.booleanRequired
onLoadMoreCallback function for call more data.VoidFunctionRequired
rootMarginA margin around the root. Default ts '0%'.stringOptional
disabledDisabled called callback.booleanOptional
delayDelay before calling callback functions.numberOptional

Return:

PropertyDescriptionType
ref, { rootRef }Ref - this is the element on which the IntersectionObserver event will be processed. RootRef - this is the parent block in which the scroll isArray<ref, { rootRef }>

useIntersectionObserver

import { useIntersectionObserver } from '@appello/web-kit';

Hook for working with IntersectionObserver.

API:

import { useIntersectionObserver } from '@appello/web-kit';

const Component = () => {
  const { isIntersecting, ref } = useIntersectionObserver({
    threshold: 0.5,
  })

  return (
    <div
      ref={ref}
      style={{
        minHeight: '100vh',
        display: 'flex',
        border: '1px dashed #000',
        fontSize: '2rem',
      }}
    >
      <div style={{ margin: 'auto' }}>Block</div>
    </div>
  );
}

Params:

PropertyDescriptionTypeDefault
rootLoading content.Element / Document / nullOptional
rootMarginA margin around the root. Default ts '0%'.stringOptional
thresholdA threshold indicating the percentage of the target's visibility needed to trigger the callback.numberOptional
freezeOnceVisibleIf true, freezes the intersection state once the element becomes visible.booleanOptional
onChangeA callback function to be invoked when the intersection state changes.(isIntersecting: boolean, entry: IntersectionObserverEntry) => voidOptional
initialIsIntersectingThe initial state of the intersection.booleanOptional

Return:

PropertyDescriptionType
refRef - this is the element on which the IntersectionObserver.Ref
isIntersectingShows the activity of the observerboolean
entryDescribes the intersection between the target element and its root container at a specific moment of transition.IntersectionObserverEntry

useListQueryParams

import { useListQueryParams } from '@appello/web-kit';

Hook for working with query parameters like page, search, filters.

API:

import { useIntersectionObserver } from '@appello/web-kit';

const Component = () => {
  const { isIntersecting, ref } = useIntersectionObserver({
    threshold: 0.5,
  })

  return (
    <div
      ref={ref}
      style={{
        minHeight: '100vh',
        display: 'flex',
        border: '1px dashed #000',
        fontSize: '2rem',
      }}
    >
      <div style={{ margin: 'auto' }}>Block</div>
    </div>
  );
}

Params:

PropertyDescriptionTypeDefault
rootLoading content.Element / Document / nullOptional
rootMarginA margin around the root. Default ts '0%'.stringOptional
thresholdA threshold indicating the percentage of the target's visibility needed to trigger the callback.numberOptional
freezeOnceVisibleIf true, freezes the intersection state once the element becomes visible.booleanOptional
onChangeA callback function to be invoked when the intersection state changes.(isIntersecting: boolean, entry: IntersectionObserverEntry) => voidOptional
initialIsIntersectingThe initial state of the intersection.booleanOptional

Return:

PropertyDescriptionType
refRef - this is the element on which the IntersectionObserver.Ref
isIntersectingShows the activity of the observerboolean
entryDescribes the intersection between the target element and its root container at a specific moment of transition.IntersectionObserverEntry

2.3.1

9 months ago

2.3.0

9 months ago

2.2.0

9 months ago

2.1.0

9 months ago

2.0.0

9 months ago

1.1.10-alpha.0

12 months ago

1.1.9

2 years ago

1.1.8

2 years ago

1.1.7

2 years ago

1.1.6

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago