@reshaped/utilities 3.10.0-canary.4 → 3.10.0-canary.5

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.
package/README.md ADDED
@@ -0,0 +1,232 @@
1
+ # @reshaped/utilities
2
+
3
+ `@reshaped/utilities` is a standalone package that provides common utilities for building components and web applications with any framework. These utilities handle common patterns like focus management, scroll locking, DOM manipulation, and more.
4
+
5
+ Reshaped uses this package internally to power its component library, and you can use the same utilities in your own projects to build consistent, accessible experiences. In case you're using React, check `@reshaped/headless` instead as it covers more APIs and provides a better built-in integration with React.
6
+
7
+ ```
8
+ npm install @reshaped/utilities
9
+ ```
10
+
11
+ ## API overview
12
+
13
+ ### Flyout
14
+
15
+ ```ts
16
+ import { Flyout } from "@reshaped/utilities";
17
+
18
+ const flyout = new Flyout({
19
+ content: contentElement,
20
+ trigger: triggerElement,
21
+ position: "bottom-start",
22
+ });
23
+
24
+ // Position the flyout content based on the trigger element
25
+ flyout.activate();
26
+
27
+ // Clean-up the flyout behavior on closing the content
28
+ flyout.deactivate();
29
+
30
+ // Update flyout position based on updated options and the current viewport position
31
+ flyout.update(options);
32
+ ```
33
+
34
+ When you need to position floating elements like dropdowns, popovers, or tooltips, create a new Flyout instance and pass the content and trigger elements. The class handles complex positioning logic, collision detection, and automatic position adjustments to ensure your floating content is always visible and properly aligned.
35
+
36
+ Flyout support multiple options to tailor its behavior for your use case. These options can be pass when creating a flyout instance or when using the `update` method.
37
+
38
+ ```ts
39
+ export type Options = {
40
+ // Element that has to be positioned against the trigger. It has to be rendered at the moment of calling `new Flyout`
41
+ content: HTMLElement;
42
+
43
+ // Trigger element to position the content against
44
+ trigger?: HTMLElement | null;
45
+
46
+ // In case there is no trigger on the page, pass the x, y coordinates instead. This is useful for building components like context menus
47
+ triggerCoordinates?: { x: number; y: number } | null;
48
+
49
+ // Specify a container to position the content within instead of using the viewport boundaries
50
+ container?: HTMLElement | null;
51
+
52
+ // Default position to render the content, relative to the trigger
53
+ position:
54
+ | `top`
55
+ | `top-start`
56
+ | `top-end`
57
+ | `bottom`
58
+ | `bottom-start`
59
+ | `bottom-end`
60
+ | `start`
61
+ | `start-top`
62
+ | `start-bottom`
63
+ | `end`
64
+ | `end-top`
65
+ | `end-bottom`;
66
+
67
+ // Define which positions are used as fallbacks when default position doesn't fit into the viewport
68
+ // Passing an empty array would always keep the content in the same position
69
+ fallbackPositions?: Position[];
70
+
71
+ // Custom content width instead of using the width based on the content children
72
+ width?: Width;
73
+
74
+ // Try shifting and resizing the content if it doesn't fit into the viewport first instead of immediately changing the position
75
+ fallbackAdjustLayout?: boolean;
76
+
77
+ // Minimal height value for the content when using `fallbackAdjustLayout`
78
+ fallbackMinHeight?: string;
79
+
80
+ // Add an additional gap between the trigger and the content
81
+ contentGap?: number;
82
+ // Shift the content alongside the trigger
83
+ contentShift?: number;
84
+
85
+ // Handler for the cases when flyout deactivates itself internally based on the event handling
86
+ // For example, it might deactivate itself after scrolling the trigger outside the viewport
87
+ onDeactivate: () => void;
88
+ };
89
+ ```
90
+
91
+ ### TrapFocus
92
+
93
+ ```ts
94
+ import { TrapFocus } from "@reshaped/utilities";
95
+
96
+ class Modal {
97
+ trapFocus;
98
+
99
+ constructor() {
100
+ this.trapFocus = new TrapFocus();
101
+ }
102
+
103
+ open() {
104
+ this.trapFocus.trap(targetRef.current);
105
+ }
106
+
107
+ close() {
108
+ this.trapFocus.release();
109
+ }
110
+ }
111
+ ```
112
+
113
+ When `TrapFocus` is activated, it traps keyboard and screen reader navigation within the given element until focus is released. Since TrapFocus is a class, you can create a new instance and pass the target element to initialize it. This is useful when an element (like a modal or popup) appears on screen. When the element is dismissed, call the release method to restore normal focus behavior.
114
+
115
+ There are multiple options you can pass to the trapFocus methods to customize its behavior:
116
+
117
+ ```ts
118
+ trapFocus.trap(
119
+ // element to trap the focus within
120
+ rootElement,
121
+ {
122
+ // keep the focus on the trigger and include it in the focus sequence
123
+ includeTrigger: boolean,
124
+
125
+ // element to move to the focus to after the initialization
126
+ initialFocusEl: HTMLElement
127
+
128
+ // keyboard navigation mode
129
+ // `dialog` - handles Tab and Shift + Tab, looping focus within the element
130
+ // `action-menu` - allows focus navigation with the ArrowUp and ArrowDown keys. Pressing Tab moves focus to the next element after the original trigger and automatically releases the focus trap. You can use the `onRelease` option to dismiss the content when that happens.
131
+ // `action-bar` - works like `action-menu`, but uses the ArrowLeft and ArrowRight keys to move focus instead.
132
+ // `content-menu` - keeps the navigation flow natural by including all focusable elements in the trapped area after the trigger element.
133
+ // Focus navigation uses the Tab key, but pressing Tab on the last element moves focus to the next element after the original trigger.
134
+ // This releases the focus trap, and you can respond to it using the `onRelease` handler.
135
+ mode: 'dialog' | 'action-menu' | 'action-bar' | 'content-menu';
136
+
137
+ // callback to run when the focus trap is released internally
138
+ // for example, when Tab is pressed in the action-menu mode
139
+ onRelease?: () => void;
140
+ }
141
+ );
142
+
143
+ trapFocus.release({
144
+ // By default, releasing the focus trap returns focus to the original trigger element.
145
+ // Use the withoutFocusReturn option to disable this behavior.
146
+ // This is useful when closing the element with an outside click and you want to avoid the page scrolling back to the trigger.
147
+ withoutFocusReturn: boolean
148
+ })
149
+ ```
150
+
151
+ ### classNames
152
+
153
+ The `classNames` utility is a lightweight function for combining multiple class names into a single string. It's similar to the popular classnames library but is included directly in Reshaped, eliminating the need for an additional dependency.
154
+
155
+ Use this utility when building custom components that need to conditionally apply CSS classes based on props, state, or other conditions. It handles various input types including strings, booleans, null, and undefined values, making it easy to compose dynamic class names.
156
+
157
+ ```tsx
158
+ import { classNames } from "@reshaped/utilities";
159
+ import styles from "./Button.module.css";
160
+
161
+ const Button = ({ variant, disabled, className }) => {
162
+ const buttonClassNames = classNames(
163
+ styles.root,
164
+ variant && styles[`variant-${variant}`],
165
+ disabled && styles.disabled,
166
+ className
167
+ );
168
+
169
+ return <button className={buttonClassNames}>Click me</button>;
170
+ };
171
+ ```
172
+
173
+ You can also pass arrays of class names, which is useful when dealing with responsive class names or more complex scenarios:
174
+
175
+ ```tsx
176
+ const containerClassNames = classNames(
177
+ styles.container,
178
+ [responsive && styles.responsive, styles.flex],
179
+ padding && [styles.paddingTop, styles.paddingBottom]
180
+ );
181
+ ```
182
+
183
+ ### lockScroll
184
+
185
+ ```ts
186
+ import { lockScroll } from "@reshaped/utilities";
187
+
188
+ class Modal {
189
+ unlock;
190
+
191
+ constructor() {}
192
+
193
+ open() {
194
+ this.unlock = lockScroll();
195
+ }
196
+
197
+ close() {
198
+ this.unlock?.();
199
+ }
200
+ }
201
+ ```
202
+
203
+ By default, `lockScroll` will lock the scrolling of the document body and there are a few additional options you can pass to customize the behavior. Calling the returned `unlockScroll` function will unlock the scrolling based on the originally passed options.
204
+
205
+ `lockScroll` options:
206
+
207
+ ```ts
208
+ const unlock = lockScroll({
209
+ // lock the scrolling of a specific element
210
+ containerEl,
211
+ // specify an element that triggered the scroll lock
212
+ // specifying it will automatically find the closest scrollable parent to lock its scrolling instead of locking the whole document
213
+ originEl,
214
+ // callback triggered when the scroll gets locked
215
+ // in case it was already locked before when triggered, the callback won't run
216
+ callback,
217
+ });
218
+
219
+ unlock({
220
+ // callback triggered when the scroll gets unlocked
221
+ callback,
222
+ });
223
+ ```
224
+
225
+ ### isRTL
226
+
227
+ ```ts
228
+ import { isRTL } from "@reshaped/utilities";
229
+
230
+ // Call anywhere in your code
231
+ const rtl = isRTL();
232
+ ```
@@ -7,7 +7,7 @@ declare class Flyout {
7
7
  * Public methods
8
8
  */
9
9
  update: (options?: Partial<Options>) => ReturnType<typeof applyPosition>;
10
- open: () => ReturnType<typeof this.update>;
11
- close: () => void;
10
+ activate: () => ReturnType<typeof this.update>;
11
+ deactivate: () => void;
12
12
  }
13
13
  export default Flyout;
@@ -18,7 +18,7 @@ class Flyout {
18
18
  return result;
19
19
  };
20
20
  #addParentScrollHandler = () => {
21
- const { trigger, onClose } = this.#options;
21
+ const { trigger, onDeactivate } = this.#options;
22
22
  if (!trigger)
23
23
  return;
24
24
  const container = findClosestScrollableContainer({ el: trigger });
@@ -36,7 +36,7 @@ class Flyout {
36
36
  triggerBounds.left < containerBounds.left ||
37
37
  triggerBounds.right > containerBounds.right ||
38
38
  triggerBounds.bottom > containerBounds.bottom) {
39
- onClose();
39
+ onDeactivate();
40
40
  }
41
41
  else {
42
42
  this.#update();
@@ -86,7 +86,7 @@ class Flyout {
86
86
  this.#options = { ...this.#options, ...options };
87
87
  return this.#update();
88
88
  };
89
- open = () => {
89
+ activate = () => {
90
90
  const result = this.#update();
91
91
  this.#addParentScrollHandler();
92
92
  this.#addRTLHandler();
@@ -94,7 +94,7 @@ class Flyout {
94
94
  this.#active = true;
95
95
  return result;
96
96
  };
97
- close = () => {
97
+ deactivate = () => {
98
98
  this.#lastUsedPosition = null;
99
99
  this.#active = false;
100
100
  this.#removeHandlers();
@@ -31,9 +31,9 @@ describe("flyout/Flyout", () => {
31
31
  trigger,
32
32
  triggerCoordinates: null,
33
33
  position: "top",
34
- onClose,
34
+ onDeactivate: onClose,
35
35
  });
36
- const result = flyout.open();
36
+ const result = flyout.activate();
37
37
  expect(result.position).toBe("top");
38
38
  trigger.style.top = "0px";
39
39
  const resultUpdate = flyout.update();
@@ -53,9 +53,9 @@ describe("flyout/Flyout", () => {
53
53
  trigger,
54
54
  triggerCoordinates: null,
55
55
  position: "top",
56
- onClose,
56
+ onDeactivate: onClose,
57
57
  });
58
- flyout.open();
58
+ flyout.activate();
59
59
  // Scroll trigger out of bounds
60
60
  trigger.style.position = "absolute";
61
61
  trigger.style.top = "-100px";
@@ -88,9 +88,9 @@ describe("flyout/Flyout", () => {
88
88
  trigger,
89
89
  triggerCoordinates: null,
90
90
  position: "top",
91
- onClose,
91
+ onDeactivate: onClose,
92
92
  });
93
- flyout.open();
93
+ flyout.activate();
94
94
  // Scroll within bounds
95
95
  container.scrollTop = 50;
96
96
  container.dispatchEvent(new Event("scroll", { bubbles: true }));
@@ -111,9 +111,9 @@ describe("flyout/Flyout", () => {
111
111
  trigger,
112
112
  triggerCoordinates: null,
113
113
  position: "start",
114
- onClose,
114
+ onDeactivate: onClose,
115
115
  });
116
- const initialResult = flyout.open();
116
+ const initialResult = flyout.activate();
117
117
  expect(initialResult.position).toBe("start");
118
118
  // Start is positioned from the right side
119
119
  expect(content.style.right).toBe("0px");
@@ -19,6 +19,6 @@ export type Options = {
19
19
  fallbackMinHeight?: string;
20
20
  contentGap?: number;
21
21
  contentShift?: number;
22
- onClose: () => void;
22
+ onDeactivate: () => void;
23
23
  };
24
24
  export {};
@@ -31,7 +31,7 @@ describe("flyout/applyPosition", () => {
31
31
  triggerCoordinates: null,
32
32
  position: "top",
33
33
  lastUsedPosition: null,
34
- onClose: vi.fn(),
34
+ onDeactivate: vi.fn(),
35
35
  });
36
36
  expect(result.position).toBe("top");
37
37
  });
@@ -44,7 +44,7 @@ describe("flyout/applyPosition", () => {
44
44
  triggerCoordinates: null,
45
45
  position: "top",
46
46
  lastUsedPosition: null,
47
- onClose: vi.fn(),
47
+ onDeactivate: vi.fn(),
48
48
  });
49
49
  expect(result.position).toBe("bottom");
50
50
  });
@@ -58,7 +58,7 @@ describe("flyout/applyPosition", () => {
58
58
  triggerCoordinates,
59
59
  position: "top",
60
60
  lastUsedPosition: null,
61
- onClose: vi.fn(),
61
+ onDeactivate: vi.fn(),
62
62
  });
63
63
  expect(result.position).toBe("top");
64
64
  expect(content.style.transform).toBe(`translate(150px, ${250 - window.innerHeight}px)`);
@@ -70,7 +70,7 @@ describe("flyout/applyPosition", () => {
70
70
  triggerCoordinates: null,
71
71
  position: "top",
72
72
  lastUsedPosition: null,
73
- onClose: vi.fn(),
73
+ onDeactivate: vi.fn(),
74
74
  });
75
75
  }).toThrow("Trigger bounds are required");
76
76
  });
@@ -82,7 +82,7 @@ describe("flyout/applyPosition", () => {
82
82
  position: "top",
83
83
  width: "200px",
84
84
  lastUsedPosition: null,
85
- onClose: vi.fn(),
85
+ onDeactivate: vi.fn(),
86
86
  });
87
87
  expect(content.style.width).toBe("200px");
88
88
  });
@@ -94,7 +94,7 @@ describe("flyout/applyPosition", () => {
94
94
  position: "top",
95
95
  width: "trigger",
96
96
  lastUsedPosition: null,
97
- onClose: vi.fn(),
97
+ onDeactivate: vi.fn(),
98
98
  });
99
99
  expect(result.position).toBeTruthy();
100
100
  });
@@ -108,7 +108,7 @@ describe("flyout/applyPosition", () => {
108
108
  triggerCoordinates: null,
109
109
  position: "top",
110
110
  lastUsedPosition: null,
111
- onClose: vi.fn(),
111
+ onDeactivate: vi.fn(),
112
112
  });
113
113
  // Should try full-width positions
114
114
  expect(result.position).toBeTruthy();
@@ -123,7 +123,7 @@ describe("flyout/applyPosition", () => {
123
123
  position: "top",
124
124
  fallbackPositions: ["start"],
125
125
  lastUsedPosition: null,
126
- onClose: vi.fn(),
126
+ onDeactivate: vi.fn(),
127
127
  });
128
128
  expect(result.position).toBe("start");
129
129
  });
@@ -135,7 +135,7 @@ describe("flyout/applyPosition", () => {
135
135
  triggerCoordinates: null,
136
136
  position: "top",
137
137
  lastUsedPosition: null,
138
- onClose: vi.fn(),
138
+ onDeactivate: vi.fn(),
139
139
  });
140
140
  // Clone should be removed
141
141
  expect(document.body.children.length).toBe(initialChildCount);
@@ -1,4 +1,4 @@
1
- export declare const lockScroll: (args: {
1
+ export declare const lockScroll: (args?: {
2
2
  containerEl?: HTMLElement | null;
3
3
  originEl?: HTMLElement | null;
4
4
  callback?: () => void;
@@ -5,8 +5,8 @@ import lockStandardScroll from "./lockStandard.js";
5
5
  export const lockScroll = (args) => {
6
6
  const isIOSLock = isIOS();
7
7
  let reset = () => { };
8
- const container = args.containerEl ??
9
- (args.originEl && findClosestScrollableContainer({ el: args.originEl })) ??
8
+ const container = args?.containerEl ??
9
+ (args?.originEl && findClosestScrollableContainer({ el: args.originEl })) ??
10
10
  document.body;
11
11
  const lockedBodyScroll = container === document.body;
12
12
  // Already locked so no need to lock again and trigger the callback
@@ -18,7 +18,7 @@ export const lockScroll = (args) => {
18
18
  else {
19
19
  reset = lockStandardScroll({ container });
20
20
  }
21
- args.callback?.();
21
+ args?.callback?.();
22
22
  return (args) => {
23
23
  reset();
24
24
  args?.callback?.();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@reshaped/utilities",
3
3
  "description": "Vanilla JS utilities for implementing common UI patterns",
4
- "version": "3.10.0-canary.4",
4
+ "version": "3.10.0-canary.5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://reshaped.so",
7
7
  "repository": {