Skip to content

Visualize Your Ideas With Code

feat(2d): add withDefaults helper (#982)

Jacob6bd072ad2275
diff --git a/packages/2d/src/lib/utils/index.ts b/packages/2d/src/lib/utils/index.ts
index 5847f637..b2f64ae4 100644
--- a/packages/2d/src/lib/utils/index.ts
+++ b/packages/2d/src/lib/utils/index.ts
@@ -1,2 +1,3 @@
export * from './CanvasUtils';
export * from './is';
+export * from './withDefaults';
diff --git a/packages/2d/src/lib/utils/withDefaults.tsx b/packages/2d/src/lib/utils/withDefaults.tsx
new file mode 100644
index 00000000..01a8826c
--- /dev/null
+++ b/packages/2d/src/lib/utils/withDefaults.tsx
@@ -0,0 +1,26 @@
+import {FunctionComponent, NodeConstructor, PropsOf} from '../components';
+
+/**
+ * Create a higher order component with default props.
+ *
+ * @example
+ * ```tsx
+ * const MyTxt = withDefaults(Txt, {
+ * fill: '#f3303f',
+ * });
+ *
+ * // ...
+ *
+ * view.add(<MyTxt>Hello, World!</MyTxt>);
+ * ```
+ *
+ * @param component - The base class or function component to wrap.
+ * @param defaults - The default props to apply.
+ */
+export function withDefaults<T extends FunctionComponent | NodeConstructor>(
+ component: T,
+ defaults: PropsOf<T>,
+) {
+ const Node = component;
+ return (props: PropsOf<T>) => <Node {...defaults} {...props} />;
+}