@cgarciagarcia/react-query-builder 1.0.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/.eslintignore ADDED
File without changes
package/.eslintrc.cjs ADDED
@@ -0,0 +1,56 @@
1
+ /** @type {import('eslint').Linter.Config} */
2
+ const config = {
3
+ extends: [
4
+ 'eslint:recommended',
5
+ 'plugin:@typescript-eslint/recommended-type-checked',
6
+ 'plugin:@typescript-eslint/stylistic-type-checked',
7
+ 'plugin:jsx-a11y/recommended',
8
+ 'plugin:react-hooks/recommended',
9
+ 'plugin:react/recommended',
10
+ 'prettier'
11
+ ],
12
+ env: {
13
+ es2022: true,
14
+ browser: true,
15
+ commonjs: true
16
+ },
17
+ parser: '@typescript-eslint/parser',
18
+ parserOptions: {
19
+ project: true
20
+ },
21
+ plugins: ['@typescript-eslint', 'import', 'unused-imports'],
22
+ rules: {
23
+ 'react/prop-types': 'off',
24
+ '@typescript-eslint/unbound-method': 'off',
25
+ '@typescript-eslint/no-unused-vars': [
26
+ 'error',
27
+ {
28
+ argsIgnorePattern: '^_',
29
+ varsIgnorePattern: '^_'
30
+ }
31
+ ],
32
+ 'unused-imports/no-unused-imports': 'error',
33
+ '@typescript-eslint/consistent-type-imports': [
34
+ 'warn',
35
+ {prefer: 'type-imports', fixStyle: 'separate-type-imports'}
36
+ ],
37
+ '@typescript-eslint/no-misused-promises': [
38
+ 2,
39
+ {checksVoidReturn: {attributes: false}}
40
+ ],
41
+ 'import/consistent-type-specifier-style': ['error', 'prefer-inline'],
42
+ 'import/no-duplicates': 'error',
43
+ 'object-curly-spacing': ["warn", "always"]
44
+
45
+ },
46
+ ignorePatterns: ['.eslintrc.cjs', '.config.js', '.config.cjs', '.config.ts'],
47
+ reportUnusedDisableDirectives: true,
48
+ globals: {
49
+ React: 'writable'
50
+ },
51
+ settings: {
52
+ react: {version: 'detect'}
53
+ }
54
+ }
55
+
56
+ module.exports = config
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ v20.14.0
@@ -0,0 +1 @@
1
+ node_modules/
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Carlos Garcia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # react-query-builder
package/bun.lockb ADDED
Binary file
package/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ import * as QueryBuilder from "./src"
2
+
3
+ export {
4
+ QueryBuilder,
5
+ }
6
+
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@cgarciagarcia/react-query-builder",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.ts",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/cgarciagarcia/react-query-builder.git"
12
+ },
13
+ "dependencies": {
14
+ "react": "^18.2.0"
15
+ },
16
+ "devDependencies": {
17
+ "@typescript-eslint/eslint-plugin": "^6.6.0",
18
+ "@typescript-eslint/parser": "^6.6.0",
19
+ "@trivago/prettier-plugin-sort-imports": "^4.3.0",
20
+ "@types/eslint": "^8.44.2",
21
+ "@types/react": "^18.2.8",
22
+ "typescript": "^5.2.2",
23
+ "eslint": "^8.48.0",
24
+ "eslint-config-prettier": "^9.0.0",
25
+ "eslint-plugin-import": "^2.28.1",
26
+ "eslint-plugin-jsx-a11y": "^6.7.1",
27
+ "eslint-plugin-react": "^7.33.2",
28
+ "eslint-plugin-react-hooks": "^4.6.0",
29
+ "eslint-plugin-unused-imports": "^3.0.0",
30
+ "prettier": "^3.0.3",
31
+ "@types/bun": "latest"
32
+ },
33
+ "keywords": [
34
+ "react",
35
+ "query-builder",
36
+ "laravel-query-builder"
37
+ ],
38
+ "author": "Carlos Garcia",
39
+ "license": "MIT",
40
+ "bugs": {
41
+ "url": "https://github.com/cgarciagarcia/react-query-builder/issues"
42
+ },
43
+ "homepage": "https://github.com/cgarciagarcia/react-query-builder#readme"
44
+ }
@@ -0,0 +1,30 @@
1
+ /** @typedef {import('@ianvs/prettier-plugin-sort-imports').PluginConfig} SortImportsConfig */
2
+ /** @typedef {import('prettier').Config} PrettierConfig */
3
+ /** @typedef {{ tailwindConfig: string }} TailwindConfig */
4
+
5
+ /** @type { PrettierConfig | SortImportsConfig | TailwindConfig } */
6
+ const config = {
7
+ arrowParens: 'always',
8
+ printWidth: 80,
9
+ singleQuote: false,
10
+ jsxSingleQuote: false,
11
+ semi: true,
12
+ trailingComma: 'all',
13
+ tabWidth: 2,
14
+ plugins: [
15
+ '@ianvs/prettier-plugin-sort-imports',
16
+ ],
17
+ importOrder: [
18
+ '^(react/(.*)$)|^(react$)',
19
+ '<THIRD_PARTY_MODULES>',
20
+ '',
21
+ '^@/(.*)$',
22
+ '^[../]',
23
+ '^[./]'
24
+ ],
25
+ importOrderParserPlugins: ['typescript', 'jsx', 'decorators-legacy'],
26
+ importOrderTypeScriptVersion: '5.0.0',
27
+ bracketSpacing: true
28
+ }
29
+
30
+ module.exports = config
@@ -0,0 +1,44 @@
1
+ import { type Alias, type GlobalState, usingAlias, } from "@/utils";
2
+
3
+ export type FilterValue = (string | number)[] | string | number;
4
+
5
+ export interface Filter {
6
+ attribute: string;
7
+ value: (string | number)[];
8
+ }
9
+
10
+ export const filterAction = <Al extends Alias<object>, Attr extends string>(
11
+ attribute: Attr,
12
+ value: FilterValue,
13
+ state: GlobalState<Al>,
14
+ ) => {
15
+ const alias = usingAlias(state, attribute);
16
+ let prevFilter: Filter | undefined;
17
+
18
+ const allFilters = state.filters.reduce((filters, filter) => {
19
+ if (filter.attribute === alias) {
20
+ prevFilter = filter;
21
+ return filters;
22
+ }
23
+ return [...filters, filter];
24
+ }, [] as Filter[]);
25
+
26
+ const val = Array.isArray(value) ? value : [value];
27
+ return {
28
+ ...state,
29
+ filters: [
30
+ ...allFilters,
31
+ {
32
+ attribute: attribute,
33
+ value: [...(prevFilter?.value ?? []), ...val],
34
+ },
35
+ ],
36
+ };
37
+ };
38
+
39
+ export const clearFilterAction = <Al>(state: GlobalState<Al>) => {
40
+ return {
41
+ ...state,
42
+ filters: [],
43
+ };
44
+ };
@@ -0,0 +1,13 @@
1
+ import { type GlobalState } from "@/index";
2
+
3
+ export type Includes = string[];
4
+
5
+ export const includeAction = <T>(
6
+ includes: Includes,
7
+ state: GlobalState<T>,
8
+ ): GlobalState<T> => {
9
+ return {
10
+ ...state,
11
+ includes: includes,
12
+ };
13
+ };
@@ -0,0 +1,5 @@
1
+ export * from "@/actions/sort";
2
+ export * from "@/actions/filter";
3
+ export * from "@/actions/include";
4
+
5
+ export type Actions = "sort" | "filter" | "clear_filter" | "include";
@@ -0,0 +1,14 @@
1
+ import { type GlobalState, usingAlias } from "@/index";
2
+
3
+ export type Sort = [string, "asc" | "desc"];
4
+
5
+ export type Sorts = Sort[];
6
+
7
+ export const sortAction = <T>(sorts: Sort, state: GlobalState<T>) => {
8
+ const [attribute, direction] = sorts;
9
+ const attributeAliased = usingAlias(state, attribute);
10
+ return {
11
+ ...state,
12
+ sorts: [...state.sorts, [attributeAliased, direction]],
13
+ } satisfies GlobalState<T>;
14
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "@/utils";
2
+ export * from "@/actions";
3
+ export * from "@/useQueryBuilder";
@@ -0,0 +1,126 @@
1
+ import { useReducer, useState } from "react";
2
+
3
+ import {
4
+ type Actions,
5
+ type Alias,
6
+ build,
7
+ clearFilterAction,
8
+ type Filter,
9
+ filterAction,
10
+ type FilterValue,
11
+ type GlobalState,
12
+ includeAction,
13
+ type Includes,
14
+ type Sort,
15
+ sortAction,
16
+ } from "@/index";
17
+
18
+
19
+ interface Action {
20
+ type: Actions;
21
+ payload: unknown;
22
+
23
+ }
24
+
25
+ const reducer = <Aliases extends Record<string, string>>(
26
+ state: GlobalState<Aliases>,
27
+ action: Action,
28
+ ) => {
29
+ switch (action?.type) {
30
+ case "filter": {
31
+ const filter = action.payload as Filter;
32
+ return filterAction(filter.attribute, filter.value, state);
33
+ }
34
+ case "clear_filter": {
35
+ return clearFilterAction(state);
36
+ }
37
+ case "include": {
38
+ const includes = action.payload as Includes;
39
+ return includeAction(includes, state);
40
+ }
41
+ case "sort": {
42
+ const sorts = action.payload as Sort;
43
+ return sortAction(sorts, state);
44
+ }
45
+ default: {
46
+ return { ...state };
47
+ }
48
+ }
49
+
50
+ };
51
+
52
+ const initialState = <T>(): GlobalState<T> => ({
53
+ aliases: {} as Alias<T>,
54
+ filters: [],
55
+ includes: [],
56
+ sorts: [],
57
+ });
58
+
59
+ export interface QueryBuilder<AliasType = NonNullable<unknown>> {
60
+ filters: (
61
+ attribute: keyof AliasType | string,
62
+ value: FilterValue,
63
+ ) => QueryBuilder<AliasType>;
64
+ build: () => string;
65
+ clearFilters: () => QueryBuilder<AliasType>;
66
+ includes: (includes: Includes) => QueryBuilder<AliasType>;
67
+ sorts: (
68
+ attribute: string,
69
+ direction?: "asc" | "desc",
70
+ ) => QueryBuilder<AliasType>;
71
+ }
72
+
73
+ type ExtensibleQueryProps<T> = Pick<
74
+ QueryBuilder<T>,
75
+ "filters" | "includes" | "sorts"
76
+ >;
77
+
78
+ interface QueryBuilderProps<AliasType> extends ExtensibleQueryProps<AliasType> {
79
+ aliases?: AliasType;
80
+ }
81
+
82
+ export const useQueryBuilder: <Aliases extends Record<string, string>>(
83
+ config?: QueryBuilderProps<Aliases>,
84
+ ) => QueryBuilder<Aliases> = <Aliases extends Record<string, string>>(
85
+ config = {} as QueryBuilderProps<Aliases>,
86
+ ) => {
87
+ const [init] = useState(() => initialState<Aliases>());
88
+ const [state, dispatch] = useReducer(reducer, init, (init) => ({
89
+ ...init,
90
+ aliases: config?.aliases ?? ({} as Aliases),
91
+ }));
92
+
93
+ const builder: QueryBuilder<Aliases> = {
94
+ filters: (attribute, value) => {
95
+ dispatch({
96
+ type: "filter",
97
+ payload: { attribute, value },
98
+ });
99
+ return builder;
100
+ },
101
+ build: () => build(state),
102
+ clearFilters: () => {
103
+ dispatch({
104
+ type: "clear_filter",
105
+ payload: undefined,
106
+ });
107
+ return builder;
108
+ },
109
+ includes: (includes) => {
110
+ dispatch({
111
+ type: "include",
112
+ payload: includes,
113
+ });
114
+ return builder;
115
+ },
116
+ sorts: (attribute, direction) => {
117
+ dispatch({
118
+ type: "sort",
119
+ payload: [attribute, direction ?? "asc"],
120
+ });
121
+ return builder;
122
+ },
123
+ };
124
+
125
+ return builder;
126
+ };
@@ -0,0 +1,11 @@
1
+ import { type GlobalState } from "@/index";
2
+
3
+ export const usingAlias = <Al, K>(state: GlobalState<Al>, key: K) => {
4
+ return (state.aliases[key as unknown as keyof Al] as string) ?? key;
5
+ };
6
+
7
+
8
+ export type Alias<Prop> = {
9
+ [key in keyof Prop]: Prop[key] extends string ? string : never;
10
+ };
11
+
@@ -0,0 +1,31 @@
1
+ import { type GlobalState } from "@/utils/state";
2
+
3
+
4
+ export const build = <T>(state: GlobalState<T>): string => {
5
+ const filters = state.filters.reduce(
6
+ (acc, filter) => ({
7
+ ...acc,
8
+ [`filters[${filter.attribute}]`]: filter.value.join(","),
9
+ }),
10
+ {},
11
+ );
12
+
13
+ const sorts = state.sorts.reduce((acc, sort) => {
14
+ const [attribute, dir] = sort;
15
+ const direction = dir === "desc" ? "-" : "";
16
+ acc.push(`${direction}${attribute}`);
17
+ return acc;
18
+ }, [] as string[]);
19
+
20
+ const urlSearchParams = new URLSearchParams({
21
+ ...filters,
22
+ });
23
+
24
+ if (sorts.length > 0) {
25
+ urlSearchParams.append("sort", sorts.join(","));
26
+ }
27
+
28
+ const searchParamsString = urlSearchParams.toString();
29
+
30
+ return searchParamsString ? "?" + urlSearchParams.toString() : "";
31
+ };
@@ -0,0 +1,3 @@
1
+ export * from "@/utils/state";
2
+ export * from "@/utils/alias";
3
+ export * from "@/utils/build";
@@ -0,0 +1,8 @@
1
+ import { type Alias, type Filter, type Includes, type Sorts } from "@/index";
2
+
3
+ export interface GlobalState<Al> {
4
+ aliases: Alias<Al>;
5
+ filters: Filter[];
6
+ includes: Includes;
7
+ sorts: Sorts;
8
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "baseUrl": "./src",
5
+ "esModuleInterop": true,
6
+ "forceConsistentCasingInFileNames": true,
7
+ "incremental": true,
8
+ "isolatedModules": true,
9
+ "jsx": "react-jsx",
10
+ "lib": [
11
+ "esnext"
12
+ ],
13
+ "module": "esnext",
14
+ "moduleResolution": "node",
15
+ "noEmit": true,
16
+ "noUnusedParameters": true,
17
+ "noUnusedLocals": true,
18
+ "noUncheckedIndexedAccess": true,
19
+ "paths": {
20
+ "@/*": [
21
+ "*"
22
+ ]
23
+ },
24
+ "resolveJsonModule": true,
25
+ "skipLibCheck": true,
26
+ "strict": true,
27
+ "target": "ESNext"
28
+ },
29
+ "include": [
30
+ "./src/**/*",
31
+ ".eslintrc.cjs",
32
+ "./prettier.config.cjs",
33
+ "./index.ts"
34
+ ]
35
+ }