Skip to content

Commit

Permalink
Merge pull request #9 from gisce/add-json-checkbox-group
Browse files Browse the repository at this point in the history
Add a new widget JSONCheckbox
  • Loading branch information
mguellsegarra authored Jul 7, 2024
2 parents 5f5707a + d669324 commit ec5b93e
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/components/widgets/JSONCheckbox/JSONCheckbox.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from "react";
import { StoryFn, Meta } from "@storybook/react";
import { JSONCheckbox } from ".";

export default {
title: "Work in progress/Widgets/JSONCheckbox/JSONCheckbox",
component: JSONCheckbox,
} as Meta<typeof JSONCheckbox>;

const Template: StoryFn<typeof JSONCheckbox> = (args: any) => (
<JSONCheckbox {...args} onChange={(value) => console.log("value", value)} />
);

export const Basic = Template.bind({});
Basic.args = {
value: { option_1: false, option_2: true, option_3: false },
};

export const ReadOnly = Template.bind({});
ReadOnly.args = {
value: { option_1: false, option_2: true, option_3: false },
readOnly: true,
};
48 changes: 48 additions & 0 deletions src/components/widgets/JSONCheckbox/JSONCheckbox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { useState } from "react";
import { BaseFieldProps } from "@/components/form";
import { Checkbox } from "antd";

const humanizeLabel = (key: string): string => {
return (
key
// Reemplaça guions baixos i guions amb espais
.replace(/[_-]+/g, " ")
// Converteix a majúscules la primera lletra de cada paraula
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ")
);
};

export const JSONCheckbox = (
props: BaseFieldProps<Record<string, boolean>>,
) => {
const { readOnly } = props;
const [values, setValues] = useState(props.value || {});

const handleChange = (key: string) => {
const newValues = {
...values,
[key]: !values[key],
};
setValues(newValues);
if (props.onChange) {
props.onChange(newValues);
}
};

return (
<div>
{Object.keys(values).map((key) => (
<Checkbox
disabled={readOnly}
key={key}
checked={values[key]}
onChange={() => handleChange(key)}
>
{humanizeLabel(key)}
</Checkbox>
))}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/widgets/JSONCheckbox/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./JSONCheckbox";

0 comments on commit ec5b93e

Please sign in to comment.