@rodrigodagostino/svelte-draggable-drawer 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,18 @@
1
1
  <script lang="ts">
2
+ import {
3
+ RANGE_END_DEFAULT,
4
+ RANGE_START_DEFAULT,
5
+ SNAP_POINT_OFFSET,
6
+ } from '../constants/index.js';
2
7
  import { setDrawerRootState } from '../states/index.js';
3
8
  import type { DrawerRootProps } from '../types/props.js';
9
+ import { toPixels } from '../utils/index.js';
10
+
4
11
  let {
5
12
  ref = $bindable(null),
13
+ range = { start: RANGE_START_DEFAULT, end: RANGE_END_DEFAULT },
14
+ snapPoints = [],
15
+ activeSnapPoint = $bindable(null),
6
16
  isOpen = $bindable(false),
7
17
  children,
8
18
  ...restProps
@@ -13,19 +23,23 @@
13
23
  $effect(() => {
14
24
  rootState.props = {
15
25
  ref,
26
+ range,
27
+ snapPoints: snapPoints.sort((a, b) => toPixels(a, 0) - toPixels(b, 0)),
28
+ activeSnapPoint,
16
29
  isOpen,
17
30
  };
18
31
  });
19
32
 
20
33
  $effect(() => {
34
+ activeSnapPoint = rootState.activeSnapPoint ?? null;
21
35
  isOpen = rootState.props.isOpen || false;
22
36
  });
23
37
 
24
38
  const classes = $derived(['sdd-root', restProps.class]);
25
39
  let pointerId: PointerEvent['pointerId'] | null = null;
26
40
 
27
- const TOP_THRESHOLD = 2 / 5;
28
- const BOTTOM_THRESHOLD = 3 / 5;
41
+ const START_THRESHOLD = 2 / 5;
42
+ const END_THRESHOLD = 2 / 5;
29
43
 
30
44
  let transitionTimeoutId: ReturnType<typeof setTimeout> | null = null;
31
45
 
@@ -57,10 +71,30 @@
57
71
  rootState.dragState = 'drag';
58
72
 
59
73
  rootState.pointer = { x: clientX, y: clientY };
60
- rootState.props.isOpen =
61
- rootState.pointerOrigin.y > window.innerHeight / 2
62
- ? clientY < window.innerHeight * BOTTOM_THRESHOLD
63
- : clientY < window.innerHeight * TOP_THRESHOLD;
74
+ const handleTop = rootState.handle?.getBoundingClientRect()?.top ?? clientY;
75
+ const visibleHeight = window.innerHeight - handleTop;
76
+ const snapPoints = rootState.props.snapPoints ?? [];
77
+ const snapPointsInPx = (snapPoints ?? []).map((point) => toPixels(point, 0));
78
+
79
+ if (snapPointsInPx.length) {
80
+ const isBelowFirst = visibleHeight <= snapPointsInPx[0] - SNAP_POINT_OFFSET;
81
+ const isAboveLast = visibleHeight >= snapPointsInPx.at(-1)! + SNAP_POINT_OFFSET;
82
+
83
+ if (isBelowFirst || isAboveLast) {
84
+ rootState.activeSnapPoint = null;
85
+ } else {
86
+ const index = snapPointsInPx.findIndex(
87
+ (point) => Math.abs(visibleHeight - point) <= SNAP_POINT_OFFSET
88
+ );
89
+ if (index !== -1) rootState.activeSnapPoint = { index, value: snapPoints[index] };
90
+ }
91
+
92
+ rootState.props.isOpen = !isBelowFirst;
93
+ } else {
94
+ const threshold =
95
+ rootState.pointerOrigin.y > window.innerHeight / 2 ? START_THRESHOLD : END_THRESHOLD;
96
+ rootState.props.isOpen = handleTop < window.innerHeight * threshold;
97
+ }
64
98
  }
65
99
 
66
100
  function handlePointerUp() {
@@ -2,6 +2,6 @@ import type { DrawerRootProps } from '../types/props.js';
2
2
  type $$ComponentProps = DrawerRootProps & {
3
3
  class?: string;
4
4
  };
5
- declare const Drawer: import("svelte").Component<$$ComponentProps, {}, "ref" | "isOpen">;
5
+ declare const Drawer: import("svelte").Component<$$ComponentProps, {}, "ref" | "activeSnapPoint" | "isOpen">;
6
6
  type Drawer = ReturnType<typeof Drawer>;
7
7
  export default Drawer;
@@ -1,44 +1,64 @@
1
1
  <script lang="ts">
2
+ import { untrack } from 'svelte';
3
+ import { RANGE_END_DEFAULT, RANGE_START_DEFAULT } from '../constants/index.js';
2
4
  import { getDrawerRootState } from '../states/drawer.svelte.js';
3
5
  import type { DrawerBackdropProps as BackdropProps } from '../types/props.js';
6
+ import { clamp, toPixels } from '../utils/index.js';
4
7
 
5
8
  let { ref = $bindable(null), ...restProps }: BackdropProps & { class?: string } = $props();
6
9
 
7
- let offsetHeight: number = $state(0);
8
-
9
10
  const rootState = getDrawerRootState();
10
11
 
11
12
  const classes = $derived(['sdd-backdrop', restProps.class]);
12
13
 
13
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
14
- function getStyleOpacity(...args: unknown[]) {
15
- if (rootState.dragState === 'drag' && rootState.pointer) {
16
- return (rootState.pointer.y / offsetHeight / 2 - 0.5) * -1;
14
+ function getStyleOpacity() {
15
+ if (rootState.dragState.startsWith('drag') && rootState.pointer) {
16
+ const handleTop = rootState.handle?.getBoundingClientRect().top ?? rootState.pointer.y;
17
+
18
+ const rangeStart = toPixels(rootState.props.range?.start, RANGE_START_DEFAULT);
19
+ const rangeEnd = Math.max(
20
+ toPixels(rootState.props.range?.end, RANGE_END_DEFAULT),
21
+ rootState.props.snapPoints?.length && rootState.content
22
+ ? rootState.content?.offsetHeight -
23
+ toPixels(rootState.props.snapPoints[0], RANGE_END_DEFAULT)
24
+ : RANGE_END_DEFAULT
25
+ );
26
+ const availableHeight = window.innerHeight - rangeEnd - rangeStart;
27
+ const handleOffset = clamp(handleTop - rangeEnd, 0, window.innerHeight - rangeStart);
28
+ const closedProgress = handleOffset / availableHeight;
29
+ const opacity = 0.5 - closedProgress / 2;
30
+
31
+ return clamp(opacity, 0, 0.5);
17
32
  }
18
- if (rootState.props.isOpen) return 0.5;
19
- return 0;
33
+
34
+ return rootState.props.isOpen ? 0.5 : 0;
20
35
  }
21
36
 
22
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
- function getStyleTransition(...args: unknown[]) {
24
- if (rootState.dragState !== 'drag-start' && rootState.dragState !== 'drag')
25
- return 'opacity 240ms';
37
+ function getStyleTransition() {
38
+ if (!rootState.dragState.startsWith('drag')) return 'opacity 240ms';
26
39
  return 'none';
27
40
  }
28
41
 
29
- const styleOpacity = $derived(
30
- getStyleOpacity(rootState.pointer, rootState.dragState, rootState.props.isOpen)
31
- );
32
- const styleTransition = $derived(getStyleTransition(rootState.dragState));
42
+ const styleOpacity = $derived.by(() => {
43
+ void rootState.pointer;
44
+ void rootState.dragState;
45
+ void rootState.props.isOpen;
46
+ return untrack(() => getStyleOpacity());
47
+ });
48
+
49
+ const styleTransition = $derived.by(() => {
50
+ void rootState.dragState;
51
+ return untrack(() => getStyleTransition());
52
+ });
33
53
 
34
54
  const handleClick = () => {
55
+ rootState.activeSnapPoint = null;
35
56
  rootState.props.isOpen = false;
36
57
  };
37
58
  </script>
38
59
 
39
60
  <div
40
61
  bind:this={ref}
41
- bind:offsetHeight
42
62
  class={classes}
43
63
  style:opacity={styleOpacity}
44
64
  style:transition={styleTransition}
@@ -1,6 +1,9 @@
1
1
  <script lang="ts">
2
+ import { untrack } from 'svelte';
3
+ import { RANGE_END_DEFAULT, RANGE_START_DEFAULT } from '../constants/index.js';
2
4
  import { getDrawerRootState } from '../states/drawer.svelte.js';
3
5
  import type { DrawerContentProps as ContentProps } from '../types/props.js';
6
+ import { applyRubberBand, toCSSLength, toPixels } from '../utils/index.js';
4
7
 
5
8
  let {
6
9
  ref = $bindable(null),
@@ -16,36 +19,52 @@
16
19
 
17
20
  const classes = $derived(['sdd-content', restProps.class]);
18
21
 
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- function getStyleTransform(...args: unknown[]) {
22
+ function getStyleTransform() {
21
23
  if (rootState.dragState === 'drag') {
22
24
  if (!rootState.pointer || !rootState.pointerOrigin || !rootState.contentOrigin) return 'none';
23
- // Prevent the drawer from being dragged above the top of the screen or below the bottom.
24
- const y =
25
- rootState.pointerOrigin.y > window.innerHeight / 2
26
- ? rootState.pointer.y > rootState.pointerOrigin.y
27
- ? rootState.pointerOrigin.y
28
- : rootState.pointer.y
29
- : rootState.pointer.y < rootState.pointerOrigin.y
30
- ? rootState.pointerOrigin.y
31
- : rootState.pointer.y;
32
- // Set the position of the content relative to the pointer.
33
- const offset = rootState.contentOrigin.y - rootState.pointerOrigin.y;
34
-
35
- return `translate3d(0, ${y + offset}px, 0)`;
25
+
26
+ const startY = rootState.pointerOrigin.y;
27
+ const currentY = rootState.pointer.y;
28
+ const offset = rootState.contentOrigin.y - startY;
29
+
30
+ // Calculate where the drawer would be without any resistance.
31
+ const rawY = currentY + offset;
32
+
33
+ const START_LIMIT =
34
+ window.innerHeight - toPixels(rootState.props.range?.start, RANGE_START_DEFAULT);
35
+ const END_LIMIT = 0 + toPixels(rootState.props.range?.end, RANGE_END_DEFAULT);
36
+ let y = rawY;
37
+ const MAX_OVERDRAG = 120;
38
+
39
+ if (rawY < END_LIMIT) {
40
+ const overdrag = END_LIMIT - rawY;
41
+ y = END_LIMIT - applyRubberBand(overdrag, MAX_OVERDRAG);
42
+ } else if (rawY > START_LIMIT) {
43
+ const overdrag = rawY - START_LIMIT;
44
+ y = START_LIMIT + applyRubberBand(overdrag, MAX_OVERDRAG);
45
+ }
46
+
47
+ return `translate3d(0, ${y}px, 0)`;
36
48
  }
37
49
 
38
- if (rootState.props.isOpen)
39
- return `translate3d(0, calc(0% + ${rootState.handle?.getBoundingClientRect().height || 24}px), 0)`;
50
+ if (rootState.activeSnapPoint !== null) {
51
+ return `translate3d(0, calc(100% - ${toCSSLength(rootState.props.snapPoints![rootState.activeSnapPoint.index])}), 0)`;
52
+ }
40
53
 
41
- return `translate3d(0, calc(100% - ${rootState.handle?.getBoundingClientRect().height || 48}px), 0)`;
54
+ return rootState.props.isOpen
55
+ ? `translate3d(0, calc(0% + ${toCSSLength(rootState.props.range?.end ?? RANGE_END_DEFAULT)}), 0)`
56
+ : `translate3d(0, calc(100% - ${toCSSLength(rootState.props.range?.start ?? RANGE_START_DEFAULT)}), 0)`;
42
57
  }
43
58
 
44
- const styleTransform = $derived(
45
- getStyleTransform(rootState.pointer, rootState.dragState, rootState.props.isOpen)
46
- );
59
+ const styleTransform = $derived.by(() => {
60
+ void rootState.pointer;
61
+ void rootState.dragState;
62
+ void rootState.props.isOpen;
63
+ return untrack(() => getStyleTransform());
64
+ });
65
+
47
66
  const styleTransition = $derived(
48
- rootState.dragState !== 'drag-start' && rootState.dragState !== 'drag'
67
+ !rootState.dragState.startsWith('drag')
49
68
  ? `transform 400ms cubic-bezier(0.32, 0.72, 0, 1)`
50
69
  : 'none'
51
70
  );
@@ -0,0 +1,3 @@
1
+ export declare const RANGE_START_DEFAULT = 0;
2
+ export declare const RANGE_END_DEFAULT = 48;
3
+ export declare const SNAP_POINT_OFFSET = 80;
@@ -0,0 +1,3 @@
1
+ export const RANGE_START_DEFAULT = 0;
2
+ export const RANGE_END_DEFAULT = 48;
3
+ export const SNAP_POINT_OFFSET = 80;
@@ -1,12 +1,26 @@
1
- import type { DrawerRootStateContext as Context } from '../types/index.js';
1
+ import type { DrawerRootProps as RootProps } from '../types/index.js';
2
2
  declare class DrawerRootState {
3
- props: Context['props'];
4
- dragState: Context['dragState'];
5
- content: Context['content'];
6
- handle: Context['handle'];
7
- pointer: Context['pointer'];
8
- pointerOrigin: Context['pointerOrigin'];
9
- contentOrigin: Context['contentOrigin'];
3
+ ref: HTMLElement | null;
4
+ props: RootProps;
5
+ dragState: 'idle' | 'drag-start' | 'drag' | 'drop';
6
+ content: HTMLElement | null;
7
+ handle: HTMLButtonElement | null;
8
+ pointer: {
9
+ x: number;
10
+ y: number;
11
+ } | null;
12
+ pointerOrigin: {
13
+ x: number;
14
+ y: number;
15
+ } | null;
16
+ contentOrigin: {
17
+ x: number;
18
+ y: number;
19
+ } | null;
20
+ activeSnapPoint: {
21
+ index: number;
22
+ value: string | number;
23
+ } | null;
10
24
  }
11
25
  export declare function setDrawerRootState(): DrawerRootState;
12
26
  export declare function getDrawerRootState(): DrawerRootState;
@@ -1,5 +1,6 @@
1
1
  import { getContext, setContext } from 'svelte';
2
2
  class DrawerRootState {
3
+ ref = $state(null);
3
4
  props = $state({});
4
5
  dragState = $state('idle');
5
6
  content = $state(null);
@@ -7,6 +8,7 @@ class DrawerRootState {
7
8
  pointer = $state.raw(null);
8
9
  pointerOrigin = $state.raw(null);
9
10
  contentOrigin = $state.raw(null);
11
+ activeSnapPoint = $state(null);
10
12
  }
11
13
  const KEY = Symbol('Drawer.RootState');
12
14
  export function setDrawerRootState() {
@@ -1,2 +1 @@
1
1
  export * from './props.js';
2
- export * from './states.js';
@@ -1,2 +1 @@
1
1
  export * from './props.js';
2
- export * from './states.js';
@@ -1,6 +1,15 @@
1
1
  import type { Snippet } from 'svelte';
2
2
  export interface DrawerRootProps {
3
- ref?: HTMLDivElement | null;
3
+ ref?: HTMLElement | null;
4
+ range?: {
5
+ start: string | number;
6
+ end: string | number;
7
+ };
8
+ snapPoints?: (string | number)[];
9
+ activeSnapPoint?: {
10
+ index: number;
11
+ value: string | number;
12
+ } | null;
4
13
  isOpen?: boolean;
5
14
  children?: Snippet;
6
15
  }
@@ -0,0 +1,2 @@
1
+ export declare function toCSSLength(value: number | string): string;
2
+ export declare function toPixels(value: string | number | undefined, fallback: number): number;
@@ -0,0 +1,12 @@
1
+ export function toCSSLength(value) {
2
+ return typeof value === 'number' ? `${value}px` : value;
3
+ }
4
+ export function toPixels(value, fallback) {
5
+ if (value === undefined)
6
+ return fallback;
7
+ if (typeof value === 'number')
8
+ return value;
9
+ if (value.endsWith('%'))
10
+ return (parseFloat(value) / 100) * window.innerHeight;
11
+ return parseFloat(value);
12
+ }
@@ -0,0 +1 @@
1
+ export declare function clamp(value: number, min: number, max: number): number;
@@ -0,0 +1,3 @@
1
+ export function clamp(value, min, max) {
2
+ return Math.min(Math.max(value, min), max);
3
+ }
@@ -0,0 +1,3 @@
1
+ export * from './conversion.ts';
2
+ export * from './geometry.ts';
3
+ export * from './physics.ts';
@@ -0,0 +1,3 @@
1
+ export * from "./conversion.js";
2
+ export * from "./geometry.js";
3
+ export * from "./physics.js";
@@ -0,0 +1 @@
1
+ export declare function applyRubberBand(overdrag: number, overdragLimit: number): number;
@@ -0,0 +1,4 @@
1
+ export function applyRubberBand(overdrag, overdragLimit) {
2
+ // Apple iOS Rubber-Band formula.
3
+ return (overdrag * overdragLimit) / (overdrag + overdragLimit);
4
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rodrigodagostino/svelte-draggable-drawer",
3
3
  "description": "Create accessible, draggable drawers in Svelte, with keyboard, mouse, and touch support.",
4
- "version": "0.2.0",
4
+ "version": "0.4.0",
5
5
  "author": "Rodrigo D’Agostino <rodrigo.dagostino@proton.me>",
6
6
  "keywords": [
7
7
  "draggable",
@@ -1,20 +0,0 @@
1
- import type { DrawerRootProps as RootProps } from './props.js';
2
- export interface DrawerRootStateContext {
3
- ref: HTMLUListElement | null;
4
- props: RootProps;
5
- dragState: 'idle' | 'drag-start' | 'drag' | 'drop';
6
- content: HTMLDivElement | null;
7
- handle: HTMLButtonElement | null;
8
- pointer: {
9
- x: number;
10
- y: number;
11
- } | null;
12
- pointerOrigin: {
13
- x: number;
14
- y: number;
15
- } | null;
16
- contentOrigin: {
17
- x: number;
18
- y: number;
19
- } | null;
20
- }
@@ -1 +0,0 @@
1
- export {};