@dxos/react-hooks 0.1.41

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/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ MIT License
2
+ Copyright (c) 2022 DXOS
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Aurora types
2
+
3
+ TypeScript types for Aurora and its themes.
@@ -0,0 +1,140 @@
1
+ // packages/ui/primitives/react-hooks/src/useForwardedRef.ts
2
+ import { useRef, useEffect } from "react";
3
+ var useForwardedRef = (ref) => {
4
+ const innerRef = useRef(null);
5
+ useEffect(() => {
6
+ if (!ref) {
7
+ return;
8
+ }
9
+ if (typeof ref === "function") {
10
+ ref(innerRef.current);
11
+ } else {
12
+ ref.current = innerRef.current;
13
+ }
14
+ });
15
+ return innerRef;
16
+ };
17
+
18
+ // packages/ui/primitives/react-hooks/src/useId.ts
19
+ import alea from "alea";
20
+ import { useMemo } from "react";
21
+ var Alea = alea;
22
+ var prng = new Alea("@dxos/react-hooks");
23
+ var randomString = (n = 4) => prng().toString(16).slice(2, n + 2);
24
+ var useId = (namespace, propsId, opts) => useMemo(() => {
25
+ var _a;
26
+ return propsId != null ? propsId : `${namespace}-${randomString((_a = opts == null ? void 0 : opts.n) != null ? _a : 4)}`;
27
+ }, [
28
+ propsId
29
+ ]);
30
+
31
+ // packages/ui/primitives/react-hooks/src/useIsFocused.ts
32
+ import { useEffect as useEffect2, useRef as useRef2, useState } from "react";
33
+ var useIsFocused = (inputRef) => {
34
+ const [isFocused, setIsFocused] = useState(void 0);
35
+ const isFocusedRef = useRef2(isFocused);
36
+ isFocusedRef.current = isFocused;
37
+ useEffect2(() => {
38
+ const input = inputRef.current;
39
+ if (!input) {
40
+ return;
41
+ }
42
+ const onFocus = () => setIsFocused(true);
43
+ const onBlur = () => setIsFocused(false);
44
+ input.addEventListener("focus", onFocus);
45
+ input.addEventListener("blur", onBlur);
46
+ if (isFocusedRef.current === void 0) {
47
+ setIsFocused(document.activeElement === input);
48
+ }
49
+ return () => {
50
+ input.removeEventListener("focus", onFocus);
51
+ input.removeEventListener("blur", onBlur);
52
+ };
53
+ }, [
54
+ inputRef,
55
+ setIsFocused
56
+ ]);
57
+ return isFocused;
58
+ };
59
+
60
+ // packages/ui/primitives/react-hooks/src/useMediaQuery.ts
61
+ import { useEffect as useEffect3, useState as useState2 } from "react";
62
+ var breakpointMediaQueries = {
63
+ sm: "(min-width: 640px)",
64
+ md: "(min-width: 768px)",
65
+ lg: "(min-width: 1024px)",
66
+ xl: "(min-width: 1280px)",
67
+ "2xl": "(min-width: 1536px)"
68
+ };
69
+ var useMediaQuery = (query, options = {}) => {
70
+ const { ssr = true, fallback } = options;
71
+ const queries = (Array.isArray(query) ? query : [
72
+ query
73
+ ]).map((query2) => query2 in breakpointMediaQueries ? breakpointMediaQueries[query2] : query2);
74
+ let fallbackValues = Array.isArray(fallback) ? fallback : [
75
+ fallback
76
+ ];
77
+ fallbackValues = fallbackValues.filter((v) => v != null);
78
+ const [value, setValue] = useState2(() => {
79
+ return queries.map((query2, index) => {
80
+ var _a;
81
+ return {
82
+ media: query2,
83
+ matches: ssr ? !!fallbackValues[index] : (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2).matches
84
+ };
85
+ });
86
+ });
87
+ useEffect3(() => {
88
+ setValue(queries.map((query2) => {
89
+ var _a;
90
+ return {
91
+ media: query2,
92
+ matches: (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2).matches
93
+ };
94
+ }));
95
+ const mql = queries.map((query2) => {
96
+ var _a;
97
+ return (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2);
98
+ });
99
+ const handler = (evt) => {
100
+ setValue((prev) => {
101
+ return prev.slice().map((item) => {
102
+ if (item.media === evt.media) {
103
+ return {
104
+ ...item,
105
+ matches: evt.matches
106
+ };
107
+ }
108
+ return item;
109
+ });
110
+ });
111
+ };
112
+ mql.forEach((mql2) => {
113
+ if (typeof (mql2 == null ? void 0 : mql2.addListener) === "function") {
114
+ mql2 == null ? void 0 : mql2.addListener(handler);
115
+ } else {
116
+ mql2 == null ? void 0 : mql2.addEventListener("change", handler);
117
+ }
118
+ });
119
+ return () => {
120
+ mql.forEach((mql2) => {
121
+ if (typeof (mql2 == null ? void 0 : mql2.removeListener) === "function") {
122
+ mql2 == null ? void 0 : mql2.removeListener(handler);
123
+ } else {
124
+ mql2 == null ? void 0 : mql2.removeEventListener("change", handler);
125
+ }
126
+ });
127
+ };
128
+ }, [
129
+ document.defaultView
130
+ ]);
131
+ return value.map((item) => !!item.matches);
132
+ };
133
+ export {
134
+ randomString,
135
+ useForwardedRef,
136
+ useId,
137
+ useIsFocused,
138
+ useMediaQuery
139
+ };
140
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: React.ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n"],
5
+ "mappings": ";AAIA,SAASA,Q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AAC5B,mBAAO;cAAE,GAAGU;cAAMT,SAASM,IAAIN;YAAQ;UACzC;AACA,iBAAOS;QACT,CAAA;MACF,CAAA;IACF;AAEAL,QAAIM,QAAQ,CAACN,SAAQ;AACnB,UAAI,QAAOA,QAAAA,gBAAAA,KAAKO,iBAAgB,YAAY;AAC1CP,QAAAA,QAAAA,gBAAAA,KAAKO,YAAYN;MACnB,OAAO;AACLD,QAAAA,QAAAA,gBAAAA,KAAKQ,iBAAiB,UAAUP;MAClC;IACF,CAAA;AAEA,WAAO,MAAM;AACXD,UAAIM,QAAQ,CAACN,SAAQ;AACnB,YAAI,QAAOA,QAAAA,gBAAAA,KAAKS,oBAAmB,YAAY;AAC7CT,UAAAA,QAAAA,gBAAAA,KAAKS,eAAeR;QACtB,OAAO;AACLD,UAAAA,QAAAA,gBAAAA,KAAKU,oBAAoB,UAAUT;QACrC;MACF,CAAA;IACF;EACF,GAAG;IAACJ,SAASC;GAAY;AAEzB,SAAON,MAAMJ,IAAI,CAACiB,SAAS,CAAC,CAACA,KAAKT,OAAO;AACvC;",
6
+ "names": ["useRef", "useEffect", "useForwardedRef", "ref", "innerRef", "current", "alea", "useMemo", "Alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useEffect", "useRef", "useState", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "undefined", "isFocusedRef", "current", "input", "onFocus", "onBlur", "addEventListener", "document", "activeElement", "removeEventListener", "useEffect", "useState", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "value", "setValue", "index", "media", "matches", "document", "defaultView", "matchMedia", "mql", "handler", "evt", "prev", "slice", "item", "forEach", "addListener", "addEventListener", "removeListener", "removeEventListener"]
7
+ }
@@ -0,0 +1 @@
1
+ {"inputs":{"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1639,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":1887,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3857,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9277,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":677,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"}]}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":8586},"packages/ui/primitives/react-hooks/dist/lib/browser/index.mjs":{"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["randomString","useForwardedRef","useId","useIsFocused","useMediaQuery"],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":316},"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":0},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":396},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":819},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":2282}},"bytes":4168}}}
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // packages/ui/primitives/react-hooks/src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ randomString: () => randomString,
34
+ useForwardedRef: () => useForwardedRef,
35
+ useId: () => useId,
36
+ useIsFocused: () => useIsFocused,
37
+ useMediaQuery: () => useMediaQuery
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // packages/ui/primitives/react-hooks/src/useForwardedRef.ts
42
+ var import_react = require("react");
43
+ var useForwardedRef = (ref) => {
44
+ const innerRef = (0, import_react.useRef)(null);
45
+ (0, import_react.useEffect)(() => {
46
+ if (!ref) {
47
+ return;
48
+ }
49
+ if (typeof ref === "function") {
50
+ ref(innerRef.current);
51
+ } else {
52
+ ref.current = innerRef.current;
53
+ }
54
+ });
55
+ return innerRef;
56
+ };
57
+
58
+ // packages/ui/primitives/react-hooks/src/useId.ts
59
+ var import_alea = __toESM(require("alea"));
60
+ var import_react2 = require("react");
61
+ var Alea = import_alea.default;
62
+ var prng = new Alea("@dxos/react-hooks");
63
+ var randomString = (n = 4) => prng().toString(16).slice(2, n + 2);
64
+ var useId = (namespace, propsId, opts) => (0, import_react2.useMemo)(() => {
65
+ var _a;
66
+ return propsId != null ? propsId : `${namespace}-${randomString((_a = opts == null ? void 0 : opts.n) != null ? _a : 4)}`;
67
+ }, [
68
+ propsId
69
+ ]);
70
+
71
+ // packages/ui/primitives/react-hooks/src/useIsFocused.ts
72
+ var import_react3 = require("react");
73
+ var useIsFocused = (inputRef) => {
74
+ const [isFocused, setIsFocused] = (0, import_react3.useState)(void 0);
75
+ const isFocusedRef = (0, import_react3.useRef)(isFocused);
76
+ isFocusedRef.current = isFocused;
77
+ (0, import_react3.useEffect)(() => {
78
+ const input = inputRef.current;
79
+ if (!input) {
80
+ return;
81
+ }
82
+ const onFocus = () => setIsFocused(true);
83
+ const onBlur = () => setIsFocused(false);
84
+ input.addEventListener("focus", onFocus);
85
+ input.addEventListener("blur", onBlur);
86
+ if (isFocusedRef.current === void 0) {
87
+ setIsFocused(document.activeElement === input);
88
+ }
89
+ return () => {
90
+ input.removeEventListener("focus", onFocus);
91
+ input.removeEventListener("blur", onBlur);
92
+ };
93
+ }, [
94
+ inputRef,
95
+ setIsFocused
96
+ ]);
97
+ return isFocused;
98
+ };
99
+
100
+ // packages/ui/primitives/react-hooks/src/useMediaQuery.ts
101
+ var import_react4 = require("react");
102
+ var breakpointMediaQueries = {
103
+ sm: "(min-width: 640px)",
104
+ md: "(min-width: 768px)",
105
+ lg: "(min-width: 1024px)",
106
+ xl: "(min-width: 1280px)",
107
+ "2xl": "(min-width: 1536px)"
108
+ };
109
+ var useMediaQuery = (query, options = {}) => {
110
+ const { ssr = true, fallback } = options;
111
+ const queries = (Array.isArray(query) ? query : [
112
+ query
113
+ ]).map((query2) => query2 in breakpointMediaQueries ? breakpointMediaQueries[query2] : query2);
114
+ let fallbackValues = Array.isArray(fallback) ? fallback : [
115
+ fallback
116
+ ];
117
+ fallbackValues = fallbackValues.filter((v) => v != null);
118
+ const [value, setValue] = (0, import_react4.useState)(() => {
119
+ return queries.map((query2, index) => {
120
+ var _a;
121
+ return {
122
+ media: query2,
123
+ matches: ssr ? !!fallbackValues[index] : (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2).matches
124
+ };
125
+ });
126
+ });
127
+ (0, import_react4.useEffect)(() => {
128
+ setValue(queries.map((query2) => {
129
+ var _a;
130
+ return {
131
+ media: query2,
132
+ matches: (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2).matches
133
+ };
134
+ }));
135
+ const mql = queries.map((query2) => {
136
+ var _a;
137
+ return (_a = document.defaultView) == null ? void 0 : _a.matchMedia(query2);
138
+ });
139
+ const handler = (evt) => {
140
+ setValue((prev) => {
141
+ return prev.slice().map((item) => {
142
+ if (item.media === evt.media) {
143
+ return {
144
+ ...item,
145
+ matches: evt.matches
146
+ };
147
+ }
148
+ return item;
149
+ });
150
+ });
151
+ };
152
+ mql.forEach((mql2) => {
153
+ if (typeof (mql2 == null ? void 0 : mql2.addListener) === "function") {
154
+ mql2 == null ? void 0 : mql2.addListener(handler);
155
+ } else {
156
+ mql2 == null ? void 0 : mql2.addEventListener("change", handler);
157
+ }
158
+ });
159
+ return () => {
160
+ mql.forEach((mql2) => {
161
+ if (typeof (mql2 == null ? void 0 : mql2.removeListener) === "function") {
162
+ mql2 == null ? void 0 : mql2.removeListener(handler);
163
+ } else {
164
+ mql2 == null ? void 0 : mql2.removeEventListener("change", handler);
165
+ }
166
+ });
167
+ };
168
+ }, [
169
+ document.defaultView
170
+ ]);
171
+ return value.map((item) => !!item.matches);
172
+ };
173
+ // Annotate the CommonJS export names for ESM import in node:
174
+ 0 && (module.exports = {
175
+ randomString,
176
+ useForwardedRef,
177
+ useId,
178
+ useIsFocused,
179
+ useMediaQuery
180
+ });
181
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/index.ts", "../../../src/useForwardedRef.ts", "../../../src/useId.ts", "../../../src/useIsFocused.ts", "../../../src/useMediaQuery.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nexport * from './useForwardedRef';\nexport * from './useId';\nexport * from './useIsFocused';\nexport * from './useMediaQuery';\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { useRef, useEffect } from 'react';\n\nexport const useForwardedRef = <T>(ref: React.ForwardedRef<T>) => {\n const innerRef = useRef<T>(null);\n\n useEffect(() => {\n if (!ref) {\n return;\n }\n if (typeof ref === 'function') {\n ref(innerRef.current);\n } else {\n ref.current = innerRef.current;\n }\n });\n\n return innerRef;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport alea from 'alea';\nimport { useMemo } from 'react';\n\ninterface PrngFactory {\n new (seed?: string): () => number;\n}\n\nconst Alea: PrngFactory = alea as unknown as PrngFactory;\n\nconst prng = new Alea('@dxos/react-hooks');\n\nexport const randomString = (n = 4) =>\n prng()\n .toString(16)\n .slice(2, n + 2);\n\nexport const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>\n useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);\n", "//\n// Copyright 2022 DXOS.org\n//\n\n// Based upon the useIsFocused hook which is part of the `rci` project:\n/// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused\n\nimport { useEffect, useRef, useState, RefObject } from 'react';\n\nexport const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {\n const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);\n const isFocusedRef = useRef<boolean | undefined>(isFocused);\n\n isFocusedRef.current = isFocused;\n\n useEffect(() => {\n const input = inputRef.current;\n if (!input) {\n return;\n }\n\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n input.addEventListener('focus', onFocus);\n input.addEventListener('blur', onBlur);\n\n if (isFocusedRef.current === undefined) {\n setIsFocused(document.activeElement === input);\n }\n\n return () => {\n input.removeEventListener('focus', onFocus);\n input.removeEventListener('blur', onBlur);\n };\n }, [inputRef, setIsFocused]);\n\n return isFocused;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts\n\nimport { useEffect, useState } from 'react';\n\nexport type UseMediaQueryOptions = {\n fallback?: boolean | boolean[];\n ssr?: boolean;\n};\n\n// TODO(thure): This should be derived from the same source of truth as the Tailwind theme config\nconst breakpointMediaQueries: Record<string, string> = {\n sm: '(min-width: 640px)',\n md: '(min-width: 768px)',\n lg: '(min-width: 1024px)',\n xl: '(min-width: 1280px)',\n '2xl': '(min-width: 1536px)',\n};\n\n/**\n * React hook that tracks state of a CSS media query\n *\n * @param query the media query to match, or a recognized breakpoint token\n * @param options the media query options { fallback, ssr }\n *\n * @see Docs https://chakra-ui.com/docs/hooks/use-media-query\n */\nexport const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {\n const { ssr = true, fallback } = options;\n\n const queries = (Array.isArray(query) ? query : [query]).map((query) =>\n query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,\n );\n\n let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];\n fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];\n\n const [value, setValue] = useState(() => {\n return queries.map((query, index) => ({\n media: query,\n matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,\n }));\n });\n\n useEffect(() => {\n setValue(\n queries.map((query) => ({\n media: query,\n matches: document.defaultView?.matchMedia(query).matches,\n })),\n );\n\n const mql = queries.map((query) => document.defaultView?.matchMedia(query));\n\n const handler = (evt: MediaQueryListEvent) => {\n setValue((prev) => {\n return prev.slice().map((item) => {\n if (item.media === evt.media) {\n return { ...item, matches: evt.matches };\n }\n return item;\n });\n });\n };\n\n mql.forEach((mql) => {\n if (typeof mql?.addListener === 'function') {\n mql?.addListener(handler);\n } else {\n mql?.addEventListener('change', handler);\n }\n });\n\n return () => {\n mql.forEach((mql) => {\n if (typeof mql?.removeListener === 'function') {\n mql?.removeListener(handler);\n } else {\n mql?.removeEventListener('change', handler);\n }\n });\n };\n }, [document.defaultView]);\n\n return value.map((item) => !!item.matches);\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;ACIA,mBAAkC;AAE3B,IAAMA,kBAAkB,CAAIC,QAA+B;AAChE,QAAMC,eAAWC,qBAAU,IAAI;AAE/BC,8BAAU,MAAM;AACd,QAAI,CAACH,KAAK;AACR;IACF;AACA,QAAI,OAAOA,QAAQ,YAAY;AAC7BA,UAAIC,SAASG,OAAO;IACtB,OAAO;AACLJ,UAAII,UAAUH,SAASG;IACzB;EACF,CAAA;AAEA,SAAOH;AACT;;;ACjBA,kBAAiB;AACjB,IAAAI,gBAAwB;AAMxB,IAAMC,OAAoBC,YAAAA;AAE1B,IAAMC,OAAO,IAAIF,KAAK,mBAAA;AAEf,IAAMG,eAAe,CAACC,IAAI,MAC/BF,KAAAA,EACGG,SAAS,EAAA,EACTC,MAAM,GAAGF,IAAI,CAAA;AAEX,IAAMG,QAAQ,CAACC,WAAmBC,SAAkBC,aACzDC,uBAAQ,MAAA;AArBV;AAqBgBF,qCAAW,GAAGD,aAAaL,cAAaO,kCAAMN,MAANM,YAAW,CAAA;GAAM;EAACD;CAAQ;;;ACdlF,IAAAG,gBAAuD;AAEhD,IAAMC,eAAe,CAACC,aAA0C;AACrE,QAAM,CAACC,WAAWC,YAAAA,QAAgBC,wBAA8BC,MAAAA;AAChE,QAAMC,mBAAeC,sBAA4BL,SAAAA;AAEjDI,eAAaE,UAAUN;AAEvBO,+BAAU,MAAM;AACd,UAAMC,QAAQT,SAASO;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AASC,cAASC,gBAATD,mBAAsBE,WAAWnB,QAAOgB;MACnD;KAAA,CAAA;AAGF,UAAMK,MAAMjB,QAAQG,IAAI,CAACP,WAAAA;AAvD3B;AAuDqCiB,4BAASC,gBAATD,mBAAsBE,WAAWnB;KAAAA;AAEpE,UAAMsB,UAAU,CAACC,QAA6B;AAC5CX,eAAS,CAACY,SAAS;AACjB,eAAOA,KAAKC,MAAK,EAAGlB,IAAI,CAACmB,SAAS;AAChC,cAAIA,KAAKX,UAAUQ,IAAIR,OAAO;AAC5B,mBAAO;cAAE,GAAGW;cAAMV,SAASO,IAAIP;YAAQ;UACzC;AACA,iBAAOU;QACT,CAAA;MACF,CAAA;IACF;AAEAL,QAAIM,QAAQ,CAACN,SAAQ;AACnB,UAAI,QAAOA,QAAAA,gBAAAA,KAAKO,iBAAgB,YAAY;AAC1CP,QAAAA,QAAAA,gBAAAA,KAAKO,YAAYN;MACnB,OAAO;AACLD,QAAAA,QAAAA,gBAAAA,KAAKQ,iBAAiB,UAAUP;MAClC;IACF,CAAA;AAEA,WAAO,MAAM;AACXD,UAAIM,QAAQ,CAACN,SAAQ;AACnB,YAAI,QAAOA,QAAAA,gBAAAA,KAAKS,oBAAmB,YAAY;AAC7CT,UAAAA,QAAAA,gBAAAA,KAAKS,eAAeR;QACtB,OAAO;AACLD,UAAAA,QAAAA,gBAAAA,KAAKU,oBAAoB,UAAUT;QACrC;MACF,CAAA;IACF;EACF,GAAG;IAACL,SAASC;GAAY;AAEzB,SAAOP,MAAMJ,IAAI,CAACmB,SAAS,CAAC,CAACA,KAAKV,OAAO;AACvC;",
6
+ "names": ["useForwardedRef", "ref", "innerRef", "useRef", "useEffect", "current", "import_react", "Alea", "alea", "prng", "randomString", "n", "toString", "slice", "useId", "namespace", "propsId", "opts", "useMemo", "import_react", "useIsFocused", "inputRef", "isFocused", "setIsFocused", "useState", "undefined", "isFocusedRef", "useRef", "current", "useEffect", "input", "onFocus", "onBlur", "addEventListener", "document", "activeElement", "removeEventListener", "import_react", "breakpointMediaQueries", "sm", "md", "lg", "xl", "useMediaQuery", "query", "options", "ssr", "fallback", "queries", "Array", "isArray", "map", "fallbackValues", "filter", "v", "value", "setValue", "useState", "index", "media", "matches", "document", "defaultView", "matchMedia", "useEffect", "mql", "handler", "evt", "prev", "slice", "item", "forEach", "addListener", "addEventListener", "removeListener", "removeEventListener"]
7
+ }
@@ -0,0 +1 @@
1
+ {"inputs":{"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytes":1639,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytes":1887,"imports":[{"path":"alea","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytes":3857,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytes":9277,"imports":[{"path":"react","kind":"import-statement","external":true}]},"packages/ui/primitives/react-hooks/src/index.ts":{"bytes":677,"imports":[{"path":"packages/ui/primitives/react-hooks/src/useForwardedRef.ts","kind":"import-statement","original":"./useForwardedRef"},{"path":"packages/ui/primitives/react-hooks/src/useId.ts","kind":"import-statement","original":"./useId"},{"path":"packages/ui/primitives/react-hooks/src/useIsFocused.ts","kind":"import-statement","original":"./useIsFocused"},{"path":"packages/ui/primitives/react-hooks/src/useMediaQuery.ts","kind":"import-statement","original":"./useMediaQuery"}]}},"outputs":{"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":8823},"packages/ui/primitives/react-hooks/dist/lib/node/index.cjs":{"imports":[{"path":"react","kind":"require-call","external":true},{"path":"alea","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/ui/primitives/react-hooks/src/index.ts","inputs":{"packages/ui/primitives/react-hooks/src/index.ts":{"bytesInOutput":267},"packages/ui/primitives/react-hooks/src/useForwardedRef.ts":{"bytesInOutput":346},"packages/ui/primitives/react-hooks/src/useId.ts":{"bytesInOutput":454},"packages/ui/primitives/react-hooks/src/useIsFocused.ts":{"bytesInOutput":834},"packages/ui/primitives/react-hooks/src/useMediaQuery.ts":{"bytesInOutput":2284}},"bytes":6068}}}
@@ -0,0 +1,5 @@
1
+ export * from './useForwardedRef';
2
+ export * from './useId';
3
+ export * from './useIsFocused';
4
+ export * from './useMediaQuery';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare const useForwardedRef: <T>(ref: import("react").ForwardedRef<T>) => import("react").RefObject<T>;
2
+ //# sourceMappingURL=useForwardedRef.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useForwardedRef.d.ts","sourceRoot":"","sources":["../../../src/useForwardedRef.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,eAAe,2EAe3B,CAAC"}
@@ -0,0 +1,5 @@
1
+ export declare const randomString: (n?: number) => string;
2
+ export declare const useId: (namespace: string, propsId?: string, opts?: Partial<{
3
+ n: number;
4
+ }>) => string;
5
+ //# sourceMappingURL=useId.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useId.d.ts","sourceRoot":"","sources":["../../../src/useId.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,YAAY,wBAGL,CAAC;AAErB,eAAO,MAAM,KAAK,cAAe,MAAM,YAAY,MAAM,SAAS,QAAQ;IAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,WACL,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { RefObject } from 'react';
2
+ export declare const useIsFocused: (inputRef: RefObject<HTMLInputElement>) => boolean | undefined;
3
+ //# sourceMappingURL=useIsFocused.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useIsFocused.d.ts","sourceRoot":"","sources":["../../../src/useIsFocused.ts"],"names":[],"mappings":"AAOA,OAAO,EAA+B,SAAS,EAAE,MAAM,OAAO,CAAC;AAE/D,eAAO,MAAM,YAAY,aAAc,UAAU,gBAAgB,CAAC,wBA4BjE,CAAC"}
@@ -0,0 +1,14 @@
1
+ export declare type UseMediaQueryOptions = {
2
+ fallback?: boolean | boolean[];
3
+ ssr?: boolean;
4
+ };
5
+ /**
6
+ * React hook that tracks state of a CSS media query
7
+ *
8
+ * @param query the media query to match, or a recognized breakpoint token
9
+ * @param options the media query options { fallback, ssr }
10
+ *
11
+ * @see Docs https://chakra-ui.com/docs/hooks/use-media-query
12
+ */
13
+ export declare const useMediaQuery: (query: string | string[], options?: UseMediaQueryOptions) => boolean[];
14
+ //# sourceMappingURL=useMediaQuery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useMediaQuery.d.ts","sourceRoot":"","sources":["../../../src/useMediaQuery.ts"],"names":[],"mappings":"AAQA,oBAAY,oBAAoB,GAAG;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,OAAO,EAAE,CAAC;IAC/B,GAAG,CAAC,EAAE,OAAO,CAAC;CACf,CAAC;AAWF;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,UAAW,MAAM,GAAG,MAAM,EAAE,YAAW,oBAAoB,KAAQ,OAAO,EA0DnG,CAAC"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@dxos/react-hooks",
3
+ "version": "0.1.41",
4
+ "description": "React hooks supporting DXOS React primitives.",
5
+ "homepage": "https://dxos.org",
6
+ "bugs": "https://github.com/dxos/dxos/issues",
7
+ "license": "MIT",
8
+ "author": "DXOS.org",
9
+ "main": "dist/lib/node/index.cjs",
10
+ "browser": {
11
+ "./dist/lib/node/index.cjs": "./dist/lib/browser/index.mjs"
12
+ },
13
+ "types": "dist/types/src/index.d.ts",
14
+ "files": [
15
+ "dist",
16
+ "src"
17
+ ],
18
+ "dependencies": {
19
+ "alea": "^1.0.1"
20
+ },
21
+ "devDependencies": {
22
+ "@types/react": "^18.0.21",
23
+ "@types/react-dom": "^18.0.6",
24
+ "react": "^18.2.0",
25
+ "react-dom": "^18.2.0"
26
+ },
27
+ "peerDependencies": {
28
+ "react": "^18.2.0",
29
+ "react-dom": "^18.2.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ export * from './useForwardedRef';
6
+ export * from './useId';
7
+ export * from './useIsFocused';
8
+ export * from './useMediaQuery';
@@ -0,0 +1,22 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ import { useRef, useEffect } from 'react';
6
+
7
+ export const useForwardedRef = <T>(ref: React.ForwardedRef<T>) => {
8
+ const innerRef = useRef<T>(null);
9
+
10
+ useEffect(() => {
11
+ if (!ref) {
12
+ return;
13
+ }
14
+ if (typeof ref === 'function') {
15
+ ref(innerRef.current);
16
+ } else {
17
+ ref.current = innerRef.current;
18
+ }
19
+ });
20
+
21
+ return innerRef;
22
+ };
package/src/useId.ts ADDED
@@ -0,0 +1,22 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ import alea from 'alea';
6
+ import { useMemo } from 'react';
7
+
8
+ interface PrngFactory {
9
+ new (seed?: string): () => number;
10
+ }
11
+
12
+ const Alea: PrngFactory = alea as unknown as PrngFactory;
13
+
14
+ const prng = new Alea('@dxos/react-hooks');
15
+
16
+ export const randomString = (n = 4) =>
17
+ prng()
18
+ .toString(16)
19
+ .slice(2, n + 2);
20
+
21
+ export const useId = (namespace: string, propsId?: string, opts?: Partial<{ n: number }>) =>
22
+ useMemo(() => propsId ?? `${namespace}-${randomString(opts?.n ?? 4)}`, [propsId]);
@@ -0,0 +1,38 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ // Based upon the useIsFocused hook which is part of the `rci` project:
6
+ /// https://github.com/leonardodino/rci/blob/main/packages/use-is-focused
7
+
8
+ import { useEffect, useRef, useState, RefObject } from 'react';
9
+
10
+ export const useIsFocused = (inputRef: RefObject<HTMLInputElement>) => {
11
+ const [isFocused, setIsFocused] = useState<boolean | undefined>(undefined);
12
+ const isFocusedRef = useRef<boolean | undefined>(isFocused);
13
+
14
+ isFocusedRef.current = isFocused;
15
+
16
+ useEffect(() => {
17
+ const input = inputRef.current;
18
+ if (!input) {
19
+ return;
20
+ }
21
+
22
+ const onFocus = () => setIsFocused(true);
23
+ const onBlur = () => setIsFocused(false);
24
+ input.addEventListener('focus', onFocus);
25
+ input.addEventListener('blur', onBlur);
26
+
27
+ if (isFocusedRef.current === undefined) {
28
+ setIsFocused(document.activeElement === input);
29
+ }
30
+
31
+ return () => {
32
+ input.removeEventListener('focus', onFocus);
33
+ input.removeEventListener('blur', onBlur);
34
+ };
35
+ }, [inputRef, setIsFocused]);
36
+
37
+ return isFocused;
38
+ };
@@ -0,0 +1,89 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ // This hook is based on Chakra UI’s `useMediaQuery`: https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/media-query/src/use-media-query.ts
6
+
7
+ import { useEffect, useState } from 'react';
8
+
9
+ export type UseMediaQueryOptions = {
10
+ fallback?: boolean | boolean[];
11
+ ssr?: boolean;
12
+ };
13
+
14
+ // TODO(thure): This should be derived from the same source of truth as the Tailwind theme config
15
+ const breakpointMediaQueries: Record<string, string> = {
16
+ sm: '(min-width: 640px)',
17
+ md: '(min-width: 768px)',
18
+ lg: '(min-width: 1024px)',
19
+ xl: '(min-width: 1280px)',
20
+ '2xl': '(min-width: 1536px)',
21
+ };
22
+
23
+ /**
24
+ * React hook that tracks state of a CSS media query
25
+ *
26
+ * @param query the media query to match, or a recognized breakpoint token
27
+ * @param options the media query options { fallback, ssr }
28
+ *
29
+ * @see Docs https://chakra-ui.com/docs/hooks/use-media-query
30
+ */
31
+ export const useMediaQuery = (query: string | string[], options: UseMediaQueryOptions = {}): boolean[] => {
32
+ const { ssr = true, fallback } = options;
33
+
34
+ const queries = (Array.isArray(query) ? query : [query]).map((query) =>
35
+ query in breakpointMediaQueries ? breakpointMediaQueries[query] : query,
36
+ );
37
+
38
+ let fallbackValues = Array.isArray(fallback) ? fallback : [fallback];
39
+ fallbackValues = fallbackValues.filter((v) => v != null) as boolean[];
40
+
41
+ const [value, setValue] = useState(() => {
42
+ return queries.map((query, index) => ({
43
+ media: query,
44
+ matches: ssr ? !!fallbackValues[index] : document.defaultView?.matchMedia(query).matches,
45
+ }));
46
+ });
47
+
48
+ useEffect(() => {
49
+ setValue(
50
+ queries.map((query) => ({
51
+ media: query,
52
+ matches: document.defaultView?.matchMedia(query).matches,
53
+ })),
54
+ );
55
+
56
+ const mql = queries.map((query) => document.defaultView?.matchMedia(query));
57
+
58
+ const handler = (evt: MediaQueryListEvent) => {
59
+ setValue((prev) => {
60
+ return prev.slice().map((item) => {
61
+ if (item.media === evt.media) {
62
+ return { ...item, matches: evt.matches };
63
+ }
64
+ return item;
65
+ });
66
+ });
67
+ };
68
+
69
+ mql.forEach((mql) => {
70
+ if (typeof mql?.addListener === 'function') {
71
+ mql?.addListener(handler);
72
+ } else {
73
+ mql?.addEventListener('change', handler);
74
+ }
75
+ });
76
+
77
+ return () => {
78
+ mql.forEach((mql) => {
79
+ if (typeof mql?.removeListener === 'function') {
80
+ mql?.removeListener(handler);
81
+ } else {
82
+ mql?.removeEventListener('change', handler);
83
+ }
84
+ });
85
+ };
86
+ }, [document.defaultView]);
87
+
88
+ return value.map((item) => !!item.matches);
89
+ };