@rodrigodagostino/svelte-draggable-drawer 0.3.0 → 0.4.1

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,11 +1,18 @@
1
1
  <script lang="ts">
2
- import { RANGE_END_DEFAULT, RANGE_START_DEFAULT } from '../constants/index.js';
2
+ import {
3
+ RANGE_END_DEFAULT,
4
+ RANGE_START_DEFAULT,
5
+ SNAP_POINT_OFFSET,
6
+ } from '../constants/index.js';
3
7
  import { setDrawerRootState } from '../states/index.js';
4
8
  import type { DrawerRootProps } from '../types/props.js';
9
+ import { isOrResidesInInteractiveElement, toPixels } from '../utils/index.js';
5
10
 
6
11
  let {
7
12
  ref = $bindable(null),
8
13
  range = { start: RANGE_START_DEFAULT, end: RANGE_END_DEFAULT },
14
+ snapPoints = [],
15
+ activeSnapPoint = $bindable(null),
9
16
  isOpen = $bindable(false),
10
17
  children,
11
18
  ...restProps
@@ -17,38 +24,65 @@
17
24
  rootState.props = {
18
25
  ref,
19
26
  range,
27
+ snapPoints: snapPoints.sort((a, b) => toPixels(a, 0) - toPixels(b, 0)),
28
+ activeSnapPoint,
20
29
  isOpen,
21
30
  };
22
31
  });
23
32
 
24
33
  $effect(() => {
34
+ activeSnapPoint = rootState.activeSnapPoint ?? null;
25
35
  isOpen = rootState.props.isOpen || false;
26
36
  });
27
37
 
28
38
  const classes = $derived(['sdd-root', restProps.class]);
29
39
  let pointerId: PointerEvent['pointerId'] | null = null;
30
40
 
31
- const TOP_THRESHOLD = 2 / 5;
32
- const BOTTOM_THRESHOLD = 3 / 5;
41
+ const START_THRESHOLD = 2 / 5;
42
+ const END_THRESHOLD = 2 / 5;
33
43
 
34
44
  let transitionTimeoutId: ReturnType<typeof setTimeout> | null = null;
35
45
 
36
46
  function handlePointerDown(e: PointerEvent) {
47
+ if (!rootState.content) return;
48
+
37
49
  const target = e.target as HTMLElement;
38
- if (!rootState.handle || !target.closest('[data-role="handle"]') || !rootState.content) return;
50
+ const isOrResidesInContent = target.closest('.sdd-content');
51
+ if (!isOrResidesInContent) return;
52
+
53
+ const isOrResidesInInteractiveElem = isOrResidesInInteractiveElement(target, rootState.content);
54
+ // Stop non-main buttons from interacting with the drawer.
55
+ if (e.button !== 0) {
56
+ // Let non-main buttons act normally on interactive elements.
57
+ if (!isOrResidesInInteractiveElem) e.preventDefault();
58
+ return;
59
+ }
60
+
61
+ // Prevent dragging if the current drawer contains a content handle, but we’re not dragging from it.
62
+ const hasHandle = !!rootState.handle;
63
+ const isOrResidesInHandle = target.closest('.sdd-content-handle');
64
+ if (hasHandle && !isOrResidesInHandle && !isOrResidesInInteractiveElem) {
65
+ e.preventDefault();
66
+ return;
67
+ }
68
+
69
+ // Prevent dragging if the current drawer contains an interactive element and
70
+ // we’re also not dragging from a handle inside that interactive element.
71
+ if (isOrResidesInInteractiveElem && !isOrResidesInHandle) return;
39
72
 
73
+ const draggedElem = rootState.handle ?? rootState.content;
40
74
  pointerId = e.pointerId;
41
- rootState.handle.setPointerCapture(pointerId);
75
+ draggedElem.setPointerCapture(pointerId);
42
76
  rootState.pointer = { x: e.clientX, y: e.clientY };
43
77
  rootState.pointerOrigin = { x: e.clientX, y: e.clientY };
44
78
  rootState.contentOrigin = rootState.content.getBoundingClientRect();
45
79
  rootState.dragState = 'drag-start';
46
80
 
47
- rootState.handle.addEventListener('pointermove', handlePointerMove);
48
- rootState.handle.addEventListener(
81
+ draggedElem.addEventListener('pointermove', handlePointerMove);
82
+ draggedElem.addEventListener(
49
83
  'pointerup',
50
84
  () => {
51
- rootState.handle?.removeEventListener('pointermove', handlePointerMove);
85
+ draggedElem?.removeEventListener('pointermove', handlePointerMove);
52
86
  handlePointerUp();
53
87
  },
54
88
  { once: true }
@@ -61,10 +95,33 @@
61
95
  rootState.dragState = 'drag';
62
96
 
63
97
  rootState.pointer = { x: clientX, y: clientY };
64
- rootState.props.isOpen =
65
- rootState.pointerOrigin.y > window.innerHeight / 2
66
- ? clientY < window.innerHeight * BOTTOM_THRESHOLD
67
- : clientY < window.innerHeight * TOP_THRESHOLD;
98
+ const draggedTop =
99
+ rootState.handle?.getBoundingClientRect()?.top ??
100
+ rootState.content?.getBoundingClientRect()?.top ??
101
+ clientY;
102
+ const visibleHeight = window.innerHeight - draggedTop;
103
+ const snapPoints = rootState.props.snapPoints ?? [];
104
+ const snapPointsInPx = (snapPoints ?? []).map((point) => toPixels(point, 0));
105
+
106
+ if (snapPointsInPx.length) {
107
+ const isBelowFirst = visibleHeight <= snapPointsInPx[0] - SNAP_POINT_OFFSET;
108
+ const isAboveLast = visibleHeight >= snapPointsInPx.at(-1)! + SNAP_POINT_OFFSET;
109
+
110
+ if (isBelowFirst || isAboveLast) {
111
+ rootState.activeSnapPoint = null;
112
+ } else {
113
+ const index = snapPointsInPx.findIndex(
114
+ (point) => Math.abs(visibleHeight - point) <= SNAP_POINT_OFFSET
115
+ );
116
+ if (index !== -1) rootState.activeSnapPoint = { index, value: snapPoints[index] };
117
+ }
118
+
119
+ rootState.props.isOpen = !isBelowFirst;
120
+ } else {
121
+ const threshold =
122
+ rootState.pointerOrigin.y > window.innerHeight / 2 ? START_THRESHOLD : END_THRESHOLD;
123
+ rootState.props.isOpen = draggedTop < window.innerHeight * threshold;
124
+ }
68
125
  }
69
126
 
70
127
  function handlePointerUp() {
@@ -100,6 +157,11 @@
100
157
  }
101
158
  </script>
102
159
 
160
+ <pre style="position: fixed; top: 2rem; left: 2rem;">
161
+ <code>activeSnapPoint: {JSON.stringify(rootState.activeSnapPoint)}</code>
162
+ <code>isOpen: {JSON.stringify(isOpen)}</code>
163
+ </pre>
164
+
103
165
  <div class={classes} data-drag-state={rootState.dragState} onpointerdown={handlePointerDown}>
104
166
  {@render children?.()}
105
167
  </div>
@@ -111,15 +173,9 @@
111
173
  pointer-events: none;
112
174
  z-index: 9999;
113
175
 
114
- &:not(:has(.sdd-content-handle)),
115
- & :global(.sdd-content-handle) {
176
+ /* Prevent touch gestures during a pointer drag. */
177
+ &[data-drag-state*='ptr'] {
116
178
  touch-action: none;
117
- cursor: grab;
118
- }
119
-
120
- &[data-drag-state*='drag'],
121
- &[data-drag-state*='drag'] :global(.sdd-content-handle) {
122
- cursor: grabbing;
123
179
  }
124
180
  }
125
181
  </style>
@@ -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;
@@ -3,31 +3,38 @@
3
3
  import { RANGE_END_DEFAULT, RANGE_START_DEFAULT } from '../constants/index.js';
4
4
  import { getDrawerRootState } from '../states/drawer.svelte.js';
5
5
  import type { DrawerBackdropProps as BackdropProps } from '../types/props.js';
6
- import { toPixels } from '../utils/index.js';
6
+ import { clamp, toPixels } from '../utils/index.js';
7
7
 
8
8
  let { ref = $bindable(null), ...restProps }: BackdropProps & { class?: string } = $props();
9
9
 
10
- let offsetHeight: number = $state(0);
11
-
12
10
  const rootState = getDrawerRootState();
13
11
 
14
12
  const classes = $derived(['sdd-backdrop', restProps.class]);
15
13
 
16
14
  function getStyleOpacity() {
17
15
  if (rootState.dragState.startsWith('drag') && rootState.pointer) {
18
- const handleRect = rootState.handle?.getBoundingClientRect();
19
- if (!handleRect) return 0;
16
+ const draggedTop =
17
+ rootState.handle?.getBoundingClientRect().top ??
18
+ rootState.content?.getBoundingClientRect().top ??
19
+ rootState.pointer.y;
20
+ const currentReveal = window.innerHeight - draggedTop;
20
21
 
21
22
  const rangeStart = toPixels(rootState.props.range?.start, RANGE_START_DEFAULT);
22
23
  const rangeEnd = toPixels(rootState.props.range?.end, RANGE_END_DEFAULT);
23
- const windowHeightWithoutRange = window.innerHeight - rangeEnd - rangeStart;
24
- const handleTop = Math.min(
25
- Math.max((handleRect.top ?? 0) - rangeEnd, 0),
26
- window.innerHeight - rangeStart
27
- );
28
- const opacity = (handleTop / windowHeightWithoutRange / 2 - 0.5) * -1;
24
+ const contentHeight = rootState.content?.offsetHeight ?? 0;
25
+ // Reveal amount at “fully open”, which is capped to the content’s own height,
26
+ // since it may no longer span the full viewport.
27
+ const openLimit = Math.min(contentHeight, window.innerHeight - rangeEnd);
28
+ // Treat the first (smallest) snap point as the “open” reference for opacity.
29
+ const openReveal = rootState.props.snapPoints?.length
30
+ ? Math.min(toPixels(rootState.props.snapPoints[0], RANGE_END_DEFAULT), openLimit)
31
+ : openLimit;
32
+
33
+ const availableHeight = openReveal - rangeStart;
34
+ const handleOffset = clamp(currentReveal - rangeStart, 0, availableHeight);
35
+ const openProgress = handleOffset / availableHeight;
29
36
 
30
- return Math.max(Math.min(opacity, 0.5), 0);
37
+ return clamp(openProgress / 2, 0, 0.5);
31
38
  }
32
39
 
33
40
  return rootState.props.isOpen ? 0.5 : 0;
@@ -51,13 +58,13 @@
51
58
  });
52
59
 
53
60
  const handleClick = () => {
61
+ rootState.activeSnapPoint = null;
54
62
  rootState.props.isOpen = false;
55
63
  };
56
64
  </script>
57
65
 
58
66
  <div
59
67
  bind:this={ref}
60
- bind:offsetHeight
61
68
  class={classes}
62
69
  style:opacity={styleOpacity}
63
70
  style:transition={styleTransition}
@@ -1,5 +1,6 @@
1
1
  <script lang="ts">
2
2
  import { untrack } from 'svelte';
3
+ import { BROWSER } from 'esm-env';
3
4
  import { RANGE_END_DEFAULT, RANGE_START_DEFAULT } from '../constants/index.js';
4
5
  import { getDrawerRootState } from '../states/drawer.svelte.js';
5
6
  import type { DrawerContentProps as ContentProps } from '../types/props.js';
@@ -20,36 +21,52 @@
20
21
  const classes = $derived(['sdd-content', restProps.class]);
21
22
 
22
23
  function getStyleTransform() {
24
+ if (!BROWSER) return 'translate3d(0, 100%, 0)';
25
+
26
+ const START_LIMIT = toPixels(rootState.props.range?.start, RANGE_START_DEFAULT);
27
+ const END_LIMIT = Math.min(
28
+ rootState.content?.getBoundingClientRect().height ?? 0,
29
+ window.innerHeight - toPixels(rootState.props.range?.end, RANGE_END_DEFAULT)
30
+ );
31
+
23
32
  if (rootState.dragState === 'drag') {
24
- if (!rootState.pointer || !rootState.pointerOrigin || !rootState.contentOrigin) return 'none';
33
+ if (!rootState.pointer || !rootState.pointerOrigin || !rootState.contentOrigin)
34
+ return 'translate3d(0, 100%, 0)';
25
35
 
26
36
  const startY = rootState.pointerOrigin.y;
27
37
  const currentY = rootState.pointer.y;
28
38
  const offset = rootState.contentOrigin.y - startY;
29
39
 
30
- // Calculate where the drawer would be without any resistance.
31
- const rawY = currentY + offset;
40
+ // Where the content’s top edge would be without any resistance.
41
+ const rawTopY = currentY + offset;
42
+ // How much of the content that leaves revealed above the bottom edge.
43
+ const rawReveal = window.innerHeight - rawTopY;
32
44
 
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;
45
+ let y = rawReveal;
37
46
  const MAX_OVERDRAG = 120;
38
47
 
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);
48
+ if (rawReveal > END_LIMIT) {
49
+ const overdrag = rawReveal - END_LIMIT;
50
+ y = END_LIMIT + applyRubberBand(overdrag, MAX_OVERDRAG);
51
+ } else if (rawReveal < START_LIMIT) {
52
+ const overdrag = START_LIMIT - rawReveal;
53
+ y = START_LIMIT - applyRubberBand(overdrag, MAX_OVERDRAG);
45
54
  }
46
55
 
47
- return `translate3d(0, ${y}px, 0)`;
56
+ return `translate3d(0, calc(100% - ${y}px), 0)`;
57
+ }
58
+
59
+ if (rootState.activeSnapPoint !== null) {
60
+ const y = Math.min(
61
+ toPixels(rootState.props.snapPoints![rootState.activeSnapPoint.index], 0),
62
+ END_LIMIT
63
+ );
64
+ return `translate3d(0, calc(100% - ${y}px), 0)`;
48
65
  }
49
66
 
50
67
  return rootState.props.isOpen
51
- ? `translate3d(0, calc(0% + ${toCSSLength(rootState.props.range?.end ?? RANGE_END_DEFAULT)}), 0)`
52
- : `translate3d(0, calc(100% - ${toCSSLength(rootState.props.range?.start ?? RANGE_START_DEFAULT)}), 0)`;
68
+ ? `translate3d(0, calc(100% - ${END_LIMIT}px), 0)`
69
+ : `translate3d(0, calc(100% - ${START_LIMIT}px), 0)`;
53
70
  }
54
71
 
55
72
  const styleTransform = $derived.by(() => {
@@ -69,27 +86,34 @@
69
86
  <div
70
87
  bind:this={ref}
71
88
  class={classes}
89
+ style:max-height="calc(100% - {toCSSLength(rootState.props.range?.end ?? RANGE_START_DEFAULT)})"
72
90
  style:transform={styleTransform}
73
91
  style:transition={styleTransition}
92
+ data-drag-state={rootState.dragState}
74
93
  >
75
94
  {@render children?.()}
76
95
  </div>
77
96
 
78
97
  <style>
79
98
  .sdd-content {
99
+ position: fixed;
100
+ inset: auto 0;
101
+ bottom: 0;
80
102
  display: flex;
81
103
  flex-direction: column;
82
- width: calc(100% - 2rem);
83
- height: 100%;
84
- margin-inline: auto;
85
104
  pointer-events: auto;
86
- position: relative;
105
+ user-select: none;
87
106
  z-index: 1;
88
- }
89
107
 
90
- @media (min-width: 48em) {
91
- .sdd-content {
92
- width: calc(100% - 2.5rem);
108
+ &:not(:has(.sdd-content-handle)),
109
+ & :global(.sdd-content-handle) {
110
+ touch-action: none;
111
+ cursor: grab;
112
+ }
113
+
114
+ &[data-drag-state*='drag'],
115
+ &[data-drag-state*='drag'] :global(.sdd-content-handle) {
116
+ cursor: grabbing;
93
117
  }
94
118
  }
95
119
  </style>
@@ -1,2 +1,3 @@
1
1
  export declare const RANGE_START_DEFAULT = 0;
2
2
  export declare const RANGE_END_DEFAULT = 48;
3
+ export declare const SNAP_POINT_OFFSET = 80;
@@ -1,2 +1,3 @@
1
1
  export const RANGE_START_DEFAULT = 0;
2
2
  export const RANGE_END_DEFAULT = 48;
3
+ export const SNAP_POINT_OFFSET = 80;
@@ -17,6 +17,10 @@ declare class DrawerRootState {
17
17
  x: number;
18
18
  y: number;
19
19
  } | null;
20
+ activeSnapPoint: {
21
+ index: number;
22
+ value: string | number;
23
+ } | null;
20
24
  }
21
25
  export declare function setDrawerRootState(): DrawerRootState;
22
26
  export declare function getDrawerRootState(): DrawerRootState;
@@ -8,6 +8,7 @@ class DrawerRootState {
8
8
  pointer = $state.raw(null);
9
9
  pointerOrigin = $state.raw(null);
10
10
  contentOrigin = $state.raw(null);
11
+ activeSnapPoint = $state(null);
11
12
  }
12
13
  const KEY = Symbol('Drawer.RootState');
13
14
  export function setDrawerRootState() {
package/dist/styles.css CHANGED
@@ -1,16 +1,27 @@
1
1
  .sdd-content {
2
+ width: calc(100% - 2rem);
3
+ padding: 1.25rem;
4
+ margin-inline: auto;
2
5
  background-color: var(--sdd-white);
3
6
  border-radius: 1rem 1rem 0 0;
4
7
 
8
+ &:has(.sdd-content-handle) {
9
+ padding-block-start: 0;
10
+ }
11
+
5
12
  &::after {
6
13
  content: "";
7
14
  position: absolute;
8
- top: 100%;
15
+ top: calc(100% - 1px);
9
16
  left: 0;
10
17
  width: 100%;
11
18
  height: 50%;
12
19
  background-color: inherit;
13
20
  }
21
+
22
+ @media (min-width: 48em) {
23
+ width: calc(100% - 2.5rem);
24
+ }
14
25
  }
15
26
 
16
27
  .sdd-content-handle {
@@ -5,6 +5,11 @@ export interface DrawerRootProps {
5
5
  start: string | number;
6
6
  end: string | number;
7
7
  };
8
+ snapPoints?: (string | number)[];
9
+ activeSnapPoint?: {
10
+ index: number;
11
+ value: string | number;
12
+ } | null;
8
13
  isOpen?: boolean;
9
14
  children?: Snippet;
10
15
  }
@@ -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
+ }
@@ -1,2 +1,4 @@
1
1
  export * from './conversion.ts';
2
- export * from './physics.js';
2
+ export * from './geometry.ts';
3
+ export * from './physics.ts';
4
+ export * from './whereabouts.ts';
@@ -1,2 +1,4 @@
1
1
  export * from "./conversion.js";
2
- export * from './physics.js';
2
+ export * from "./geometry.js";
3
+ export * from "./physics.js";
4
+ export * from "./whereabouts.js";
@@ -0,0 +1,4 @@
1
+ export declare const INTERACTIVE_ELEMENTS: Set<string>;
2
+ export declare const INTERACTIVE_ROLE_ATTRIBUTES: Set<string>;
3
+ export declare const INTERACTIVE_SELECTORS: string;
4
+ export declare function isOrResidesInInteractiveElement(target: HTMLElement, root: HTMLElement): boolean;
@@ -0,0 +1,55 @@
1
+ export const INTERACTIVE_ELEMENTS = new Set([
2
+ 'a',
3
+ 'audio',
4
+ 'button',
5
+ 'input',
6
+ 'optgroup',
7
+ 'option',
8
+ 'select',
9
+ 'summary',
10
+ 'textarea',
11
+ 'video',
12
+ ]);
13
+ const INTERACTIVE_ROLES = new Set([
14
+ 'button',
15
+ 'checkbox',
16
+ 'combobox',
17
+ 'link',
18
+ 'menuitem',
19
+ 'menuitemcheckbox',
20
+ 'menuitemradio',
21
+ 'radio',
22
+ 'searchbox',
23
+ 'slider',
24
+ 'spinbutton',
25
+ 'switch',
26
+ 'tab',
27
+ 'textbox',
28
+ ]);
29
+ export const INTERACTIVE_ROLE_ATTRIBUTES = new Set([...INTERACTIVE_ROLES].map((role) => `[role="${role}"]`));
30
+ export const INTERACTIVE_SELECTORS = [
31
+ ...INTERACTIVE_ELEMENTS,
32
+ ...INTERACTIVE_ROLE_ATTRIBUTES,
33
+ '[contenteditable]:not([contenteditable="false"])',
34
+ ].join(', ');
35
+ // Thank you, Vojtech Miksu :)
36
+ // https://github.com/tajo/react-movable/blob/master/src/utils.ts
37
+ export function isOrResidesInInteractiveElement(target, root) {
38
+ while (target && target !== root) {
39
+ if (target.classList.contains('ssl-item-handle'))
40
+ return false;
41
+ const tagName = target.tagName.toLowerCase();
42
+ if (INTERACTIVE_ELEMENTS.has(tagName))
43
+ return true;
44
+ const role = target.getAttribute('role')?.toLowerCase();
45
+ if (role && INTERACTIVE_ROLES.has(role))
46
+ return true;
47
+ if (target.isContentEditable)
48
+ return true;
49
+ if (tagName === 'label' && target.hasAttribute('for'))
50
+ return true;
51
+ if (tagName)
52
+ target = target.parentElement;
53
+ }
54
+ return false;
55
+ }
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.3.0",
4
+ "version": "0.4.1",
5
5
  "author": "Rodrigo D’Agostino <rodrigo.dagostino@proton.me>",
6
6
  "keywords": [
7
7
  "draggable",
@@ -48,7 +48,8 @@
48
48
  }
49
49
  },
50
50
  "peerDependencies": {
51
- "svelte": "^5.0.0"
51
+ "svelte": "^5.0.0",
52
+ "esm-env": "^1.0.0"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@eslint/js": "10.0.1",