react-ternary-be-gone 0.1.1 → 0.1.3

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/Case.js ADDED
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+
3
+ const Case = ({ when, children, default: isDefault = false }) => {
4
+ // This component is just a marker for Conditional to process
5
+ return <>{children}</>;
6
+ };
7
+
8
+ export default Case;
package/Conditional.js CHANGED
@@ -1,4 +1,8 @@
1
1
  import React, { useMemo, useEffect } from 'react';
2
+ import Case from './Case';
3
+ import If from './If';
4
+ import ElseIf from './ElseIf';
5
+ import Else from './Else';
2
6
 
3
7
  const Conditional = ({
4
8
  when,
@@ -27,6 +31,8 @@ const Conditional = ({
27
31
  startsWith = null,
28
32
  endsWith = null,
29
33
  match = null, // regex match
34
+ // Switch-case feature
35
+ switch: switchValue,
30
36
  }) => {
31
37
  const hasCondition = when !== undefined;
32
38
  const hasIteration = each !== undefined;
@@ -139,6 +145,133 @@ const Conditional = ({
139
145
  // Wrapper component
140
146
  const WrapperComponent = wrapper;
141
147
 
148
+ // Switch-case logic
149
+ if (switchValue !== undefined) {
150
+ // Find all Case children
151
+ const caseChildren = React.Children.toArray(children).filter(
152
+ child => child && child.type === Case
153
+ );
154
+ // Find matching case
155
+ let match = null;
156
+ let defaultCase = null;
157
+ caseChildren.forEach(child => {
158
+ if (child.props.default) {
159
+ defaultCase = child;
160
+ } else if (child.props.when === switchValue) {
161
+ match = child;
162
+ }
163
+ });
164
+ if (match) {
165
+ return <WrapperComponent>{match.props.children}</WrapperComponent>;
166
+ } else if (defaultCase) {
167
+ return <WrapperComponent>{defaultCase.props.children}</WrapperComponent>;
168
+ } else {
169
+ return fallback;
170
+ }
171
+ }
172
+
173
+ // If-ElseIf-Else logic
174
+ const childrenArray = React.Children.toArray(children);
175
+ const ifElseBlocks = childrenArray.filter(child =>
176
+ child && (child.type === If || child.type === ElseIf || child.type === Else)
177
+ );
178
+ if (ifElseBlocks.length > 0) {
179
+ let rendered = null;
180
+ for (let i = 0; i < ifElseBlocks.length; i++) {
181
+ const child = ifElseBlocks[i];
182
+ // Extract Conditional props from child
183
+ const {
184
+ when,
185
+ each,
186
+ filter,
187
+ sort,
188
+ limit,
189
+ reverse,
190
+ animate,
191
+ wrapper: childWrapper,
192
+ keyExtractor: childKeyExtractor,
193
+ empty: childEmpty,
194
+ fallback: childFallback,
195
+ ...rest
196
+ } = child.props;
197
+
198
+ // Evaluate condition
199
+ let condition = true;
200
+ if (child.type === If || child.type === ElseIf) {
201
+ condition = Boolean(when);
202
+ }
203
+
204
+ // Array processing for each
205
+ let arrayItems = [];
206
+ if (each && Array.isArray(each)) {
207
+ arrayItems = [...each];
208
+ if (filter && typeof filter === 'function') {
209
+ arrayItems = arrayItems.filter(filter);
210
+ }
211
+ if (sort && typeof sort === 'function') {
212
+ arrayItems = arrayItems.sort(sort);
213
+ }
214
+ if (reverse) {
215
+ arrayItems = arrayItems.reverse();
216
+ }
217
+ if (limit && typeof limit === 'number') {
218
+ arrayItems = arrayItems.slice(0, limit);
219
+ }
220
+ }
221
+
222
+ // Render logic
223
+ if ((child.type === If || child.type === ElseIf) && condition) {
224
+ if (each && Array.isArray(each)) {
225
+ if (arrayItems.length === 0) {
226
+ rendered = childEmpty || childFallback || null;
227
+ break;
228
+ }
229
+ const elements = arrayItems.map((item, idx) => (
230
+ <React.Fragment key={childKeyExtractor ? childKeyExtractor(item, idx) : idx}>
231
+ {typeof child.props.children === 'function'
232
+ ? child.props.children(item, idx, arrayItems)
233
+ : child.props.children}
234
+ </React.Fragment>
235
+ ));
236
+ rendered = childWrapper
237
+ ? React.createElement(childWrapper, null, elements)
238
+ : <>{elements}</>;
239
+ break;
240
+ } else {
241
+ rendered = childWrapper
242
+ ? React.createElement(childWrapper, null, child.props.children)
243
+ : <>{child.props.children}</>;
244
+ break;
245
+ }
246
+ }
247
+ if (child.type === Else) {
248
+ if (each && Array.isArray(each)) {
249
+ if (arrayItems.length === 0) {
250
+ rendered = childEmpty || childFallback || null;
251
+ break;
252
+ }
253
+ const elements = arrayItems.map((item, idx) => (
254
+ <React.Fragment key={childKeyExtractor ? childKeyExtractor(item, idx) : idx}>
255
+ {typeof child.props.children === 'function'
256
+ ? child.props.children(item, idx, arrayItems)
257
+ : child.props.children}
258
+ </React.Fragment>
259
+ ));
260
+ rendered = childWrapper
261
+ ? React.createElement(childWrapper, null, elements)
262
+ : <>{elements}</>;
263
+ break;
264
+ } else {
265
+ rendered = childWrapper
266
+ ? React.createElement(childWrapper, null, child.props.children)
267
+ : <>{child.props.children}</>;
268
+ break;
269
+ }
270
+ }
271
+ }
272
+ return rendered;
273
+ }
274
+
142
275
  // Only condition
143
276
  if (hasCondition && !hasIteration) {
144
277
  return evaluateCondition ? (
package/Else.js ADDED
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+
3
+ const Else = ({ children, ...rest }) => {
4
+ // Marker for Conditional, supports all Conditional props
5
+ return <>{children}</>;
6
+ };
7
+
8
+ export default Else;
package/ElseIf.js ADDED
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+
3
+ const ElseIf = ({ when, children, ...rest }) => {
4
+ // Marker for Conditional, supports all Conditional props
5
+ return <>{children}</>;
6
+ };
7
+
8
+ export default ElseIf;
package/If.js ADDED
@@ -0,0 +1,8 @@
1
+ import React from 'react';
2
+
3
+ const If = ({ when, children, ...rest }) => {
4
+ // Marker for Conditional, supports all Conditional props
5
+ return <>{children}</>;
6
+ };
7
+
8
+ export default If;
package/README.md CHANGED
@@ -11,10 +11,12 @@ npm install react-ternary-be-gone
11
11
  yarn add react-ternary-be-gone
12
12
  ```
13
13
 
14
+
15
+
14
16
  ## Usage
15
17
 
16
18
  ```javascript
17
- import Conditional from 'react-ternary-be-gone';
19
+ import Conditional, { Case, If, ElseIf, Else } from 'react-ternary-be-gone';
18
20
 
19
21
  // Basic conditional rendering
20
22
  <Conditional when={true}>
@@ -35,6 +37,120 @@ const items = ['Item 1', 'Item 2', 'Item 3'];
35
37
  <Conditional each={items}>
36
38
  {(item, index) => <p key={index}>{item}</p>}
37
39
  </Conditional>
40
+
41
+ // Switch-case rendering
42
+ const value = 'b';
43
+
44
+ <Conditional switch={value}>
45
+ <Case when="a">A selected</Case>
46
+ <Case when="b">B selected</Case>
47
+ <Case default>None selected</Case>
48
+ </Conditional>
49
+
50
+ // If-ElseIf-Else rendering
51
+ const status = 'loading';
52
+
53
+ <Conditional>
54
+ <If when={status === 'loading'}>
55
+ <p>Loading...</p>
56
+ </If>
57
+ <ElseIf when={status === 'success'}>
58
+ <p>Success!</p>
59
+ </ElseIf>
60
+ <Else>
61
+ <p>Status unknown.</p>
62
+ </Else>
63
+ </Conditional>
64
+
65
+ // If-ElseIf-Else with advanced props
66
+ const users = [{ id: 1, name: 'Alice', active: true }, { id: 2, name: 'Bob', active: false }];
67
+
68
+ <Conditional>
69
+ <If when={users.length > 0} each={users} filter={user => user.active}>
70
+ {(user) => <p>{user.name}</p>}
71
+ </If>
72
+ <Else>
73
+ <p>No users found.</p>
74
+ </Else>
75
+ </Conditional>
76
+ ```
77
+ ### If-ElseIf-Else Blocks
78
+
79
+ You can use `<If>`, `<ElseIf>`, and `<Else>` as children of `<Conditional>` (without any prop on Conditional itself) to mimic if-else if-else logic. The first matching block is rendered. You can use all Conditional props (each, filter, sort, etc.) on these blocks.
80
+
81
+ **Example:**
82
+
83
+ ```javascript
84
+ import Conditional, { If, ElseIf, Else } from 'react-ternary-be-gone';
85
+
86
+ const status = 'success';
87
+
88
+ <Conditional>
89
+ <If when={status === 'loading'}>
90
+ <p>Yükleniyor...</p>
91
+ </If>
92
+ <ElseIf when={status === 'success'}>
93
+ <p>Başarılı!</p>
94
+ </ElseIf>
95
+ <Else>
96
+ <p>Durum bilinmiyor.</p>
97
+ </Else>
98
+ </Conditional>
99
+ ```
100
+
101
+ **Advanced Example (with array props):**
102
+
103
+ ```javascript
104
+ const users = [{ id: 1, name: 'Alice', active: true }, { id: 2, name: 'Bob', active: false }];
105
+
106
+ <Conditional>
107
+ <If when={users.length > 0} each={users} filter={user => user.active}>
108
+ {(user) => <p>{user.name}</p>}
109
+ </If>
110
+ <Else>
111
+ <p>Kullanıcı yok.</p>
112
+ </Else>
113
+ </Conditional>
114
+ ```
115
+
116
+ You can use multiple `<ElseIf>` blocks. The first matching block is rendered. All Conditional props (each, filter, sort, etc.) are supported on If/ElseIf/Else blocks.
117
+ ### `switch` (Switch-Case Rendering)
118
+
119
+ Allows you to use switch-case style rendering with `<Case>` children. The `switch` prop sets the value to match, and each `<Case when={...}>...</Case>` child is checked. If no match is found, `<Case default>...</Case>` is rendered if present.
120
+
121
+ **Type:** `any`
122
+
123
+ **Example:**
124
+
125
+ ```javascript
126
+ import Conditional, { Case } from 'react-ternary-be-gone';
127
+
128
+ const value = 'b';
129
+
130
+ <Conditional switch={value}>
131
+ <Case when="a">A seçildi</Case>
132
+ <Case when="b">B seçildi</Case>
133
+ <Case default>Hiçbiri seçilmedi</Case>
134
+ </Conditional>
135
+ ```
136
+
137
+ #### `<Case>`
138
+
139
+ Child component for use with `switch` prop. Use `when` for matching value, and `default` for the default case.
140
+
141
+ **Props:**
142
+
143
+ - `when`: Value to match against the `switch` prop.
144
+ - `default`: Boolean, renders if no other case matches.
145
+
146
+ **Example:**
147
+
148
+ ```javascript
149
+ <Conditional switch={status}>
150
+ <Case when="loading">Loading...</Case>
151
+ <Case when="success">Success!</Case>
152
+ <Case default>Status unknown.</Case>
153
+ </Conditional>
38
154
  ```
39
155
 
40
156
  ## Props
package/index.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import Conditional from './Conditional';
2
+ import Case from './Case';
3
+ import If from './If';
4
+ import ElseIf from './ElseIf';
5
+ import Else from './Else';
2
6
  import { useConditionalHelpers } from './useConditionalHelpers';
3
7
 
4
8
  export default Conditional;
5
- export { useConditionalHelpers };
9
+ export { Case, If, ElseIf, Else, useConditionalHelpers };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-ternary-be-gone",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A React component designed to simplify conditional rendering and list iteration, providing a more readable and maintainable alternative to ternary operators and verbose conditional logic.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -1,206 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _react = _interopRequireWildcard(require("react"));
8
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
9
- const Conditional = _ref => {
10
- let {
11
- when,
12
- each,
13
- children,
14
- fallback = null,
15
- empty = null,
16
- loading = false,
17
- error = null,
18
- keyExtractor = (item, index) => index,
19
- // New features
20
- filter = null,
21
- sort = null,
22
- limit = null,
23
- reverse = false,
24
- animate = false,
25
- wrapper = _react.default.Fragment,
26
- debug = false,
27
- onRender = null,
28
- // Conditional rendering helpers
29
- gt = null,
30
- // greater than
31
- lt = null,
32
- // less than
33
- eq = null,
34
- // equal
35
- ne = null,
36
- // not equal
37
- includes = null,
38
- startsWith = null,
39
- endsWith = null,
40
- match = null // regex match
41
- } = _ref;
42
- const hasCondition = when !== undefined;
43
- const hasIteration = each !== undefined;
44
-
45
- // Advanced condition evaluation
46
- const evaluateCondition = (0, _react.useMemo)(() => {
47
- if (when !== undefined) return Boolean(when);
48
-
49
- // Numerical comparisons
50
- if (gt !== null && typeof gt === 'object') {
51
- const {
52
- value,
53
- target
54
- } = gt;
55
- return value > target;
56
- }
57
- if (lt !== null && typeof lt === 'object') {
58
- const {
59
- value,
60
- target
61
- } = lt;
62
- return value < target;
63
- }
64
- if (eq !== null && typeof eq === 'object') {
65
- const {
66
- value,
67
- target
68
- } = eq;
69
- return value === target;
70
- }
71
- if (ne !== null && typeof ne === 'object') {
72
- const {
73
- value,
74
- target
75
- } = ne;
76
- return value !== target;
77
- }
78
-
79
- // String operations
80
- if (includes !== null && typeof includes === 'object') {
81
- const {
82
- value,
83
- target
84
- } = includes;
85
- return String(value).includes(target);
86
- }
87
- if (startsWith !== null && typeof startsWith === 'object') {
88
- const {
89
- value,
90
- target
91
- } = startsWith;
92
- return String(value).startsWith(target);
93
- }
94
- if (endsWith !== null && typeof endsWith === 'object') {
95
- const {
96
- value,
97
- target
98
- } = endsWith;
99
- return String(value).endsWith(target);
100
- }
101
- if (match !== null && typeof match === 'object') {
102
- const {
103
- value,
104
- pattern
105
- } = match;
106
- return new RegExp(pattern).test(String(value));
107
- }
108
- return true;
109
- }, [when, gt, lt, eq, ne, includes, startsWith, endsWith, match]);
110
-
111
- // Array processing
112
- const processedArray = (0, _react.useMemo)(() => {
113
- if (!hasIteration || !Array.isArray(each)) return [];
114
- let result = [...each];
115
-
116
- // Apply filter
117
- if (filter && typeof filter === 'function') {
118
- result = result.filter(filter);
119
- }
120
-
121
- // Apply sort
122
- if (sort && typeof sort === 'function') {
123
- result = result.sort(sort);
124
- }
125
-
126
- // Apply reverse
127
- if (reverse) {
128
- result = result.reverse();
129
- }
130
-
131
- // Apply limit
132
- if (limit && typeof limit === 'number') {
133
- result = result.slice(0, limit);
134
- }
135
- if (debug) {
136
- console.log('Conditional Debug:', {
137
- original: each,
138
- processed: result,
139
- filter: !!filter,
140
- sort: !!sort,
141
- reverse,
142
- limit
143
- });
144
- }
145
- return result;
146
- }, [each, filter, sort, reverse, limit, hasIteration, debug]);
147
-
148
- // Render callback
149
- (0, _react.useEffect)(() => {
150
- if (onRender && typeof onRender === 'function') {
151
- onRender({
152
- condition: evaluateCondition,
153
- itemCount: processedArray.length,
154
- hasCondition,
155
- hasIteration
156
- });
157
- }
158
- }, [evaluateCondition, processedArray.length, hasCondition, hasIteration, onRender]);
159
-
160
- // Loading state
161
- if (loading) {
162
- return fallback || /*#__PURE__*/_react.default.createElement("div", {
163
- className: "conditional-loading"
164
- }, "Loading...");
165
- }
166
-
167
- // Error state
168
- if (error) {
169
- return /*#__PURE__*/_react.default.createElement("div", {
170
- className: "conditional-error"
171
- }, "Error: ", error);
172
- }
173
-
174
- // Wrapper component
175
- const WrapperComponent = wrapper;
176
-
177
- // Only condition
178
- if (hasCondition && !hasIteration) {
179
- return evaluateCondition ? /*#__PURE__*/_react.default.createElement(WrapperComponent, null, children) : fallback;
180
- }
181
-
182
- // Only iteration
183
- if (!hasCondition && hasIteration) {
184
- if (processedArray.length === 0) {
185
- return empty || fallback;
186
- }
187
- const elements = processedArray.map((item, index) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
188
- key: keyExtractor(item, index)
189
- }, typeof children === 'function' ? children(item, index, processedArray) : children));
190
- return animate ? /*#__PURE__*/_react.default.createElement(WrapperComponent, {
191
- className: "conditional-animated"
192
- }, elements) : /*#__PURE__*/_react.default.createElement(WrapperComponent, null, elements);
193
- }
194
-
195
- // Both condition and iteration
196
- if (hasCondition && hasIteration) {
197
- if (!evaluateCondition) return fallback;
198
- if (processedArray.length === 0) return empty || fallback;
199
- const elements = processedArray.map((item, index) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
200
- key: keyExtractor(item, index)
201
- }, children(item, index, processedArray)));
202
- return /*#__PURE__*/_react.default.createElement(WrapperComponent, null, elements);
203
- }
204
- return /*#__PURE__*/_react.default.createElement(WrapperComponent, null, children);
205
- };
206
- var _default = exports.default = Conditional;
@@ -1,5 +0,0 @@
1
- "use strict";
2
-
3
- module.exports = {
4
- presets: ["@babel/preset-env", "@babel/preset-react"]
5
- };
package/dist/index.js DELETED
@@ -1,16 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- Object.defineProperty(exports, "useConditionalHelpers", {
8
- enumerable: true,
9
- get: function () {
10
- return _useConditionalHelpers.useConditionalHelpers;
11
- }
12
- });
13
- var _Conditional = _interopRequireDefault(require("./Conditional"));
14
- var _useConditionalHelpers = require("./useConditionalHelpers");
15
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
16
- var _default = exports.default = _Conditional.default;
@@ -1,53 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.useConditionalHelpers = void 0;
7
- var _react = require("react");
8
- const useConditionalHelpers = () => {
9
- return (0, _react.useMemo)(() => ({
10
- // Quick condition helpers
11
- isEmpty: array => ({
12
- when: !array || array.length === 0
13
- }),
14
- isNotEmpty: array => ({
15
- when: array && array.length > 0
16
- }),
17
- hasLength: (array, length) => ({
18
- when: array && array.length === length
19
- }),
20
- isEven: num => ({
21
- when: num % 2 === 0
22
- }),
23
- isOdd: num => ({
24
- when: num % 2 !== 0
25
- }),
26
- // Array processing helpers
27
- sortBy: function (field) {
28
- let order = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'asc';
29
- return (a, b) => {
30
- const aValue = a[field];
31
- const bValue = b[field];
32
- if (aValue < bValue) {
33
- return order === 'asc' ? -1 : 1;
34
- }
35
- if (aValue > bValue) {
36
- return order === 'asc' ? 1 : -1;
37
- }
38
- return 0;
39
- };
40
- },
41
- filterBy: (field, value) => item => item[field] === value,
42
- unique: (array, key) => {
43
- const seen = new Set();
44
- return array.filter(item => {
45
- const keyValue = typeof key === 'function' ? key(item) : item[key];
46
- const isNew = !seen.has(keyValue);
47
- seen.add(keyValue);
48
- return isNew;
49
- });
50
- }
51
- }), []);
52
- };
53
- exports.useConditionalHelpers = useConditionalHelpers;