@open-pioneer/react-utils 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @open-pioneer/react-utils
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 182da1c: Initial release.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @open-pioneer/react-utils
2
+
3
+ This package provides React utilities that help a developer create applications.
4
+
5
+ ## Titled sections
6
+
7
+ Use the `<TitledSection>` and `<SectionHeading>` components instead of raw `hX` HTML tags (such as `<h1>` or `<h2>`).
8
+ This way, the appropriate heading level is determined automatically.
9
+
10
+ Example:
11
+
12
+ ```jsx
13
+ import { TitledSection, SectionHeading } from "@open-pioneer/react-utils";
14
+
15
+ function SomeComponent(props) {
16
+ return (
17
+ {/* Renders as h1 if this is the topmost section.
18
+ Title strings are automatically wrapped into `SectionHeading`. */}
19
+ <TitledSection title="Root Title">
20
+ ... Some content ...
21
+ {/* Custom react component as title. Renders as the next level (h2). */}
22
+ <TitledSection title={<SectionHeading size="4xl">Sub Title</SectionHeading>}>
23
+ ... More content ...
24
+ </TitledSection>
25
+ </TitledSection>
26
+ );
27
+ }
28
+ ```
29
+
30
+ To override the automatic heading level, use the `ConfigureTitledSection` component.
31
+ This can be used for example to override the initial heading level or to force a certain level when the React tree differs from the DOM tree.
32
+
33
+ Example:
34
+
35
+ ```jsx
36
+ <ConfigureTitledSection level={2}>
37
+ <TheRestOfYourApplication />
38
+ </ConfigureTitledSection>
39
+ ```
40
+
41
+ In the preceding example the topmost heading(s) in `TheRestOfYourApplication` start at level 2, and nested headings use increasing levels as usual.
42
+ For more details, see the API documentation.
43
+
44
+ ## Tool buttons
45
+
46
+ To create a simple icon button with a tooltip and an `aria-label`, use the `ToolButton` component as in the following sample:
47
+
48
+ ```jsx
49
+ <ToolButton label={someLabel} icon={<SomeIcon />} onClick={someEventHandler} />
50
+ ```
51
+
52
+ This is used, for example, to add an icon button to the map.
53
+
54
+ ## Hooks
55
+
56
+ ### useCommonComponentProps()
57
+
58
+ A helper hook that automatically computes `containerProps`: common properties to set on the topmost container element of a public component.
59
+
60
+ For the time being, these properties are `className` (combined component class and optional additional class names) and `data-testid` (for tests).
61
+
62
+ Example:
63
+
64
+ ```tsx
65
+ // SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)
66
+ // SPDX-License-Identifier: Apache-2.0
67
+ import { CommonComponentProps, useCommonComponentProps } from "@open-pioneer/react-utils";
68
+ // ...
69
+
70
+ // Inherit from CommonComponentProps
71
+ export interface InitialExtentProps extends CommonComponentProps {
72
+ mapId: string;
73
+ }
74
+
75
+ export const InitialExtent: FC<InitialExtentProps> = forwardRef(function InitialExtent(
76
+ props: InitialExtentProps,
77
+ ref: ForwardedRef<HTMLDivElement>
78
+ ) {
79
+ const { mapId } = props;
80
+
81
+ // Use the hook to compute container props (classNames, data-testid, maybe more in the future)
82
+ const { containerProps } = useCommonComponentProps("initial-extent", props);
83
+
84
+ // Pass containerProps directly to the container
85
+ return <Box {...containerProps}>{/* ... */}</Box>;
86
+ });
87
+ ```
88
+
89
+ ### useEvent()
90
+
91
+ The `useEvent` can be used to obtain a stable event handler function with changing implementation.
92
+ This is useful to avoid re-triggering `useEffect`-hooks when only the event handler changed.
93
+
94
+ Example:
95
+
96
+ ```jsx
97
+ import { useEvent } from "@open-pioneer/react-utils";
98
+
99
+ function someReactComponent(props) {
100
+ // NOTE: logMessage() must not be called during rendering!
101
+ const logMessage = useEvent((message: string) => {
102
+ console.log(message, props.someProperty);
103
+ });
104
+ const someService = ...; // injected
105
+
106
+ // Changes of prop.someProperty will not cause the effect to re-fire, because the function identity
107
+ // of `logMessage` remains stable.
108
+ useEffect(() => {
109
+ const handle = someService.registerHandler(logMessage);
110
+ return () => handle.destroy();
111
+ }, [someService, logMessage]);
112
+ }
113
+ ```
114
+
115
+ For more details, see the API docs of `useEvent` or <https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md>.
116
+
117
+ ## License
118
+
119
+ Apache-2.0 (see `LICENSE` file)
@@ -0,0 +1,126 @@
1
+ import { HeadingProps } from "@open-pioneer/chakra-integration";
2
+ import { FC, ReactNode } from "react";
3
+ /** Properties of the {@link TitledSection} component. */
4
+ export interface TitledSectionProps {
5
+ /**
6
+ * The title component.
7
+ *
8
+ * Strings are automatically wrapped in a {@link SectionHeading}.
9
+ * More complex nodes should use the {@link SectionHeading} internally.
10
+ */
11
+ title?: string | ReactNode | undefined;
12
+ /**
13
+ * Children are rendered without any modifications.
14
+ */
15
+ children?: ReactNode | undefined;
16
+ /**
17
+ * Allows to substitute the heading level that is used up from this section.
18
+ * This should only be used to configure the initial level
19
+ * or if it is actually intended to adjust the DOM structure.
20
+ */
21
+ substituteHeadingLevel?: HeadingLevel | undefined;
22
+ }
23
+ /**
24
+ * Automatically manages the level of html headings such as `h1` and `h2`.
25
+ *
26
+ * Use this component's `title` property instead of manual heading tags.
27
+ * Nested sections will automatically use the correct level for their current location.
28
+ *
29
+ * Titles are rendered as [Chakra Headings](https://chakra-ui.com/docs/components/heading) by default.
30
+ *
31
+ * Example: Simple string headings (1, 2 and 3 will be rendered as h1, h2 and h3):
32
+ *
33
+ * ```jsx
34
+ * <TitledSection title="1">
35
+ * Top level content
36
+ *
37
+ * <TitledSection title="2">
38
+ * Nested content
39
+ *
40
+ * <TitledSection title="3">
41
+ * Deeply nested content
42
+ * </TitledSection>
43
+ * </TitledSection>
44
+ * </TitledSection>
45
+ * ```
46
+ *
47
+ * Example: custom title rendering
48
+ *
49
+ * ```jsx
50
+ * <TitledSection
51
+ * title={
52
+ * <SectionHeading size="4xl">Heading</SectionHeading>
53
+ * }
54
+ * >
55
+ * Content
56
+ * </TitledSection>
57
+ * ```
58
+ */
59
+ export declare function TitledSection(props: TitledSectionProps): JSX.Element;
60
+ /**
61
+ * Properties supported by the {@link SectionHeading} component.
62
+ *
63
+ * All chakra properties are forwarded to the [Heading](https://chakra-ui.com/docs/components/heading) component.
64
+ */
65
+ export interface SectionHeadingProps extends HeadingProps {
66
+ children?: ReactNode | undefined;
67
+ }
68
+ /**
69
+ * Renders an appropriate heading tag for the current heading level (`h1` through `h6`).
70
+ * This component should only be used as part of the `title` prop of the {@link TitledSection}.
71
+ *
72
+ * Headings are rendered as [Chakra Headings](https://chakra-ui.com/docs/components/heading).
73
+ *
74
+ * Heading levels are managed by nesting {@link TitledSection}.
75
+ */
76
+ export declare const SectionHeading: import("react").ForwardRefExoticComponent<SectionHeadingProps & import("react").RefAttributes<HTMLHeadingElement>>;
77
+ /**
78
+ * Properties for the {@link ConfigureTitledSection} component.
79
+ */
80
+ export interface ConfigureTitledSectionProps {
81
+ level: HeadingLevel;
82
+ children?: ReactNode;
83
+ }
84
+ /**
85
+ * Overrides the heading level for all children.
86
+ *
87
+ * TitledSection components nested in `children` will start with the configured level.
88
+ * Nested TitledSections will continue to use the next appropriate heading level.
89
+ *
90
+ * Example: Changing the global heading level for your application
91
+ *
92
+ * If your application is embedded into another site, it should often not use the `h1` tag
93
+ * but start with a higher heading level instead. To achieve that, simply wrap your application
94
+ * with `<ConfigureTitledSectionProps>`. No other code changes are necessary:
95
+ *
96
+ * ```jsx
97
+ * <ConfigureTitledSection level={2}>
98
+ * <TheRestOfYourApplication />
99
+ * </ConfigureTitledSection>
100
+ * ```
101
+ *
102
+ * Example: Embedding a widget
103
+ *
104
+ * Given a `<Widget />` (that we cannot easily change) that internally uses `TitledSection`,
105
+ * this is how we can embed it with a custom heading level.
106
+ * This can be appropriate in some circumstances, for example when the react component tree does not match the DOM
107
+ * tree (portals etc.).
108
+ *
109
+ * ```jsx
110
+ * <ConfigureTitledSection level={5}>
111
+ * <Widget />
112
+ * </ConfigureTitledSection>
113
+ * ```
114
+ *
115
+ * The headings used by `Widget` will start with `h5`.
116
+ *
117
+ */
118
+ export declare const ConfigureTitledSection: FC<ConfigureTitledSectionProps>;
119
+ /** The level of a html heading. */
120
+ export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
121
+ /**
122
+ * Returns the current heading level.
123
+ *
124
+ * This hook should be used in the `title` property of a {@link TitledSection}.
125
+ */
126
+ export declare function useHeadingLevel(): HeadingLevel;
@@ -0,0 +1,35 @@
1
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
+ import { Heading } from '@open-pioneer/chakra-integration';
3
+ import { createContext, forwardRef, useContext } from 'react';
4
+
5
+ const DEFAULT_LEVEL = 1;
6
+ const LevelContext = createContext(DEFAULT_LEVEL);
7
+ LevelContext.displayName = "LevelContext";
8
+ function TitledSection(props) {
9
+ const { title, children } = props;
10
+ const currentLevel = useContext(LevelContext);
11
+ const heading = typeof title === "string" ? /* @__PURE__ */ jsx(SectionHeading, { children: title }) : title;
12
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
13
+ heading,
14
+ /* @__PURE__ */ jsx(LevelContext.Provider, { value: currentLevel + 1, children })
15
+ ] });
16
+ }
17
+ const SectionHeading = forwardRef(function SectionHeading2(props, forwardedRef) {
18
+ const { children, ...rest } = props;
19
+ const level = useHeadingLevel();
20
+ const tag = getHeadingTag(level);
21
+ return /* @__PURE__ */ jsx(Heading, { as: tag, ref: forwardedRef, ...rest, children });
22
+ });
23
+ const ConfigureTitledSection = (props) => {
24
+ return /* @__PURE__ */ jsx(LevelContext.Provider, { value: props.level, children: props.children });
25
+ };
26
+ function useHeadingLevel() {
27
+ const level = useContext(LevelContext);
28
+ return Math.min(level, 6);
29
+ }
30
+ function getHeadingTag(level) {
31
+ return `h${level}`;
32
+ }
33
+
34
+ export { ConfigureTitledSection, SectionHeading, TitledSection, useHeadingLevel };
35
+ //# sourceMappingURL=TitledSection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TitledSection.js","sources":["TitledSection.tsx"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { Heading, HeadingProps } from \"@open-pioneer/chakra-integration\";\nimport { FC, ForwardedRef, ReactNode, createContext, forwardRef, useContext } from \"react\";\n\nconst DEFAULT_LEVEL = 1;\n\nconst LevelContext = createContext(DEFAULT_LEVEL);\nLevelContext.displayName = \"LevelContext\";\n\n/** Properties of the {@link TitledSection} component. */\nexport interface TitledSectionProps {\n /**\n * The title component.\n *\n * Strings are automatically wrapped in a {@link SectionHeading}.\n * More complex nodes should use the {@link SectionHeading} internally.\n */\n title?: string | ReactNode | undefined;\n\n /**\n * Children are rendered without any modifications.\n */\n children?: ReactNode | undefined;\n\n /**\n * Allows to substitute the heading level that is used up from this section.\n * This should only be used to configure the initial level\n * or if it is actually intended to adjust the DOM structure.\n */\n substituteHeadingLevel?: HeadingLevel | undefined;\n}\n\n/**\n * Automatically manages the level of html headings such as `h1` and `h2`.\n *\n * Use this component's `title` property instead of manual heading tags.\n * Nested sections will automatically use the correct level for their current location.\n *\n * Titles are rendered as [Chakra Headings](https://chakra-ui.com/docs/components/heading) by default.\n *\n * Example: Simple string headings (1, 2 and 3 will be rendered as h1, h2 and h3):\n *\n * ```jsx\n * <TitledSection title=\"1\">\n * Top level content\n *\n * <TitledSection title=\"2\">\n * Nested content\n *\n * <TitledSection title=\"3\">\n * Deeply nested content\n * </TitledSection>\n * </TitledSection>\n * </TitledSection>\n * ```\n *\n * Example: custom title rendering\n *\n * ```jsx\n * <TitledSection\n * title={\n * <SectionHeading size=\"4xl\">Heading</SectionHeading>\n * }\n * >\n * Content\n * </TitledSection>\n * ```\n */\nexport function TitledSection(props: TitledSectionProps): JSX.Element {\n const { title, children } = props;\n const currentLevel = useContext(LevelContext);\n const heading = typeof title === \"string\" ? <SectionHeading>{title}</SectionHeading> : title;\n\n return (\n <>\n {heading}\n <LevelContext.Provider value={currentLevel + 1}>{children}</LevelContext.Provider>\n </>\n );\n}\n\n/**\n * Properties supported by the {@link SectionHeading} component.\n *\n * All chakra properties are forwarded to the [Heading](https://chakra-ui.com/docs/components/heading) component.\n */\nexport interface SectionHeadingProps extends HeadingProps {\n children?: ReactNode | undefined;\n}\n\n/**\n * Renders an appropriate heading tag for the current heading level (`h1` through `h6`).\n * This component should only be used as part of the `title` prop of the {@link TitledSection}.\n *\n * Headings are rendered as [Chakra Headings](https://chakra-ui.com/docs/components/heading).\n *\n * Heading levels are managed by nesting {@link TitledSection}.\n */\nexport const SectionHeading = forwardRef(function SectionHeading(\n props: SectionHeadingProps,\n forwardedRef: ForwardedRef<HTMLHeadingElement>\n): JSX.Element {\n const { children, ...rest } = props;\n const level = useHeadingLevel();\n const tag = getHeadingTag(level);\n return (\n <Heading as={tag} ref={forwardedRef} {...rest}>\n {children}\n </Heading>\n );\n});\n\n/**\n * Properties for the {@link ConfigureTitledSection} component.\n */\nexport interface ConfigureTitledSectionProps {\n level: HeadingLevel;\n children?: ReactNode;\n}\n\n/**\n * Overrides the heading level for all children.\n *\n * TitledSection components nested in `children` will start with the configured level.\n * Nested TitledSections will continue to use the next appropriate heading level.\n *\n * Example: Changing the global heading level for your application\n *\n * If your application is embedded into another site, it should often not use the `h1` tag\n * but start with a higher heading level instead. To achieve that, simply wrap your application\n * with `<ConfigureTitledSectionProps>`. No other code changes are necessary:\n *\n * ```jsx\n * <ConfigureTitledSection level={2}>\n * <TheRestOfYourApplication />\n * </ConfigureTitledSection>\n * ```\n *\n * Example: Embedding a widget\n *\n * Given a `<Widget />` (that we cannot easily change) that internally uses `TitledSection`,\n * this is how we can embed it with a custom heading level.\n * This can be appropriate in some circumstances, for example when the react component tree does not match the DOM\n * tree (portals etc.).\n *\n * ```jsx\n * <ConfigureTitledSection level={5}>\n * <Widget />\n * </ConfigureTitledSection>\n * ```\n *\n * The headings used by `Widget` will start with `h5`.\n *\n */\nexport const ConfigureTitledSection: FC<ConfigureTitledSectionProps> = (props) => {\n return <LevelContext.Provider value={props.level}>{props.children}</LevelContext.Provider>;\n};\n\n/** The level of a html heading. */\nexport type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;\n\n/**\n * Returns the current heading level.\n *\n * This hook should be used in the `title` property of a {@link TitledSection}.\n */\nexport function useHeadingLevel(): HeadingLevel {\n const level = useContext(LevelContext);\n return Math.min(level, 6) as HeadingLevel;\n}\n\nfunction getHeadingTag(level: HeadingLevel): `h${HeadingLevel}` {\n return `h${level}`;\n}\n"],"names":["SectionHeading"],"mappings":";;;;AAKA,MAAM,aAAgB,GAAA,CAAA,CAAA;AAEtB,MAAM,YAAA,GAAe,cAAc,aAAa,CAAA,CAAA;AAChD,YAAA,CAAa,WAAc,GAAA,cAAA,CAAA;AA6DpB,SAAS,cAAc,KAAwC,EAAA;AAClE,EAAM,MAAA,EAAE,KAAO,EAAA,QAAA,EAAa,GAAA,KAAA,CAAA;AAC5B,EAAM,MAAA,YAAA,GAAe,WAAW,YAAY,CAAA,CAAA;AAC5C,EAAA,MAAM,UAAU,OAAO,KAAA,KAAU,2BAAY,GAAA,CAAA,cAAA,EAAA,EAAgB,iBAAM,CAAoB,GAAA,KAAA,CAAA;AAEvF,EAAA,uBAES,IAAA,CAAA,QAAA,EAAA,EAAA,QAAA,EAAA;AAAA,IAAA,OAAA;AAAA,wBACA,YAAa,CAAA,QAAA,EAAb,EAAsB,KAAO,EAAA,YAAA,GAAe,GAAI,QAAS,EAAA,CAAA;AAAA,GAC9D,EAAA,CAAA,CAAA;AAER,CAAA;AAmBO,MAAM,cAAiB,GAAA,UAAA,CAAW,SAASA,eAAAA,CAC9C,OACA,YACW,EAAA;AACX,EAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAS,GAAA,KAAA,CAAA;AAC9B,EAAA,MAAM,QAAQ,eAAgB,EAAA,CAAA;AAC9B,EAAM,MAAA,GAAA,GAAM,cAAc,KAAK,CAAA,CAAA;AAC/B,EACI,uBAAA,GAAA,CAAC,WAAQ,EAAI,EAAA,GAAA,EAAK,KAAK,YAAe,EAAA,GAAG,MACpC,QACL,EAAA,CAAA,CAAA;AAER,CAAC,EAAA;AA4CY,MAAA,sBAAA,GAA0D,CAAC,KAAU,KAAA;AAC9E,EAAO,uBAAA,GAAA,CAAC,aAAa,QAAb,EAAA,EAAsB,OAAO,KAAM,CAAA,KAAA,EAAQ,gBAAM,QAAS,EAAA,CAAA,CAAA;AACtE,EAAA;AAUO,SAAS,eAAgC,GAAA;AAC5C,EAAM,MAAA,KAAA,GAAQ,WAAW,YAAY,CAAA,CAAA;AACrC,EAAO,OAAA,IAAA,CAAK,GAAI,CAAA,KAAA,EAAO,CAAC,CAAA,CAAA;AAC5B,CAAA;AAEA,SAAS,cAAc,KAAyC,EAAA;AAC5D,EAAA,OAAO,IAAI,KAAK,CAAA,CAAA,CAAA;AACpB;;;;"}
@@ -0,0 +1,54 @@
1
+ import { ButtonProps, TooltipProps } from "@open-pioneer/chakra-integration";
2
+ import { FC, MouseEventHandler, ReactElement, RefAttributes } from "react";
3
+ import { CommonComponentProps } from "./useCommonComponentProps";
4
+ /**
5
+ * Properties supported by {@link ToolButton}.
6
+ */
7
+ export interface ToolButtonProps extends CommonComponentProps, RefAttributes<HTMLButtonElement> {
8
+ /**
9
+ * The label for the ToolButton.
10
+ * This value services as the tooltip text and the aria-label.
11
+ *
12
+ * This property is required for a11y reasons because a ToolButton usually only displays an icon.
13
+ */
14
+ label: string;
15
+ /**
16
+ * The icon displayed by the button.
17
+ */
18
+ icon: ReactElement;
19
+ /**
20
+ * If `true`, the button will show a spinner.
21
+ * Defaults to `false`.
22
+ */
23
+ isLoading?: boolean;
24
+ /**
25
+ * If `true`, indicates that the button is currently active with a different style.
26
+ * Defaults to `false`.
27
+ */
28
+ isActive?: boolean;
29
+ /**
30
+ * If `true`, the button will be disabled.
31
+ * Defaults to `false`.
32
+ */
33
+ isDisabled?: boolean;
34
+ /**
35
+ * The callback that will be called when the user clicks the button.
36
+ */
37
+ onClick?: MouseEventHandler<HTMLButtonElement> | undefined;
38
+ /**
39
+ * Additional properties for the `Tooltip` element.
40
+ *
41
+ * Note that the ToolButton also defines some of these props.
42
+ */
43
+ tooltipProps?: Partial<TooltipProps>;
44
+ /**
45
+ * Additional properties for the `Button` element.
46
+ *
47
+ * Note that the ToolButton also defines some of these props.
48
+ */
49
+ buttonProps?: Partial<ButtonProps>;
50
+ }
51
+ /**
52
+ * An button with a tooltip, used for tool buttons on a map.
53
+ */
54
+ export declare const ToolButton: FC<ToolButtonProps>;
package/ToolButton.js ADDED
@@ -0,0 +1,67 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { Tooltip, Button } from '@open-pioneer/chakra-integration';
3
+ import { forwardRef, useState } from 'react';
4
+ import { useCommonComponentProps } from './useCommonComponentProps.js';
5
+ import classNames from 'classnames';
6
+
7
+ const ToolButton = forwardRef(function ToolButton2(props, ref) {
8
+ const {
9
+ label,
10
+ icon,
11
+ onClick: onClickProp,
12
+ isLoading,
13
+ isDisabled,
14
+ isActive,
15
+ tooltipProps,
16
+ buttonProps
17
+ } = props;
18
+ const {
19
+ containerProps: { className: baseClassName, ...containerProps }
20
+ } = useCommonComponentProps("tool-button", props);
21
+ const className = classNames(baseClassName, {
22
+ "tool-button--active": isActive,
23
+ "tool-button--loading": isLoading,
24
+ "tool-button--disabled": isDisabled
25
+ });
26
+ const [tooltipOpen, setTooltipOpen] = useState(false);
27
+ const onClick = (e) => {
28
+ setTooltipOpen(false);
29
+ onClickProp?.(e);
30
+ };
31
+ return /* @__PURE__ */ jsx(
32
+ Tooltip,
33
+ {
34
+ label,
35
+ placement: "auto",
36
+ openDelay: 500,
37
+ ...tooltipProps,
38
+ isOpen: tooltipOpen,
39
+ onOpen: () => setTooltipOpen(true),
40
+ onClose: () => setTooltipOpen(false),
41
+ children: /* @__PURE__ */ jsx(
42
+ ButtonIgnoringAriaProps,
43
+ {
44
+ className,
45
+ ref,
46
+ "aria-label": label,
47
+ leftIcon: icon,
48
+ iconSpacing: 0,
49
+ padding: 0,
50
+ isDisabled,
51
+ isLoading,
52
+ isActive,
53
+ ...containerProps,
54
+ ...buttonProps,
55
+ onClick
56
+ }
57
+ )
58
+ }
59
+ );
60
+ });
61
+ const ButtonIgnoringAriaProps = forwardRef(function ButtonIgnoringAriaProps2(props, ref) {
62
+ const { "aria-labelledby": _label, "aria-describedby": _describedBy, ...rest } = props;
63
+ return /* @__PURE__ */ jsx(Button, { ref, ...rest });
64
+ });
65
+
66
+ export { ToolButton };
67
+ //# sourceMappingURL=ToolButton.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ToolButton.js","sources":["ToolButton.tsx"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, ButtonProps, Tooltip, TooltipProps } from \"@open-pioneer/chakra-integration\";\nimport {\n FC,\n MouseEvent,\n MouseEventHandler,\n ReactElement,\n RefAttributes,\n forwardRef,\n useState\n} from \"react\";\nimport { CommonComponentProps, useCommonComponentProps } from \"./useCommonComponentProps\";\nimport classNames from \"classnames\";\n\n/**\n * Properties supported by {@link ToolButton}.\n */\nexport interface ToolButtonProps extends CommonComponentProps, RefAttributes<HTMLButtonElement> {\n /**\n * The label for the ToolButton.\n * This value services as the tooltip text and the aria-label.\n *\n * This property is required for a11y reasons because a ToolButton usually only displays an icon.\n */\n label: string;\n\n /**\n * The icon displayed by the button.\n */\n icon: ReactElement;\n\n /**\n * If `true`, the button will show a spinner.\n * Defaults to `false`.\n */\n isLoading?: boolean;\n\n /**\n * If `true`, indicates that the button is currently active with a different style.\n * Defaults to `false`.\n */\n isActive?: boolean;\n\n /**\n * If `true`, the button will be disabled.\n * Defaults to `false`.\n */\n isDisabled?: boolean;\n\n /**\n * The callback that will be called when the user clicks the button.\n */\n onClick?: MouseEventHandler<HTMLButtonElement> | undefined;\n\n /**\n * Additional properties for the `Tooltip` element.\n *\n * Note that the ToolButton also defines some of these props.\n */\n tooltipProps?: Partial<TooltipProps>;\n\n /**\n * Additional properties for the `Button` element.\n *\n * Note that the ToolButton also defines some of these props.\n */\n buttonProps?: Partial<ButtonProps>;\n}\n\n/**\n * An button with a tooltip, used for tool buttons on a map.\n */\nexport const ToolButton: FC<ToolButtonProps> = forwardRef(function ToolButton(\n props: ToolButtonProps,\n ref\n) {\n const {\n label,\n icon,\n onClick: onClickProp,\n isLoading,\n isDisabled,\n isActive,\n tooltipProps,\n buttonProps\n } = props;\n\n const {\n containerProps: { className: baseClassName, ...containerProps }\n } = useCommonComponentProps(\"tool-button\", props);\n\n const className = classNames(baseClassName, {\n \"tool-button--active\": isActive,\n \"tool-button--loading\": isLoading,\n \"tool-button--disabled\": isDisabled\n });\n\n const [tooltipOpen, setTooltipOpen] = useState(false);\n const onClick = (e: MouseEvent<HTMLButtonElement>) => {\n // Immediately hide the tooltip. When the label switches in reaction to the click,\n // the tooltip would flicker briefly with the new label.\n setTooltipOpen(false);\n onClickProp?.(e);\n };\n\n return (\n <Tooltip\n label={label}\n placement=\"auto\"\n openDelay={500}\n {...tooltipProps}\n /* don't allow overwrite because component would break */\n isOpen={tooltipOpen}\n onOpen={() => setTooltipOpen(true)}\n onClose={() => setTooltipOpen(false)}\n >\n <ButtonIgnoringAriaProps\n className={className}\n ref={ref}\n aria-label={label}\n leftIcon={icon}\n iconSpacing={0}\n padding={0}\n isDisabled={isDisabled}\n isLoading={isLoading}\n isActive={isActive}\n {...containerProps}\n {...buttonProps}\n /* don't allow overwrite because component would break */\n onClick={onClick}\n />\n </Tooltip>\n );\n});\n\n/**\n * The tooltip will automatically set 'aria-describedby' when it is being shown.\n * This is redundant because the aria-label already has the same content as the tooltip.\n * This component wraps chakra's button to ignore the *-by attributes.\n */\nconst ButtonIgnoringAriaProps = forwardRef(function ButtonIgnoringAriaProps(\n props: ButtonProps,\n ref: React.ForwardedRef<HTMLButtonElement>\n) {\n const { \"aria-labelledby\": _label, \"aria-describedby\": _describedBy, ...rest } = props;\n return <Button ref={ref} {...rest} />;\n});\n"],"names":["ToolButton","ButtonIgnoringAriaProps"],"mappings":";;;;;;AAyEO,MAAM,UAAkC,GAAA,UAAA,CAAW,SAASA,WAAAA,CAC/D,OACA,GACF,EAAA;AACE,EAAM,MAAA;AAAA,IACF,KAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAS,EAAA,WAAA;AAAA,IACT,SAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAA;AAAA,IACA,YAAA;AAAA,IACA,WAAA;AAAA,GACA,GAAA,KAAA,CAAA;AAEJ,EAAM,MAAA;AAAA,IACF,cAAgB,EAAA,EAAE,SAAW,EAAA,aAAA,EAAe,GAAG,cAAe,EAAA;AAAA,GAClE,GAAI,uBAAwB,CAAA,aAAA,EAAe,KAAK,CAAA,CAAA;AAEhD,EAAM,MAAA,SAAA,GAAY,WAAW,aAAe,EAAA;AAAA,IACxC,qBAAuB,EAAA,QAAA;AAAA,IACvB,sBAAwB,EAAA,SAAA;AAAA,IACxB,uBAAyB,EAAA,UAAA;AAAA,GAC5B,CAAA,CAAA;AAED,EAAA,MAAM,CAAC,WAAA,EAAa,cAAc,CAAA,GAAI,SAAS,KAAK,CAAA,CAAA;AACpD,EAAM,MAAA,OAAA,GAAU,CAAC,CAAqC,KAAA;AAGlD,IAAA,cAAA,CAAe,KAAK,CAAA,CAAA;AACpB,IAAA,WAAA,GAAc,CAAC,CAAA,CAAA;AAAA,GACnB,CAAA;AAEA,EACI,uBAAA,GAAA;AAAA,IAAC,OAAA;AAAA,IAAA;AAAA,MACG,KAAA;AAAA,MACA,SAAU,EAAA,MAAA;AAAA,MACV,SAAW,EAAA,GAAA;AAAA,MACV,GAAG,YAAA;AAAA,MAEJ,MAAQ,EAAA,WAAA;AAAA,MACR,MAAA,EAAQ,MAAM,cAAA,CAAe,IAAI,CAAA;AAAA,MACjC,OAAA,EAAS,MAAM,cAAA,CAAe,KAAK,CAAA;AAAA,MAEnC,QAAA,kBAAA,GAAA;AAAA,QAAC,uBAAA;AAAA,QAAA;AAAA,UACG,SAAA;AAAA,UACA,GAAA;AAAA,UACA,YAAY,EAAA,KAAA;AAAA,UACZ,QAAU,EAAA,IAAA;AAAA,UACV,WAAa,EAAA,CAAA;AAAA,UACb,OAAS,EAAA,CAAA;AAAA,UACT,UAAA;AAAA,UACA,SAAA;AAAA,UACA,QAAA;AAAA,UACC,GAAG,cAAA;AAAA,UACH,GAAG,WAAA;AAAA,UAEJ,OAAA;AAAA,SAAA;AAAA,OACJ;AAAA,KAAA;AAAA,GACJ,CAAA;AAER,CAAC,EAAA;AAOD,MAAM,uBAA0B,GAAA,UAAA,CAAW,SAASC,wBAAAA,CAChD,OACA,GACF,EAAA;AACE,EAAA,MAAM,EAAE,iBAAmB,EAAA,MAAA,EAAQ,oBAAoB,YAAc,EAAA,GAAG,MAAS,GAAA,KAAA,CAAA;AACjF,EAAA,uBAAQ,GAAA,CAAA,MAAA,EAAA,EAAO,GAAW,EAAA,GAAG,IAAM,EAAA,CAAA,CAAA;AACvC,CAAC,CAAA;;;;"}
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { useEvent } from "./useEvent";
2
+ export { type TitledSectionProps, TitledSection, type SectionHeadingProps, SectionHeading, type ConfigureTitledSectionProps, ConfigureTitledSection, type HeadingLevel, useHeadingLevel } from "./TitledSection";
3
+ export { type ToolButtonProps, ToolButton } from "./ToolButton";
4
+ export { type CommonComponentProps, useCommonComponentProps } from "./useCommonComponentProps";
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { useEvent } from './useEvent.js';
2
+ export { ConfigureTitledSection, SectionHeading, TitledSection, useHeadingLevel } from './TitledSection.js';
3
+ export { ToolButton } from './ToolButton.js';
4
+ export { useCommonComponentProps } from './useCommonComponentProps.js';
5
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@open-pioneer/react-utils",
4
+ "version": "0.1.0",
5
+ "description": "Contains common react utilities used by the open pioneer trails project",
6
+ "license": "Apache-2.0",
7
+ "peerDependencies": {
8
+ "react": "^18.2.0",
9
+ "@open-pioneer/core": "^1.1.0",
10
+ "@open-pioneer/chakra-integration": "^1.1.0",
11
+ "classnames": "^2.3.2"
12
+ },
13
+ "exports": {
14
+ "./package.json": "./package.json",
15
+ ".": {
16
+ "import": "./index.js",
17
+ "types": "./index.d.ts"
18
+ }
19
+ },
20
+ "openPioneerFramework": {
21
+ "services": [],
22
+ "i18n": {
23
+ "languages": []
24
+ },
25
+ "ui": {
26
+ "references": []
27
+ },
28
+ "properties": [],
29
+ "packageFormatVersion": "1.0.0"
30
+ }
31
+ }
@@ -0,0 +1,30 @@
1
+ import { HTMLAttributes } from "react";
2
+ /**
3
+ * Common properties supported by all public react components.
4
+ */
5
+ export interface CommonComponentProps {
6
+ /**
7
+ * Additional class name(s).
8
+ */
9
+ "className"?: string;
10
+ /**
11
+ * Used for testing.
12
+ */
13
+ "data-testid"?: string;
14
+ }
15
+ /**
16
+ * A helper hook that computes react properties for the topmost container in a public react component.
17
+ *
18
+ * Example:
19
+ *
20
+ * ```jsx
21
+ * function MyComponent(props) {
22
+ * const { containerProps } = useCommonComponentProps("my-component", props);
23
+ * // automatically applies css classes and testid
24
+ * return <Box {...containerProps}>Content</Box>;
25
+ * }
26
+ * ```
27
+ */
28
+ export declare function useCommonComponentProps(componentClassName: string, props: CommonComponentProps): {
29
+ containerProps: HTMLAttributes<HTMLElement>;
30
+ };
@@ -0,0 +1,14 @@
1
+ import classNames from 'classnames';
2
+
3
+ function useCommonComponentProps(componentClassName, props) {
4
+ const containerProps = {
5
+ "className": classNames(componentClassName, props.className),
6
+ "data-testid": props["data-testid"]
7
+ };
8
+ return {
9
+ containerProps
10
+ };
11
+ }
12
+
13
+ export { useCommonComponentProps };
14
+ //# sourceMappingURL=useCommonComponentProps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCommonComponentProps.js","sources":["useCommonComponentProps.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport classNames from \"classnames\";\nimport { HTMLAttributes } from \"react\";\n\n/**\n * Common properties supported by all public react components.\n */\nexport interface CommonComponentProps {\n /**\n * Additional class name(s).\n */\n \"className\"?: string;\n\n /**\n * Used for testing.\n */\n \"data-testid\"?: string;\n}\n\n/**\n * A helper hook that computes react properties for the topmost container in a public react component.\n *\n * Example:\n *\n * ```jsx\n * function MyComponent(props) {\n * const { containerProps } = useCommonComponentProps(\"my-component\", props);\n * // automatically applies css classes and testid\n * return <Box {...containerProps}>Content</Box>;\n * }\n * ```\n */\nexport function useCommonComponentProps(\n componentClassName: string,\n props: CommonComponentProps\n): { containerProps: HTMLAttributes<HTMLElement> } {\n const containerProps = {\n \"className\": classNames(componentClassName, props.className),\n \"data-testid\": props[\"data-testid\"]\n };\n return {\n containerProps\n };\n}\n"],"names":[],"mappings":";;AAiCgB,SAAA,uBAAA,CACZ,oBACA,KAC+C,EAAA;AAC/C,EAAA,MAAM,cAAiB,GAAA;AAAA,IACnB,WAAa,EAAA,UAAA,CAAW,kBAAoB,EAAA,KAAA,CAAM,SAAS,CAAA;AAAA,IAC3D,aAAA,EAAe,MAAM,aAAa,CAAA;AAAA,GACtC,CAAA;AACA,EAAO,OAAA;AAAA,IACH,cAAA;AAAA,GACJ,CAAA;AACJ;;;;"}
package/useEvent.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Creates an event handler with stable function identity.
3
+ * The returned function will always invoke the most recent implementation of `handler`.
4
+ *
5
+ * The returned event handler can be used, for example, as an event handler in `useEffect()`.
6
+ * Because the function identity is stable, `useEffect()` will not re-trigger if the implementation changes.
7
+ *
8
+ * NOTE: the event handler must not be called during rendering!
9
+ *
10
+ * See also: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
11
+ */
12
+ export declare function useEvent<Args extends unknown[], Ret>(handler: (...args: Args) => Ret): typeof handler;
package/useEvent.js ADDED
@@ -0,0 +1,16 @@
1
+ import { useRef, useLayoutEffect, useCallback } from 'react';
2
+
3
+ function useEvent(handler) {
4
+ const handlerRef = useRef(null);
5
+ useLayoutEffect(() => {
6
+ handlerRef.current = handler;
7
+ });
8
+ const stableHandler = useCallback((...args) => {
9
+ const currentHandler = handlerRef.current;
10
+ return currentHandler(...args);
11
+ }, []);
12
+ return stableHandler;
13
+ }
14
+
15
+ export { useEvent };
16
+ //# sourceMappingURL=useEvent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEvent.js","sources":["useEvent.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { useCallback, useLayoutEffect, useRef } from \"react\";\n\n/**\n * Creates an event handler with stable function identity.\n * The returned function will always invoke the most recent implementation of `handler`.\n *\n * The returned event handler can be used, for example, as an event handler in `useEffect()`.\n * Because the function identity is stable, `useEffect()` will not re-trigger if the implementation changes.\n *\n * NOTE: the event handler must not be called during rendering!\n *\n * See also: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md\n */\nexport function useEvent<Args extends unknown[], Ret>(\n handler: (...args: Args) => Ret\n): typeof handler {\n const handlerRef = useRef<typeof handler | null>(null);\n\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n const stableHandler = useCallback((...args: Args): Ret => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const currentHandler = handlerRef.current!;\n return currentHandler(...args);\n }, []);\n return stableHandler;\n}\n"],"names":[],"mappings":";;AAeO,SAAS,SACZ,OACc,EAAA;AACd,EAAM,MAAA,UAAA,GAAa,OAA8B,IAAI,CAAA,CAAA;AAErD,EAAA,eAAA,CAAgB,MAAM;AAClB,IAAA,UAAA,CAAW,OAAU,GAAA,OAAA,CAAA;AAAA,GACxB,CAAA,CAAA;AAED,EAAM,MAAA,aAAA,GAAgB,WAAY,CAAA,CAAA,GAAI,IAAoB,KAAA;AAEtD,IAAA,MAAM,iBAAiB,UAAW,CAAA,OAAA,CAAA;AAClC,IAAO,OAAA,cAAA,CAAe,GAAG,IAAI,CAAA,CAAA;AAAA,GACjC,EAAG,EAAE,CAAA,CAAA;AACL,EAAO,OAAA,aAAA,CAAA;AACX;;;;"}