@futaba-soft/when 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 futaba-soft
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 CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # When
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A tiny library for generating declarative conditional-rendering components, inspired by [react-display-switch](https://www.npmjs.com/package/react-display-switch).
4
+
5
+ Generate `When` / `WhenNot` components from an arbitrary set of conditions, and combine them with `and` / `or` to toggle what is displayed.
6
+
7
+ - https://www.npmjs.com/package/@futaba-soft/when
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ npm install @futaba-soft/when
13
+ ```
14
+
15
+ `react` (>=18) is a peer dependency.
16
+
17
+ ## Usage
18
+
19
+ ```tsx
20
+ import { useState } from 'react'
21
+ import { createWhen } from '@futaba-soft/when'
22
+
23
+ // A trivial "store". Conditions are plain `() => boolean` predicates,
24
+ // so they can read from anywhere in scope.
25
+ const store = { user: null as { role: string } | null }
26
+
27
+ // Register your conditions once.
28
+ const { When, WhenNot } = createWhen({
29
+ isLoggedIn: () => store.user !== null,
30
+ isAdmin: () => store.user?.role === 'admin',
31
+ })
32
+
33
+ const App = () => {
34
+ // Conditions are re-evaluated on every render, so trigger a re-render
35
+ // (here via state) after the data they read changes.
36
+ const [, forceRender] = useState(0)
37
+ const signInAsAdmin = () => {
38
+ store.user = { role: 'admin' }
39
+ forceRender((n) => n + 1)
40
+ }
41
+
42
+ return (
43
+ <>
44
+ <When isLoggedIn>Welcome back!</When>
45
+ <WhenNot isLoggedIn>
46
+ <button onClick={signInAsAdmin}>Sign in</button>
47
+ </WhenNot>
48
+
49
+ {/* Multiple conditions require an explicit `and` / `or` */}
50
+ <When isLoggedIn and isAdmin>
51
+ Admin dashboard
52
+ </When>
53
+ </>
54
+ )
55
+ }
56
+ ```
57
+
58
+ Case props are boolean flags — write `<When isLoggedIn>` (equivalent to `isLoggedIn={true}`). You can also read a condition's current value directly with `When.case('isLoggedIn')`.
59
+
60
+ ## API
61
+
62
+ - `createWhen(cases)` — build `{ When, WhenNot }` from a condition map. Requires at least one condition.
63
+ - `When` / `WhenNot` — show / hide children based on the conditions. `WhenNot` renders the logical negation of `When`.
64
+ - Passing multiple conditions requires an explicit `and` or `or` (they are mutually exclusive).
65
+ - `When.case(label)` returns the condition's current boolean; `When.cases` exposes the (frozen) registered map.
66
+ - `children`, `and`, `or` are reserved and cannot be used as condition labels.
67
+
68
+ ## Behavior & limitations
69
+
70
+ - **Evaluated on render, not subscribed.** Conditions are re-run every time the component renders; the library does not subscribe to external sources. To reflect a change (viewport size, store, etc.), make sure something triggers a re-render, and keep predicates side-effect-free and cheap. For viewport-based conditions, read from React state fed by a listener rather than calling `window.matchMedia` directly inside a predicate (which is also not SSR-safe).
71
+ - **Flat, single operator only.** You can express `a and b and c` or `a or b or c`, but not mixed logic like `(a and b) or c`. Compose complex conditions in `createWhen` instead, e.g. `phonePortrait: () => isPhone() && isPortrait()`.
72
+ - **`true`-only flags.** Case props and `and` / `or` accept only `true` (or omission); the types reject non-`true` values at compile time. Passing a non-`true` value to a case prop throws at runtime. For `and` / `or`, a non-`true` value is treated as "not specified" (so multiple cases without an effective operator still throw "must specify an operator").
73
+
74
+ ## Development
75
+
76
+ ```sh
77
+ npm run typecheck # type check (includes *.test-d.tsx type tests)
78
+ npm test # tests (vitest)
79
+ npm run lint # lint / format check (biome)
80
+ npm run format # auto-fix
81
+ npm run build # generate dist (tsup)
82
+ ```
83
+
84
+ ## License
85
+
86
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ // src/When.tsx
6
+ var reservedWords = ["children", "or", "and"];
7
+ var filterCaseLabel = (labels) => labels.filter((label) => !reservedWords.includes(label));
8
+ var isReservedWord = (label) => reservedWords.includes(label);
9
+ var hasOwn = (props, key) => Object.getOwnPropertyDescriptor(props, key) !== void 0;
10
+ var createWhen = (cases) => {
11
+ const frozenCases = Object.freeze({ ...cases });
12
+ if (Object.keys(frozenCases).length === 0) {
13
+ throw new Error("at least one case must be registered.");
14
+ }
15
+ for (const [label, condition] of Object.entries(frozenCases)) {
16
+ if (isReservedWord(label)) {
17
+ throw new Error(`label "${label}" is reserved.`);
18
+ }
19
+ if (typeof condition !== "function") {
20
+ throw new Error("condition must be a function.");
21
+ }
22
+ }
23
+ const resolveCase = (label) => {
24
+ if (!hasOwn(frozenCases, label)) {
25
+ throw new Error(`label "${label}" is not registered.`);
26
+ }
27
+ return frozenCases[label]();
28
+ };
29
+ const renderChildren = (children) => children === void 0 || children === null ? null : react.createElement(react.Fragment, null, children);
30
+ const validateProps = (props) => {
31
+ const hasAnd = hasOwn(props, "and") && props.and === true;
32
+ const hasOr = hasOwn(props, "or") && props.or === true;
33
+ if (hasAnd && hasOr) {
34
+ throw new Error('must not use "and" with "or".');
35
+ }
36
+ const labels = filterCaseLabel(Object.keys(props));
37
+ if (labels.length === 0) {
38
+ throw new Error("at least one case is required.");
39
+ }
40
+ for (const label of labels) {
41
+ if (hasOwn(frozenCases, label) && props[label] !== true) {
42
+ throw new Error(`case "${label}" prop must be true or omitted.`);
43
+ }
44
+ }
45
+ if (labels.length > 1 && !hasAnd && !hasOr) {
46
+ throw new Error('must specify "and" or "or" operator.');
47
+ }
48
+ return { labels, operator: hasOr ? "or" : hasAnd ? "and" : void 0 };
49
+ };
50
+ const attachCaseApi = (component) => Object.defineProperties(component, {
51
+ cases: { value: frozenCases, enumerable: true },
52
+ case: {
53
+ value: (label) => resolveCase(label),
54
+ enumerable: true
55
+ }
56
+ });
57
+ const When = attachCaseApi((props) => {
58
+ const { labels, operator } = validateProps(props);
59
+ for (const label of labels) {
60
+ if (operator === "or") {
61
+ if (resolveCase(label)) {
62
+ return renderChildren(props.children);
63
+ }
64
+ } else if (!resolveCase(label)) {
65
+ return null;
66
+ }
67
+ }
68
+ if (operator === "or") {
69
+ return null;
70
+ }
71
+ return renderChildren(props.children);
72
+ });
73
+ const WhenNot = attachCaseApi((props) => {
74
+ const { labels, operator } = validateProps(props);
75
+ for (const label of labels) {
76
+ if (operator === "or") {
77
+ if (resolveCase(label)) {
78
+ return null;
79
+ }
80
+ } else if (!resolveCase(label)) {
81
+ return renderChildren(props.children);
82
+ }
83
+ }
84
+ if (operator === "or") {
85
+ return renderChildren(props.children);
86
+ }
87
+ return null;
88
+ });
89
+ return { When, WhenNot };
90
+ };
91
+
92
+ exports.createWhen = createWhen;
93
+ //# sourceMappingURL=index.cjs.map
94
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/When.tsx"],"names":["createElement","Fragment"],"mappings":";;;;;AAGA,IAAM,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OAAO,cAAA,CAAe,MAAM,QAAQ,CAAA;AAAA,MACtC;AAAA,IACF;AAEA,IAAA,IAAI,aAAa,IAAA,EAAM;AACrB,MAAA,OAAO,cAAA,CAAe,MAAM,QAAQ,CAAA;AAAA,IACtC;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA;AAED,EAAA,OAAO,EAAE,MAAM,OAAA,EAAQ;AACzB","file":"index.cjs","sourcesContent":["import type { ReactElement, ReactNode } from 'react'\nimport { createElement, Fragment } from 'react'\n\nconst reservedWords = ['children', 'or', 'and'] as const\n\ntype ReservedWord = (typeof reservedWords)[number]\ntype Condition = () => boolean\ntype ConditionMap = Record<string, Condition>\ntype CaseLabel<Cases extends ConditionMap> = Extract<keyof Cases, string>\n\ntype OperatorProps =\n | { and?: never; or?: never }\n | { and: true; or?: never }\n | { or: true; and?: never }\n\nexport type WhenProps<Cases extends ConditionMap> = Partial<\n Record<CaseLabel<Cases>, true>\n> & { children?: ReactNode } & OperatorProps\n\nexport type WhenComponent<Cases extends ConditionMap> = {\n (props: WhenProps<Cases>): ReactElement | null\n readonly cases: Readonly<Cases>\n readonly case: (label: CaseLabel<Cases>) => boolean\n}\n\nexport type CreateWhenResult<Cases extends ConditionMap> = {\n When: WhenComponent<Cases>\n WhenNot: WhenComponent<Cases>\n}\n\nconst filterCaseLabel = (labels: string[]): string[] =>\n labels.filter((label) => !reservedWords.includes(label as ReservedWord))\n\nconst isReservedWord = (label: string): label is ReservedWord =>\n reservedWords.includes(label as ReservedWord)\n\nconst hasOwn = (props: object, key: PropertyKey): boolean =>\n Object.getOwnPropertyDescriptor(props, key) !== undefined\n\nexport const createWhen = <Cases extends ConditionMap>(\n cases: Cases,\n): CreateWhenResult<Cases> => {\n // Build the frozen copy first, then validate it, so the validated object and\n // the one read at render time are the same snapshot (stable even for cases\n // with getters).\n const frozenCases = Object.freeze({ ...cases })\n\n if (Object.keys(frozenCases).length === 0) {\n throw new Error('at least one case must be registered.')\n }\n\n for (const [label, condition] of Object.entries(frozenCases)) {\n if (isReservedWord(label)) {\n throw new Error(`label \"${label}\" is reserved.`)\n }\n if (typeof condition !== 'function') {\n throw new Error('condition must be a function.')\n }\n }\n\n const resolveCase = (label: string): boolean => {\n // The hasOwn guard prevents Object.prototype keys (e.g. toString) from\n // being run as if they were registered conditions.\n if (!hasOwn(frozenCases, label)) {\n throw new Error(`label \"${label}\" is not registered.`)\n }\n // biome-ignore lint/style/noNonNullAssertion: hasOwn and createWhen validation guarantee this exists.\n return frozenCases[label]!()\n }\n\n const renderChildren = (children: ReactNode): ReactElement | null =>\n children === undefined || children === null\n ? null\n : createElement(Fragment, null, children)\n\n const validateProps = (\n props: WhenProps<Cases>,\n ): { labels: string[]; operator: 'and' | 'or' | undefined } => {\n // Only treat an operator as set when it is an own property equal to true,\n // so an inherited and/or cannot silently bypass the operator-required guard.\n const hasAnd = hasOwn(props, 'and') && props.and === true\n const hasOr = hasOwn(props, 'or') && props.or === true\n\n if (hasAnd && hasOr) {\n throw new Error('must not use \"and\" with \"or\".')\n }\n\n const labels = filterCaseLabel(Object.keys(props))\n if (labels.length === 0) {\n throw new Error('at least one case is required.')\n }\n\n for (const label of labels) {\n if (\n hasOwn(frozenCases, label) &&\n props[label as CaseLabel<Cases>] !== true\n ) {\n throw new Error(`case \"${label}\" prop must be true or omitted.`)\n }\n }\n\n if (labels.length > 1 && !hasAnd && !hasOr) {\n throw new Error('must specify \"and\" or \"or\" operator.')\n }\n\n return { labels, operator: hasOr ? 'or' : hasAnd ? 'and' : undefined }\n }\n\n const attachCaseApi = (\n component: (props: WhenProps<Cases>) => ReactElement | null,\n ): WhenComponent<Cases> =>\n Object.defineProperties(component, {\n cases: { value: frozenCases, enumerable: true },\n case: {\n value: (label: CaseLabel<Cases>) => resolveCase(label),\n enumerable: true,\n },\n }) as WhenComponent<Cases>\n\n const When = attachCaseApi((props) => {\n const { labels, operator } = validateProps(props)\n\n for (const label of labels) {\n if (operator === 'or') {\n if (resolveCase(label)) {\n return renderChildren(props.children)\n }\n } else if (!resolveCase(label)) {\n return null\n }\n }\n\n if (operator === 'or') {\n return null\n }\n return renderChildren(props.children)\n })\n\n const WhenNot = attachCaseApi((props) => {\n const { labels, operator } = validateProps(props)\n\n for (const label of labels) {\n if (operator === 'or') {\n if (resolveCase(label)) {\n return null\n }\n } else if (!resolveCase(label)) {\n return renderChildren(props.children)\n }\n }\n\n if (operator === 'or') {\n return renderChildren(props.children)\n }\n return null\n })\n\n return { When, WhenNot }\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+
3
+ type Condition = () => boolean;
4
+ type ConditionMap = Record<string, Condition>;
5
+ type CaseLabel<Cases extends ConditionMap> = Extract<keyof Cases, string>;
6
+ type OperatorProps = {
7
+ and?: never;
8
+ or?: never;
9
+ } | {
10
+ and: true;
11
+ or?: never;
12
+ } | {
13
+ or: true;
14
+ and?: never;
15
+ };
16
+ type WhenProps<Cases extends ConditionMap> = Partial<Record<CaseLabel<Cases>, true>> & {
17
+ children?: ReactNode;
18
+ } & OperatorProps;
19
+ type WhenComponent<Cases extends ConditionMap> = {
20
+ (props: WhenProps<Cases>): ReactElement | null;
21
+ readonly cases: Readonly<Cases>;
22
+ readonly case: (label: CaseLabel<Cases>) => boolean;
23
+ };
24
+ type CreateWhenResult<Cases extends ConditionMap> = {
25
+ When: WhenComponent<Cases>;
26
+ WhenNot: WhenComponent<Cases>;
27
+ };
28
+ declare const createWhen: <Cases extends ConditionMap>(cases: Cases) => CreateWhenResult<Cases>;
29
+
30
+ export { type CreateWhenResult, type WhenComponent, type WhenProps, createWhen };
@@ -0,0 +1,30 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+
3
+ type Condition = () => boolean;
4
+ type ConditionMap = Record<string, Condition>;
5
+ type CaseLabel<Cases extends ConditionMap> = Extract<keyof Cases, string>;
6
+ type OperatorProps = {
7
+ and?: never;
8
+ or?: never;
9
+ } | {
10
+ and: true;
11
+ or?: never;
12
+ } | {
13
+ or: true;
14
+ and?: never;
15
+ };
16
+ type WhenProps<Cases extends ConditionMap> = Partial<Record<CaseLabel<Cases>, true>> & {
17
+ children?: ReactNode;
18
+ } & OperatorProps;
19
+ type WhenComponent<Cases extends ConditionMap> = {
20
+ (props: WhenProps<Cases>): ReactElement | null;
21
+ readonly cases: Readonly<Cases>;
22
+ readonly case: (label: CaseLabel<Cases>) => boolean;
23
+ };
24
+ type CreateWhenResult<Cases extends ConditionMap> = {
25
+ When: WhenComponent<Cases>;
26
+ WhenNot: WhenComponent<Cases>;
27
+ };
28
+ declare const createWhen: <Cases extends ConditionMap>(cases: Cases) => CreateWhenResult<Cases>;
29
+
30
+ export { type CreateWhenResult, type WhenComponent, type WhenProps, createWhen };
package/dist/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import { createElement, Fragment } from 'react';
2
+
3
+ // src/When.tsx
4
+ var reservedWords = ["children", "or", "and"];
5
+ var filterCaseLabel = (labels) => labels.filter((label) => !reservedWords.includes(label));
6
+ var isReservedWord = (label) => reservedWords.includes(label);
7
+ var hasOwn = (props, key) => Object.getOwnPropertyDescriptor(props, key) !== void 0;
8
+ var createWhen = (cases) => {
9
+ const frozenCases = Object.freeze({ ...cases });
10
+ if (Object.keys(frozenCases).length === 0) {
11
+ throw new Error("at least one case must be registered.");
12
+ }
13
+ for (const [label, condition] of Object.entries(frozenCases)) {
14
+ if (isReservedWord(label)) {
15
+ throw new Error(`label "${label}" is reserved.`);
16
+ }
17
+ if (typeof condition !== "function") {
18
+ throw new Error("condition must be a function.");
19
+ }
20
+ }
21
+ const resolveCase = (label) => {
22
+ if (!hasOwn(frozenCases, label)) {
23
+ throw new Error(`label "${label}" is not registered.`);
24
+ }
25
+ return frozenCases[label]();
26
+ };
27
+ const renderChildren = (children) => children === void 0 || children === null ? null : createElement(Fragment, null, children);
28
+ const validateProps = (props) => {
29
+ const hasAnd = hasOwn(props, "and") && props.and === true;
30
+ const hasOr = hasOwn(props, "or") && props.or === true;
31
+ if (hasAnd && hasOr) {
32
+ throw new Error('must not use "and" with "or".');
33
+ }
34
+ const labels = filterCaseLabel(Object.keys(props));
35
+ if (labels.length === 0) {
36
+ throw new Error("at least one case is required.");
37
+ }
38
+ for (const label of labels) {
39
+ if (hasOwn(frozenCases, label) && props[label] !== true) {
40
+ throw new Error(`case "${label}" prop must be true or omitted.`);
41
+ }
42
+ }
43
+ if (labels.length > 1 && !hasAnd && !hasOr) {
44
+ throw new Error('must specify "and" or "or" operator.');
45
+ }
46
+ return { labels, operator: hasOr ? "or" : hasAnd ? "and" : void 0 };
47
+ };
48
+ const attachCaseApi = (component) => Object.defineProperties(component, {
49
+ cases: { value: frozenCases, enumerable: true },
50
+ case: {
51
+ value: (label) => resolveCase(label),
52
+ enumerable: true
53
+ }
54
+ });
55
+ const When = attachCaseApi((props) => {
56
+ const { labels, operator } = validateProps(props);
57
+ for (const label of labels) {
58
+ if (operator === "or") {
59
+ if (resolveCase(label)) {
60
+ return renderChildren(props.children);
61
+ }
62
+ } else if (!resolveCase(label)) {
63
+ return null;
64
+ }
65
+ }
66
+ if (operator === "or") {
67
+ return null;
68
+ }
69
+ return renderChildren(props.children);
70
+ });
71
+ const WhenNot = attachCaseApi((props) => {
72
+ const { labels, operator } = validateProps(props);
73
+ for (const label of labels) {
74
+ if (operator === "or") {
75
+ if (resolveCase(label)) {
76
+ return null;
77
+ }
78
+ } else if (!resolveCase(label)) {
79
+ return renderChildren(props.children);
80
+ }
81
+ }
82
+ if (operator === "or") {
83
+ return renderChildren(props.children);
84
+ }
85
+ return null;
86
+ });
87
+ return { When, WhenNot };
88
+ };
89
+
90
+ export { createWhen };
91
+ //# sourceMappingURL=index.js.map
92
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/When.tsx"],"names":[],"mappings":";;;AAGA,IAAM,aAAA,GAAgB,CAAC,UAAA,EAAY,IAAA,EAAM,KAAK,CAAA;AA2B9C,IAAM,eAAA,GAAkB,CAAC,MAAA,K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B,MAAA,OAAO,cAAA,CAAe,MAAM,QAAQ,CAAA;AAAA,IACtC;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA;AAED,EAAA,OAAO,EAAE,MAAM,OAAA,EAAQ;AACzB","file":"index.js","sourcesContent":["import type { ReactElement, ReactNode } from 'react'\nimport { createElement, Fragment } from 'react'\n\nconst reservedWords = ['children', 'or', 'and'] as const\n\ntype ReservedWord = (typeof reservedWords)[number]\ntype Condition = () => boolean\ntype ConditionMap = Record<string, Condition>\ntype CaseLabel<Cases extends ConditionMap> = Extract<keyof Cases, string>\n\ntype OperatorProps =\n | { and?: never; or?: never }\n | { and: true; or?: never }\n | { or: true; and?: never }\n\nexport type WhenProps<Cases extends ConditionMap> = Partial<\n Record<CaseLabel<Cases>, true>\n> & { children?: ReactNode } & OperatorProps\n\nexport type WhenComponent<Cases extends ConditionMap> = {\n (props: WhenProps<Cases>): ReactElement | null\n readonly cases: Readonly<Cases>\n readonly case: (label: CaseLabel<Cases>) => boolean\n}\n\nexport type CreateWhenResult<Cases extends ConditionMap> = {\n When: WhenComponent<Cases>\n WhenNot: WhenComponent<Cases>\n}\n\nconst filterCaseLabel = (labels: string[]): string[] =>\n labels.filter((label) => !reservedWords.includes(label as ReservedWord))\n\nconst isReservedWord = (label: string): label is ReservedWord =>\n reservedWords.includes(label as ReservedWord)\n\nconst hasOwn = (props: object, key: PropertyKey): boolean =>\n Object.getOwnPropertyDescriptor(props, key) !== undefined\n\nexport const createWhen = <Cases extends ConditionMap>(\n cases: Cases,\n): CreateWhenResult<Cases> => {\n // Build the frozen copy first, then validate it, so the validated object and\n // the one read at render time are the same snapshot (stable even for cases\n // with getters).\n const frozenCases = Object.freeze({ ...cases })\n\n if (Object.keys(frozenCases).length === 0) {\n throw new Error('at least one case must be registered.')\n }\n\n for (const [label, condition] of Object.entries(frozenCases)) {\n if (isReservedWord(label)) {\n throw new Error(`label \"${label}\" is reserved.`)\n }\n if (typeof condition !== 'function') {\n throw new Error('condition must be a function.')\n }\n }\n\n const resolveCase = (label: string): boolean => {\n // The hasOwn guard prevents Object.prototype keys (e.g. toString) from\n // being run as if they were registered conditions.\n if (!hasOwn(frozenCases, label)) {\n throw new Error(`label \"${label}\" is not registered.`)\n }\n // biome-ignore lint/style/noNonNullAssertion: hasOwn and createWhen validation guarantee this exists.\n return frozenCases[label]!()\n }\n\n const renderChildren = (children: ReactNode): ReactElement | null =>\n children === undefined || children === null\n ? null\n : createElement(Fragment, null, children)\n\n const validateProps = (\n props: WhenProps<Cases>,\n ): { labels: string[]; operator: 'and' | 'or' | undefined } => {\n // Only treat an operator as set when it is an own property equal to true,\n // so an inherited and/or cannot silently bypass the operator-required guard.\n const hasAnd = hasOwn(props, 'and') && props.and === true\n const hasOr = hasOwn(props, 'or') && props.or === true\n\n if (hasAnd && hasOr) {\n throw new Error('must not use \"and\" with \"or\".')\n }\n\n const labels = filterCaseLabel(Object.keys(props))\n if (labels.length === 0) {\n throw new Error('at least one case is required.')\n }\n\n for (const label of labels) {\n if (\n hasOwn(frozenCases, label) &&\n props[label as CaseLabel<Cases>] !== true\n ) {\n throw new Error(`case \"${label}\" prop must be true or omitted.`)\n }\n }\n\n if (labels.length > 1 && !hasAnd && !hasOr) {\n throw new Error('must specify \"and\" or \"or\" operator.')\n }\n\n return { labels, operator: hasOr ? 'or' : hasAnd ? 'and' : undefined }\n }\n\n const attachCaseApi = (\n component: (props: WhenProps<Cases>) => ReactElement | null,\n ): WhenComponent<Cases> =>\n Object.defineProperties(component, {\n cases: { value: frozenCases, enumerable: true },\n case: {\n value: (label: CaseLabel<Cases>) => resolveCase(label),\n enumerable: true,\n },\n }) as WhenComponent<Cases>\n\n const When = attachCaseApi((props) => {\n const { labels, operator } = validateProps(props)\n\n for (const label of labels) {\n if (operator === 'or') {\n if (resolveCase(label)) {\n return renderChildren(props.children)\n }\n } else if (!resolveCase(label)) {\n return null\n }\n }\n\n if (operator === 'or') {\n return null\n }\n return renderChildren(props.children)\n })\n\n const WhenNot = attachCaseApi((props) => {\n const { labels, operator } = validateProps(props)\n\n for (const label of labels) {\n if (operator === 'or') {\n if (resolveCase(label)) {\n return null\n }\n } else if (!resolveCase(label)) {\n return renderChildren(props.children)\n }\n }\n\n if (operator === 'or') {\n return renderChildren(props.children)\n }\n return null\n })\n\n return { When, WhenNot }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@futaba-soft/when",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "react-display-switch に倣って作った、宣言的な条件表示コンポーネントを生成するライブラリ",
5
+ "keywords": [
6
+ "react",
7
+ "conditional",
8
+ "display",
9
+ "switch",
10
+ "responsive"
11
+ ],
12
+ "type": "module",
13
+ "main": "./dist/index.cjs",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "sideEffects": false,
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsup",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest run",
34
+ "test:watch": "vitest",
35
+ "lint": "biome check .",
36
+ "format": "biome check --write .",
37
+ "prepublishOnly": "npm run typecheck && npm run test && npm run build"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=18"
41
+ },
42
+ "devDependencies": {
43
+ "@biomejs/biome": "^2.0.0",
44
+ "@types/node": "^22.20.1",
45
+ "@types/react": "^19.0.0",
46
+ "@types/react-dom": "^19.0.0",
47
+ "react": "^19.0.0",
48
+ "react-dom": "^19.0.0",
49
+ "tsup": "^8.0.0",
50
+ "typescript": "^5.6.0",
51
+ "vitest": "^3.0.0"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+ssh://git@github.com/futaba-soft/When.git"
56
+ },
57
+ "author": "futaba-soft",
58
+ "license": "MIT",
59
+ "bugs": {
60
+ "url": "https://github.com/futaba-soft/When/issues"
61
+ },
62
+ "homepage": "https://github.com/futaba-soft/When#readme"
63
+ }