@developer_tribe/react-builder 0.1.29 → 0.1.30

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.
@@ -0,0 +1,2 @@
1
+ import { Node, NodeData } from '../types/Node';
2
+ export declare function querySelector(node: Node, selector: string): NodeData[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@developer_tribe/react-builder",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "type": "module",
5
5
  "restricted": true,
6
6
  "main": "dist/index.cjs.js",
package/src/index.ts CHANGED
@@ -24,3 +24,4 @@ export type { Device } from './types/Device';
24
24
  export { AttributesEditor };
25
25
  export * from './build-components/index';
26
26
  export { default as useNode } from './build-components/useNode';
27
+ export { querySelector } from './utils/querySelector';
@@ -0,0 +1,43 @@
1
+ import { Node, NodeData } from '../types/Node';
2
+
3
+ function isNodeData(value: Node): value is NodeData<Record<string, unknown>> {
4
+ if (value === null || value === undefined) return false;
5
+ if (Array.isArray(value)) return false;
6
+ if (typeof value === 'string') return false;
7
+ if (typeof value !== 'object') return false;
8
+ return (
9
+ 'type' in (value as Record<string, unknown>) &&
10
+ 'children' in (value as Record<string, unknown>)
11
+ );
12
+ }
13
+
14
+ export function querySelector(node: Node, selector: string): NodeData[] {
15
+ if (node === null || node === undefined) return [];
16
+ if (!selector) return [];
17
+
18
+ const isKeySearch = selector.startsWith('#');
19
+ const keyToMatch = isKeySearch ? selector.slice(1) : undefined;
20
+
21
+ const matches = (n: NodeData): boolean => {
22
+ if (isKeySearch) return n.key === keyToMatch;
23
+ return n.type === selector;
24
+ };
25
+
26
+ const result: NodeData[] = [];
27
+
28
+ const visit = (current: Node) => {
29
+ if (current === null || current === undefined) return;
30
+ if (Array.isArray(current)) {
31
+ for (const child of current) visit(child);
32
+ return;
33
+ }
34
+ if (typeof current === 'string') return;
35
+ if (isNodeData(current)) {
36
+ if (matches(current)) result.push(current);
37
+ visit(current.children);
38
+ }
39
+ };
40
+
41
+ visit(node);
42
+ return result;
43
+ }