lodash#clone JavaScript Examples

The following examples show how to use lodash#clone. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Slider.jsx    From kube-design with MIT License 6 votes vote down vote up
getStateFromProps() {
    const { unit, range, min, value: _value, defaultValue } = this.props;
    let value = clone(!isUndefined(_value) ? _value : defaultValue);

    let left;
    let right;
    let stateValue;

    if (range) {
      if (!value) {
        value = [min, min];
      } else {
        value[0] = Number(String(value[0]).replace(unit, ""));
        value[1] = Number(String(value[1]).replace(unit, ""));
      }
      left = this.getValuePercent(value[0]) * 100;
      right = this.getValuePercent(value[1]) * 100;
      stateValue = value;
    } else {
      if (!value) {
        value = min;
      } else {
        value = Number(String(value).replace(unit, ""));
      }
      left = 0;
      right = this.getValuePercent(value) * 100;
      stateValue = [min, value];
    }

    return { left, right, value: stateValue, originValue: _value };
  }
Example #2
Source File: createDropComponent.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
/**
 * 创建一个 DropComponent 包装组件
 * @param {{dropAcceptTypes: string | string[], drop: Function}} - 配置
 * @param {string|string[]} [dropAcceptTypes=[DragType.dragField, DragType.drawDragComponent]] - 接收 drop 的类型
 * @param {Function} drop - 触发drop后的回调方法
 */
export default function createDropComponent({
  dropAcceptTypes = [DragType.dragField, DragType.drawDragComponent],
  drop = defaultDrop,
} = {}) {
  const dropComponentSpec = {
    drop,
  };

  const dropComponentCollect = (connect, monitor) => {
    const connectDropTarget = connect.dropTarget();
    const isOver = monitor.isOver();
    return {
      connectDropTarget,
      isOver,
    };
  };

  // drop component only accepts dragField, dragComponent and drawDragComponent

  @DropTarget(dropAcceptTypes, dropComponentSpec, dropComponentCollect)
  class DropComponent extends React.Component {
    render() {
      const {
        component = {},
        connectDropTarget,
        currentEditComponent,
        currentEditField,
        children,
      } = this.props;
      const config = clone(component);
      const configProps = {};
      forEach(config.props, prop => {
        configProps[prop[attributeNameProp]] = prop[attributeValueProp];
      });
      delete config.props;
      Object.assign(config, configProps);

      const dropComponentClassNames = [styles['drop-component']];

      if (!currentEditField && currentEditComponent === component) {
        dropComponentClassNames.push(styles['drop-component-active']);
      }
      /**
       * notice
       * 字段布局 和 字段 之间包一层 DrawDrag 和 Drop
       */
      return (
        connectDropTarget &&
        connectDropTarget(
          <div className={dropComponentClassNames.join(' ')}>
            {isEmpty(component.fields) ? '拖入组件' : children}
          </div>
        )
      );
    }
  }
  return DropComponent;
}
Example #3
Source File: Integrations.js    From gutenberg-forms with GNU General Public License v2.0 5 votes vote down vote up
function Integrations(props) {
	const integrations = get(window, "cwpGlobal.settings.integrations");
	const savedIntegrations = props.data.attributes.integrations;
	const { actions } = props.data.attributes;

	// responsible for keeping the form actions and integrations synchronized
	useEffect(() => {
		each(savedIntegrations, (integration, name) => {
			const title = get(integrations[name], "title");
			const hasActionOfCurrentIntegration = includes(actions, title); // checking if the action has current integration

			if (!hasActionOfCurrentIntegration) {
				const newIntegrations = clone(savedIntegrations);
				const withoutCurrentIntegrations = omit(newIntegrations, [name]); // deleting the current integration from the list

				props.data.setAttributes({ integrations: withoutCurrentIntegrations });
			}
		});
	}, [actions]);

	useEffect(() => {
		each(integrations, (integration, name) => {
			const title = get(integration, "title");
			const hasActionOfCurrentIntegration = includes(actions, title); // checking if the action has current integration
			const isAllFieldIntegration = get(integration, "include_all_fields");

			if (isAllFieldIntegration && hasActionOfCurrentIntegration === true) {
				// if this integration support all field then the field plotter will be hidden
				// therefore updating the integration attribute manually

				const newIntegrations = clone(savedIntegrations);
				set(newIntegrations, name, new Object());
				props.data.setAttributes({ integrations: newIntegrations });
			}
		});
	}, [actions]);

	return (
		<Fragment>
			{map(integrations, (integration, name) => {
				const api_fields = get(integration, "api_fields"),
					query_fields = get(integration, "query_fields"),
					title = get(integration, "title"),
					enable = get(integration, "enable"),
					fields = get(integration, "fields"),
					type = get(integration, "type"),
					include_all_fields = get(integration, "include_all_fields");
				if (
					enable &&
					actions.includes(title) &&
					isEqual(type, "autoResponder") &&
					!include_all_fields
				) {
					return (
						<PanelBody title={__(title, "cwp-gutenberg-forms")}>
							<FieldPlotter
								fields={fields}
								title={title}
								name={name}
								data={props.data}
								clientId={props.clientId}
								api_fields={api_fields}
								query_fields={query_fields}
							/>
						</PanelBody>
					);
				}
			})}
		</Fragment>
	);
}
Example #4
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let name = e.target.value;

		props.setAttributes({ name });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		name,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty, invalidName },
		messages,
		pattern,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("name", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "name"),
					default: extract_admin_id(newFieldName, "name"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"name",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"name",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "name");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Prefix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Suffix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<Fragment>
							<div className="cwp-option">
								<h3 className="cwp-heading">
									{__("Required Text", "cwp-gutenberg-forms")}
								</h3>
								<TextControl
									onChange={(label) =>
										props.setAttributes({ requiredLabel: label })
									}
									value={requiredLabel}
								/>
							</div>
						</Fragment>
					)}
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Name Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalidName", v)}
							value={invalidName}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-name cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}
			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					<input value={name} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
		</div>,
	];
}
Example #5
Source File: sessionStorage.test.js    From skeletor with MIT License 4 votes vote down vote up
describe('browserStorage Collection using sessionStorage', function () {
    beforeEach(() => sessionStorage.clear());

    it('saves to sessionStorage', function () {
        const mySavedCollection = new SavedCollection();
        mySavedCollection.create(attributes);
        expect(mySavedCollection.length).to.equal(1);
    });

    it('saves to sessionStorage when wait=true', async function () {
        const mySavedCollection = new SavedCollection();
        await new Promise(success => mySavedCollection.create(attributes, {'wait': true, success}));
        expect(mySavedCollection.length).to.equal(1);
        const attrs2 = { string: 'String' };
        await new Promise(success => mySavedCollection.create(attrs2, {'wait': true, success}));
        expect(mySavedCollection.length).to.equal(2);
        await new Promise(success => mySavedCollection.fetch({success}));
        expect(mySavedCollection.length).to.equal(2);

    });

    it('cannot duplicate id in sessionStorage', async function () {
        const item = clone(attributes);
        item.id = 5;
        const newCollection = new SavedCollection([item]);
        await new Promise((resolve, reject) => newCollection.create(item, {'success': resolve}));
        await new Promise((resolve, reject) => newCollection.create(item, {'success': resolve}));
        const localItem = root.sessionStorage.getItem('localforage/SavedCollection-5');
        expect(newCollection.length).to.equal(1);
        expect(JSON.parse(localItem).id).to.equal(5);
    });


    describe('pulling from sessionStorage', function () {
        beforeEach(() => sessionStorage.clear());

        it('saves into the sessionStorage', async function () {
            const mySavedCollection = new SavedCollection();
            const model = await new Promise((resolve, reject) => mySavedCollection.create(attributes, {'success': resolve}));
            const item = root.sessionStorage.getItem(`localforage/SavedCollection-${model.id}`);
            expect(item).to.be.a('string');
        });

        it('saves the right data', async function () {
            const mySavedCollection = new SavedCollection();
            const model = await new Promise((resolve, reject) => mySavedCollection.create(attributes, {'success': resolve}));
            const item = root.sessionStorage.getItem(`localforage/SavedCollection-${model.id}`);
            const parsed = JSON.parse(item);
            expect(parsed.id).to.equal(model.id);
            expect(parsed.string).to.equal('String');
        });

        it('reads from sessionStorage', async function () {
            const mySavedCollection = new SavedCollection();
            let model = await new Promise((resolve, reject) => mySavedCollection.create(attributes, {'success': resolve}));
            const newCollection = new SavedCollection();
            model = await new Promise((resolve, reject) => newCollection.fetch({'success': resolve}));
            expect(newCollection.length).to.equal(1);
            const newModel = newCollection.at(0);
            expect(newModel.get('string')).to.equal('String');
        });

        it('destroys models and removes from collection', async function () {
            const mySavedCollection = new SavedCollection();
            const model = await new Promise((resolve, reject) => mySavedCollection.create(attributes, {'success': resolve}));
            const item = root.sessionStorage.getItem(`localforage/SavedCollection-${model.id}`);
            const parsed = JSON.parse(item);
            const newModel = mySavedCollection.get(parsed.id);
            await new Promise((resolve, reject) => newModel.destroy({'success': resolve}));
            const removed = root.sessionStorage.getItem(`localforage/SavedCollection-${parsed.id}`);
            expect(removed).to.be.null;
            expect(mySavedCollection.length).to.equal(0);
        });
    });

    describe('will fetch from sessionStorage if updated separately', function () {
        beforeEach(() => sessionStorage.clear());

        it('fetches the items from the original collection', async function () {
            const mySavedCollection = new SavedCollection();
            await new Promise((resolve, reject) => mySavedCollection.create(attributes, {'success': resolve}));
            const newCollection = new SavedCollection();
            await new Promise((resolve, reject) => newCollection.fetch({'success': resolve}));
            expect(newCollection.length).to.equal(1);
        });

        it('will update future changes', async function () {
            const mySavedCollection = new SavedCollection();
            const newAttributes = clone(attributes);
            mySavedCollection.create(newAttributes);
            await new Promise((resolve, reject) => mySavedCollection.create(newAttributes, {'success': resolve}));

            const newCollection = new SavedCollection();
            await new Promise((resolve, reject) => newCollection.fetch({'success': resolve}));
            expect(newCollection.length).to.equal(2);
        });
    });
});
Example #6
Source File: localStorage.test.js    From skeletor with MIT License 4 votes vote down vote up
describe("Storage using localStorage", function () {

    const attributes = {
        string: "String",
        string2: "String 2",
        number: 1337
    };

    const onError = function (model, resp, options) {
        throw new Error(resp);
    };

    describe("on a Collection", function () {
        beforeEach(() => localStorage.clear());

        const TestModel = Model.extend({
            defaults: attributes
        });

        const TestCollection = Collection.extend({
            model: TestModel,
            browserStorage: new Storage("collectionStore", "local")
        });

        it("should use `localSync`", function () {
            const collection = new TestCollection();
            collection.fetch();
            const method = getSyncMethod(collection);
            assert.equal(method.__name__, 'localSync');
        });

        it("should initially be empty", function () {
            const collection = new TestCollection();
            collection.fetch();
            assert.equal(collection.length, 0);
        });


        describe("create", function () {
            beforeEach(() => localStorage.clear());

            it("should have 1 model", async function () {
                const collection = new TestCollection();
                const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                assert.equal(collection.length, 1);
            });

            it("should have a populated model", async function () {
                const collection = new TestCollection();
                const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                assert.equal(collection.length, 1);
                assert.deepEqual(model.toJSON(), extend(clone(attributes), {'id': model.id}));
            });

            it("should have assigned an `id` to the model", async function () {
                const collection = new TestCollection();
                const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                await model.collection.browserStorage.storeInitialized;
                assert.isDefined(model.id);
            });

            it("should be saved to the localstorage", async function () {
                const collection = new TestCollection();
                const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                await model.collection.browserStorage.storeInitialized;
                assert.isNotNull(root.localStorage.getItem('localforage/collectionStore'+'-'+model.id));
            });
        });

        describe("get (by `id`)", function () {
            beforeEach(() => localStorage.clear());

            it("should find the model with its `id`", async function () {
                const collection = new TestCollection();
                const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                await model.collection.browserStorage.storeInitialized;
                assert.deepEqual(collection.get(model.id), model);
            });
        });

        describe("instances", function () {
            beforeEach(() => localStorage.clear());

            describe("when saved", function () {
                beforeEach(() => localStorage.clear());

                it("should persist the changes", async function () {
                    const collection = new TestCollection();
                    const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                    model.save({'string': "String 0"});
                    collection.fetch();

                    assert.equal(model.get("string"), "String 0");
                });

                describe("with a new `id`", function () {
                    beforeEach(() => localStorage.clear());

                    it("should have a new `id`", async function () {
                        const collection = new TestCollection();
                        const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                        model.save({'id': 1});
                        collection.fetch();

                        assert.equal(model.id, 1);
                    });

                    it("should have kept its old properties", async function () {
                        const collection = new TestCollection();
                        const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                        model.save({'id': 1});
                        collection.fetch();

                        const withId = clone(attributes);
                        withId.id = 1;
                        assert.deepEqual(model.toJSON(), withId);
                    });

                    it("should be saved in localstorage by new id", async function () {
                        const collection = new TestCollection();
                        const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
                        model.save({'id': 1});
                        await new Promise((resolve, reject) => collection.fetch({'success': resolve}));
                        assert.isNotNull(root.localStorage.getItem('localforage/collectionStore-1'));
                    });
                });
            });


            describe("destroy", function () {
                beforeEach(() => localStorage.clear());

                it("should remove all items from the collection and its store", async function () {
                    const collection = new TestCollection();
                    await Promise.all(range(5).map(i => new Promise((resolve, reject) => collection.create({}, {'success': resolve}))));
                    assert.equal(collection.length, 5);
                    while (collection.length) {
                        collection.at(0).destroy();
                    }
                    const beforeFetchLength = collection.length;
                    collection.fetch();
                    const afterFetchLength = collection.length;

                    assert.equal(beforeFetchLength, 0);
                    assert.equal(afterFetchLength, 0);
                });
            });

            describe("with a different `idAttribute`", function () {

                it("should use the custom `idAttribute`", async function () {
                    const TestModel = Model.extend({
                        defaults: attributes,
                        idAttribute: "_id"
                    });
                    const TestCollection = Collection.extend({
                        model: TestModel,
                        browserStorage: new Storage("collection2Store", "local")
                    });

                    const collection = new TestCollection();
                    const model = await new Promise(resolve => collection.create({}, {'success': resolve}));
                    assert.equal(collection.first().id, collection.first().get("_id"));
                });
            });
        });
    });

    describe("on a Model", function () {
        beforeEach(() => localStorage.clear());

        const TestModel = Model.extend({
            defaults: attributes,
            browserStorage: new Storage("modelStore", "local")
        });

        it("should use `localSync`", function () {
            const model = new TestModel();
            assert.equal(getSyncMethod(model).__name__, 'localSync');
        });

        describe("fetch", function () {
            beforeEach(() => localStorage.clear());

            it('should fire sync event on fetch', function(done) {
                const model = new TestModel(attributes);
                model.on('sync', () => done());
                model.fetch();
            });
        });

        describe("save", function () {
            beforeEach(() => localStorage.clear());

            it("should have assigned an `id` to the model", async function () {
                const model = new TestModel();
                await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
                model.fetch();
                assert.isDefined(model.id);
            });

            it("should be saved to the localstorage", async function () {
                const model = new TestModel();
                await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
                assert.isNotNull(root.localStorage.getItem('localforage/modelStore'+'-'+model.id));
            });

            describe("with new attributes", function () {

                it("should persist the changes", async function () {
                    const model = new TestModel();
                    await new Promise((resolve, reject) => model.save({number: 42}, {'success': resolve}));
                    model.fetch();
                    assert.deepEqual(model.toJSON(), extend(clone(attributes), {id: model.id, number: 42}));
                });
            });

            describe('fires events', function () {

                it('should fire sync event on save', function(done) {
                    const model = new TestModel();
                    model.on('sync', () => done());
                    model.save({foo: 'baz'});
                });
            });
        });

        describe("destroy", function () {

            it("should have removed the instance from the store", async function () {
                const model = new TestModel();
                await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
                const store = model.browserStorage.store;
                let item = await store.getItem(model.browserStorage.getItemName(model.id));
                assert.isNotNull(item);
                await new Promise((resolve, reject) => model.destroy({'success': resolve}));
                item = await store.getItem(model.browserStorage.getItemName(model.id));
                assert.isNull(item);
            });
        });
    });
});
Example #7
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let website = e.target.value;

		props.setAttributes({ website });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		website,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { invalid, empty },
		messages,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("website", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "website"),
					default: extract_admin_id(newFieldName, "website"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"website",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"website",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "website");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Prefix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Suffix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-website cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					<input value={website} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #8
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let website = e.target.value;

		props.setAttributes({ website });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		website,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { invalid, empty },
		messages,
		condition,
		enableCondition,
		adminId,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("website", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "website"),
					default: extract_admin_id(newFieldName, "website"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"website",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"website",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "website");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-website cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<input value={website} onChange={handleChange} />
			</div>
		</div>,
	];
}
Example #9
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let text = e.target.value;

		props.setAttributes({ text });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		text,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages,
		messages: { invalid, empty },
		pattern,
		minimumLength,
		maximumLength,
		condition,
		adminId,
		enableCondition,
		prefix,
		suffix,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("text", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "text"),
					default: extract_admin_id(newFieldName, "text"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"text",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"text",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "text");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>
					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Prefix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>
					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Suffix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>
					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label={__("Required", "cwp-gutenberg-forms")}
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}

					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}

					<div className="cwp-option">
						<RangeControl
							label={__("Minimum Length", "cwp-gutenberg-forms")}
							value={minimumLength}
							initialPosition={0}
							onChange={(value) =>
								props.setAttributes({ minimumLength: value })
							}
							min={0}
							max={100}
						/>
						<RangeControl
							label={__("Maximum Length", "cwp-gutenberg-forms")}
							value={maximumLength}
							onChange={(value) =>
								props.setAttributes({ maximumLength: value })
							}
							min={1}
							max={100}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-text cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>Required</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					<input value={text} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #10
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let text = e.target.value;

		props.setAttributes({ text });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		text,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages,
		messages: { invalid, empty },
		pattern,
		minimumLength,
		maximumLength,
		condition,
		adminId,
		enableCondition,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("text", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "text"),
					default: extract_admin_id(newFieldName, "text"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"text",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"text",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "text");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label={__("Required", "cwp-gutenberg-forms")}
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}

					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}

					<div className="cwp-option">
						<RangeControl
							label={__("Minimum Length", "cwp-gutenberg-forms")}
							value={minimumLength}
							initialPosition={0}
							onChange={(value) =>
								props.setAttributes({ minimumLength: value })
							}
							min={0}
							max={100}
						/>
						<RangeControl
							label={__("Maximum Length", "cwp-gutenberg-forms")}
							value={maximumLength}
							onChange={(value) =>
								props.setAttributes({ maximumLength: value })
							}
							min={1}
							max={100}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-text cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>Required</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<input value={text} onChange={handleChange} />
			</div>
		</div>,
	];
}
Example #11
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	let {
		options,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty },
		messages,
		condition,
		enableCondition,
		bulkAdd,
		adminId,
		hint,
		showHint
	} = props.attributes;

	const [select, setSelect] = useState([]);

	const [focus, setFocus] = useState({
		f: false,
		index: null,
	});

	const selectContainer = useRef();

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("select", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "select"),
					default: extract_admin_id(newFieldName, "select"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"select",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"select",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "select");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		let { options } = props.attributes;

		setSelect(options);

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	useEffect(() => {
		if (bulkAdd) return;

		let boxes = selectContainer.current.querySelectorAll(
			'.cwp-select-option input[type="text"]'
		);

		if (focus.f) {
			if (focus.index === null) {
				boxes[boxes.length - 1].focus();
			} else {
				boxes[focus.index].focus();
			}

			setFocus({ f: false, index: null });
		}
	}, [select, focus]); //subscribing to any further changes...

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const addSelect = () => {
		let newOption = {
			label: "Option " + (select.length + 1),
		};

		let new_options = clone(select);

		new_options.push(newOption);

		props.setAttributes({ options: new_options });
		setSelect(new_options);
	};

	const handleDelete = (index) => {
		let new_options = clone(options);

		let deleted_options = pullAt(new_options, [index]); //dosen't matter :-D

		props.setAttributes({ options: new_options });
		setSelect(new_options);
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const handleChange = (e, index) => {
		let new_options = clone(options);

		new_options[index] = {
			...new_options[index],
			label: e.target.value,
		};

		setSelect(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleDuplicate = (index) => {
		let new_options = clone(options);

		new_options.splice(index, 0, new_options[index]);

		setSelect(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleEnter = (index) => {
		let new_options = clone(options);

		new_options.splice(index + 1, 0, { label: "" });

		setSelect(new_options);
		props.setAttributes({ options: new_options });
		setFocus({ f: true, index: index + 1 });
	};

	let handleBackspace = (index) => {
		if (select[index].label === "") {
			handleDelete(index);

			if (select[index - 1]) {
				setFocus({ f: true, index: index - 1 });
			}
		}
	};

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	let clearAll = () => {
		const reset = [
			{
				label: "Option 1",
			},
		];

		setSelect(reset);
		props.setAttributes({
			options: reset,
		});
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const editView = select.map((s, index) => {
		return (
			<div className="cwp-select-option">
				<input
					aria-label={strip_tags(label)}
					onChange={(e) => handleChange(e, index)}
					type="text"
					value={s.label}
					onKeyDown={(e) => {
						e.key === "Enter" && handleEnter(index);
						e.key === "Backspace" && handleBackspace(index);
					}}
				/>
				<Button isDefault onClick={() => handleDuplicate(index)}>
					<Icon icon="admin-page" />
				</Button>
				<Button isDefault onClick={() => handleDelete(index)}>
					<Icon icon="no-alt" />
				</Button>
			</div>
		);
	});

	const SelectView = () => {
		return (
			<select data-cwp-field>
				{select.map((s, index) => {
					return <option value={s.label}>{s.label}</option>;
				})}
			</select>
		);
	};

	return [
		<InspectorControls>
			<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
				<div className="cwp-option">
					<TextControl
						placeholder={adminId.default}
						label={__("Field ID", "cwp-gutenberg-forms")}
						value={adminId.value}
						onChange={handleAdminId}
					/>
				</div>

				{!enableCondition ? (
					<PanelRow>
						<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
						<FormToggle
							label={__("Required", "cwp-gutenberg-forms")}
							checked={isRequired}
							onChange={handleRequired}
						/>
					</PanelRow>
				) : (
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("You cannot set a conditional field required!", "cwp-gutenberg-forms")}
						</p>
					</div>
				)}
				{isRequired && (
					<div className="cwp-option">
						<h3 className="cwp-heading">{__("Required Text", "cwp-gutenberg-forms")}</h3>
						<TextControl
							onChange={(label) =>
								props.setAttributes({ requiredLabel: label })
							}
							value={requiredLabel}
						/>
					</div>
				)}
			</PanelBody>
			<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<FormToggle
						label="Show Hint"
						checked={showHint}
						onChange={() => props.setAttributes({ showHint: !showHint })}
					/>
					{showHint && (
						<Fragment>
							<TextControl
								label={__("Hint Text", "cwp-gutenberg-forms")}
								onChange={(hint) => props.setAttributes({ hint })}
								value={hint}
							/>
						</Fragment>
					)}
				</div>
			</PanelBody>
			<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
				<ConditionalLogic
					condition={condition}
					set={props.setAttributes}
					clientId={props.clientId}
					useCondition={props.attributes.enableCondition}
				/>
			</PanelBody>
			{isRequired && (
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<h3 className="cwp-heading">{__("Required Error", "cwp-gutenberg-forms")}</h3>
						<TextControl
							onChange={(label) => setMessages("empty", label)}
							value={empty}
						/>
					</div>
				</PanelBody>
			)}
		</InspectorControls>,
		null,
		<div
			className={`cwp-select cwp-field ${
				!props.isSelected ? props.className : ""
			}`}
		>
			{bulkAdd ? (
				<Bulk_Add onChange={(c) => setSelect(c)} data={props} />
			) : (
				<Fragment>
					{!!props.isSelected && !enableCondition && (
						<div className="cwp-required">
							<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle checked={isRequired} onChange={handleRequired} />
						</div>
					)}

					<div className="cwp-select-set" ref={selectContainer}>
						<div className="cwp-label-wrap">
							<RichText
								placeholder={__("Add a label", "cwp-gutenberg-forms")}
								tag="label"
								value={label}
								onChange={handleLabel}
							/>
							{!props.isSelected && isRequired && !enableCondition && (
								<div className="cwp-required cwp-noticed">
									<h3>{requiredLabel}</h3>
								</div>
							)}
						</div>
						{!!props.isSelected ? editView : <SelectView />}
						{!!props.isSelected && (
							<div className="cwp-select-controls">
								<div>
									<Button isDefault onClick={addSelect}>
										{__("Add Option", "cwp-gutenberg-forms")}
									</Button>
									<Button
										isDefault
										onClick={() => props.setAttributes({ bulkAdd: true })}
									>
										{__("Bulk Add", "cwp-gutenberg-forms")}
									</Button>
								</div>
								<div>
									<Button onClick={clearAll}>
										{__("Clear All", "cwp-gutenberg-forms")}
									</Button>
								</div>
							</div>
						)}
					</div>
				</Fragment>
			)}
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #12
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	let {
		options,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty },
		messages,
		condition,
		enableCondition,
		bulkAdd,
		adminId,
	} = props.attributes;

	const [select, setSelect] = useState([]);

	const [focus, setFocus] = useState({
		f: false,
		index: null,
	});

	const selectContainer = useRef();

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("select", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "select"),
					default: extract_admin_id(newFieldName, "select"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"select",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"select",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "select");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		let { options } = props.attributes;

		setSelect(options);

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	useEffect(() => {
		if (bulkAdd) return;

		let boxes = selectContainer.current.querySelectorAll(
			'.cwp-select-option input[type="text"]'
		);

		if (focus.f) {
			if (focus.index === null) {
				boxes[boxes.length - 1].focus();
			} else {
				boxes[focus.index].focus();
			}

			setFocus({ f: false, index: null });
		}
	}, [select, focus]); //subscribing to any further changes...

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const addSelect = () => {
		let newOption = {
			label: "Option " + (select.length + 1),
		};

		let new_options = clone(select);

		new_options.push(newOption);

		props.setAttributes({ options: new_options });
		setSelect(new_options);
	};

	const handleDelete = (index) => {
		let new_options = clone(options);

		let deleted_options = pullAt(new_options, [index]); //dosen't matter :-D

		props.setAttributes({ options: new_options });
		setSelect(new_options);
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const handleChange = (e, index) => {
		let new_options = clone(options);

		new_options[index] = {
			...new_options[index],
			label: e.target.value,
		};

		setSelect(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleDuplicate = (index) => {
		let new_options = clone(options);

		new_options.splice(index, 0, new_options[index]);

		setSelect(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleEnter = (index) => {
		let new_options = clone(options);

		new_options.splice(index + 1, 0, { label: "" });

		setSelect(new_options);
		props.setAttributes({ options: new_options });
		setFocus({ f: true, index: index + 1 });
	};

	let handleBackspace = (index) => {
		if (select[index].label === "") {
			handleDelete(index);

			if (select[index - 1]) {
				setFocus({ f: true, index: index - 1 });
			}
		}
	};

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	let clearAll = () => {
		const reset = [
			{
				label: "Option 1",
			},
		];

		setSelect(reset);
		props.setAttributes({
			options: reset,
		});
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const editView = select.map((s, index) => {
		return (
			<div className="cwp-select-option">
				<input
					aria-label={strip_tags(label)}
					onChange={(e) => handleChange(e, index)}
					type="text"
					value={s.label}
					onKeyDown={(e) => {
						e.key === "Enter" && handleEnter(index);
						e.key === "Backspace" && handleBackspace(index);
					}}
				/>
				<Button isDefault onClick={() => handleDuplicate(index)}>
					<Icon icon="admin-page" />
				</Button>
				<Button isDefault onClick={() => handleDelete(index)}>
					<Icon icon="no-alt" />
				</Button>
			</div>
		);
	});

	const SelectView = () => {
		return (
			<select data-cwp-field>
				<option value="" disabled selected>
					Select your option
				</option>
				{select.map((s, index) => {
					return <option value={s.label}>{s.label}</option>;
				})}
			</select>
		);
	};

	return [
		<InspectorControls>
			<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
				<div className="cwp-option">
					<TextControl
						placeholder={adminId.default}
						label={__("Field ID", "cwp-gutenberg-forms")}
						value={adminId.value}
						onChange={handleAdminId}
					/>
				</div>

				{!enableCondition ? (
					<PanelRow>
						<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
						<FormToggle
							label={__("Required", "cwp-gutenberg-forms")}
							checked={isRequired}
							onChange={handleRequired}
						/>
					</PanelRow>
				) : (
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("You cannot set a conditional field required!", "cwp-gutenberg-forms")}
						</p>
					</div>
				)}
				{isRequired && (
					<div className="cwp-option">
						<h3 className="cwp-heading">{__("Required Text", "cwp-gutenberg-forms")}</h3>
						<TextControl
							onChange={(label) =>
								props.setAttributes({ requiredLabel: label })
							}
							value={requiredLabel}
						/>
					</div>
				)}
			</PanelBody>
			<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
				<ConditionalLogic
					condition={condition}
					set={props.setAttributes}
					clientId={props.clientId}
					useCondition={props.attributes.enableCondition}
				/>
			</PanelBody>
			{isRequired && (
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<h3 className="cwp-heading">{__("Required Error", "cwp-gutenberg-forms")}</h3>
						<TextControl
							onChange={(label) => setMessages("empty", label)}
							value={empty}
						/>
					</div>
				</PanelBody>
			)}
		</InspectorControls>,
		null,
		<div
			className={`cwp-select cwp-field ${
				!props.isSelected ? props.className : ""
			}`}
		>
			{bulkAdd ? (
				<Bulk_Add onChange={(c) => setSelect(c)} data={props} />
			) : (
				<Fragment>
					{!!props.isSelected && !enableCondition && (
						<div className="cwp-required">
							<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle checked={isRequired} onChange={handleRequired} />
						</div>
					)}

					<div className="cwp-select-set" ref={selectContainer}>
						<div className="cwp-label-wrap">
							<RichText
								placeholder={__("Add a label", "cwp-gutenberg-forms")}
								tag="label"
								value={label}
								onChange={handleLabel}
							/>
							{!props.isSelected && isRequired && !enableCondition && (
								<div className="cwp-required cwp-noticed">
									<h3>{requiredLabel}</h3>
								</div>
							)}
						</div>
						{!!props.isSelected ? editView : <SelectView />}
						{!!props.isSelected && (
							<div className="cwp-select-controls">
								<div>
									<Button isDefault onClick={addSelect}>
										{__("Add Option", "cwp-gutenberg-forms")}
									</Button>
									<Button
										isDefault
										onClick={() => props.setAttributes({ bulkAdd: true })}
									>
										{__("Bulk Add", "cwp-gutenberg-forms")}
									</Button>
								</div>
								<div>
									<Button onClick={clearAll}>
										{__("Clear All", "cwp-gutenberg-forms")}
									</Button>
								</div>
							</div>
						)}
					</div>
				</Fragment>
			)}
		</div>,
	];
}
Example #13
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	let {
		options,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty },
		messages,
		condition,
		enableCondition,
		fieldStyle,
		bulkAdd,
		adminId,
		hint,
		showHint,
	} = props.attributes;

	const radiosContainer = useRef();

	const [radios, setRadios] = useState([]);

	const [focus, setFocus] = useState({
		f: false,
		index: null,
	});

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("radio", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "radio"),
					default: extract_admin_id(newFieldName, "radio"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"radio",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"radio",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "radio");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		let { options } = props.attributes;

		const checked = options.find((c) => c.checked);

		if (checked) {
			let opt = clone(options);

			let remove_extra_checked = opt.map((v) => {
				if (!isEqual(v, checked)) {
					return {
						...v,
						checked: false,
					};
				} else return v;
			});
			setRadios(remove_extra_checked);
		} else {
			setRadios(options);
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	useEffect(() => {
		if (bulkAdd) return;

		let boxes = radiosContainer.current.querySelectorAll(
			'.cwp-radios-option input[type="text"]'
		);

		if (focus.f) {
			if (focus.index === null) {
				boxes[boxes.length - 1].focus();
			} else {
				boxes[focus.index].focus();
			}

			setFocus({ f: false, index: null });
		}
	}, [radios, focus]); //subscribing to any further changes...

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const addRadio = () => {
		let newOption = {
			label: "Option " + (radios.length + 1),
			checked: false,
		};

		let new_options = clone(radios);

		new_options.push(newOption);

		props.setAttributes({ options: new_options });
		setRadios(new_options);
	};

	const handleDelete = (index) => {
		let new_options = clone(options);

		let deleted_options = pullAt(new_options, [index]); //dosen't matter :-D

		props.setAttributes({ options: new_options });
		setRadios(new_options);
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const handleChange = (e, index) => {
		let new_options = clone(options);

		new_options[index] = {
			...new_options[index],
			label: e.target.value,
		};

		setRadios(new_options);
		props.setAttributes({ options: new_options });
	};

	const handleCheck = (c, index) => {
		let new_options = clone(options);

		new_options.forEach((v) => (v.checked = false));

		new_options[index].checked = c;

		setRadios(new_options);
		props.setAttributes({ options: new_options });
	};

	const handleImage = (img, index, action) => {
		let new_options = clone(options);

		if (action === "add") {
			new_options[index] = {
				...new_options[index],
				image: img,
			};
		}

		if (action === "remove") {
			const RadioToRemove = new_options[index];
			new_options[index] = {
				label: RadioToRemove.label,
			};
		}

		setRadios(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleDuplicate = (index) => {
		let new_options = clone(options);

		new_options.splice(index, 0, new_options[index]);

		setRadios(new_options);
		props.setAttributes({ options: new_options });
	};

	let handleEnter = (index) => {
		let new_options = clone(options);

		new_options.splice(index + 1, 0, { label: "" });

		setRadios(new_options);
		props.setAttributes({ options: new_options });
		setFocus({ f: true, index: index + 1 });
	};

	let handleBackspace = (index) => {
		if (radios[index].label === "") {
			handleDelete(index);

			if (radios[index - 1]) {
				setFocus({ f: true, index: index - 1 });
			}
		}
	};

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	let clearAll = () => {
		const reset = [
			{
				label: "Option 1",
			},
		];

		setRadios(reset);
		props.setAttributes({
			options: reset,
		});
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		<InspectorControls>
			<PanelBody title="Field Settings" initialOpen={true}>
				<div className="cwp-option">
					<TextControl
						placeholder={adminId.default}
						label={__("Field ID", "cwp-gutenberg-forms")}
						value={adminId.value}
						onChange={handleAdminId}
					/>
				</div>

				{!enableCondition ? (
					<PanelRow>
						<h3 className="cwp-heading">
							{__("Required", "cwp-gutenberg-forms")}
						</h3>
						<FormToggle
							label="Required"
							checked={isRequired}
							onChange={handleRequired}
						/>
					</PanelRow>
				) : (
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__(
								"You cannot set a conditional field required!",
								"cwp-gutenberg-forms"
							)}
						</p>
					</div>
				)}
				{isRequired && (
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Required Text", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(label) =>
								props.setAttributes({ requiredLabel: label })
							}
							value={requiredLabel}
						/>
					</div>
				)}
				<div className="cwp-option">
					<SelectControl
						label={__("Layout", "cwp-gutenberg-forms")}
						value={fieldStyle}
						options={[
							{ label: __("Block", "cwp-gutenberg-forms"), value: "block" },
							{ label: __("Inline", "cwp-gutenberg-forms"), value: "inline" },
						]}
						onChange={(s) => {
							props.setAttributes({ fieldStyle: s });
						}}
					/>
				</div>
			</PanelBody>
			<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<FormToggle
						label="Show Hint"
						checked={showHint}
						onChange={() => props.setAttributes({ showHint: !showHint })}
					/>
					{showHint && (
						<Fragment>
							<TextControl
								label={__("Hint Text", "cwp-gutenberg-forms")}
								onChange={(hint) => props.setAttributes({ hint })}
								value={hint}
							/>
						</Fragment>
					)}
				</div>
			</PanelBody>
			<PanelBody title="Condition">
				<ConditionalLogic
					condition={condition}
					set={props.setAttributes}
					clientId={props.clientId}
					useCondition={props.attributes.enableCondition}
				/>
			</PanelBody>

			{isRequired && (
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Required Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(label) => setMessages("empty", label)}
							value={empty}
						/>
					</div>
				</PanelBody>
			)}
		</InspectorControls>,
		null,
		<div
			className={`cwp-radios cwp-field ${props.className} is-style-${fieldStyle}`}
		>
			{bulkAdd ? (
				<Bulk_Add onChange={(c) => setRadios(c)} data={props} />
			) : (
				<Fragment>
					{!!props.isSelected && !enableCondition && (
						<div className="cwp-required">
							<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle checked={isRequired} onChange={handleRequired} />
						</div>
					)}

					<div
						ref={radiosContainer}
						className={`cwp-radios-set ${
							!props.isSelected ? "cwp-radio-set-preview" : ""
						}`}
					>
						<div className="cwp-label-wrap">
							<RichText
								placeholder={__("Add a label", "cwp-gutenberg-forms")}
								tag="label"
								value={label}
								onChange={handleLabel}
							/>
							{!props.isSelected && isRequired && !enableCondition && (
								<div className="cwp-required cwp-noticed">
									<h3>{requiredLabel}</h3>
								</div>
							)}
						</div>
						{radios.map((radio, index) => {
							const hasImage = has(radio, "image"),
								image = hasImage ? radio.image.url : "";

							return (
								<Fragment>
									<div className="cwp-radios-option">
										<input
											id={id.concat(index.toString())}
											checked={radio.checked}
											onClick={() => handleCheck(!radio.checked, index)}
											type="radio"
										/>
										{!!props.isSelected && (
											<label
												style={{ width: "auto" }}
												onClick={() => handleCheck(!radio.checked, index)}
												for={id.concat(index.toString())}
											></label>
										)}
										{!!props.isSelected ? (
											<input
												onKeyDown={(e) => {
													e.key === "Enter" && handleEnter(index);
													e.key === "Backspace" && handleBackspace(index);
												}}
												onChange={(e) => handleChange(e, index)}
												type="text"
												value={radio.label}
											/>
										) : (
											<label>
												{radio.label}{" "}
												{hasImage && !props.isSelected && (
													<ImagePreview
														onEdit={(img) => handleImage(img, index, "add")}
														onRemove={() => handleImage(null, index, "remove")}
														isSelected={props.isSelected}
														image={radio.image}
													/>
												)}
											</label>
										)}
										{!!props.isSelected && (
											<Fragment>
												<ImageUpload
													icon="format-image"
													value={image}
													onSelect={(img) => handleImage(img, index, "add")}
												/>
												<Button
													isDefault
													onClick={() => handleDuplicate(index)}
												>
													<Icon icon="admin-page" />
												</Button>
												<Button isDefault onClick={() => handleDelete(index)}>
													<Icon icon="no-alt" />
												</Button>
											</Fragment>
										)}
									</div>
									{hasImage && !!props.isSelected && (
										<ImagePreview
											onEdit={(img) => handleImage(img, index, "add")}
											onRemove={() => handleImage(null, index, "remove")}
											isSelected={props.isSelected}
											image={radio.image}
										/>
									)}
								</Fragment>
							);
						})}
						{!!props.isSelected && (
							<div className="cwp-radios-controls">
								<div>
									<Button isDefault onClick={addRadio}>
										{__("Add Option", "cwp-gutenberg-forms")}
									</Button>
									<Button
										isDefault
										onClick={() => props.setAttributes({ bulkAdd: true })}
									>
										{__("Bulk Add", "cwp-gutenberg-forms")}
									</Button>
								</div>
								<div>
									<Button onClick={clearAll}>
										{__("Clear All", "cwp-gutenberg-forms")}
									</Button>
								</div>
							</div>
						)}
					</div>
				</Fragment>
			)}
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #14
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let phone = e.target.value;

		props.setAttributes({ phone });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		phone,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages,
		messages: { invalid, empty },
		pattern,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("phone", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "phone"),
					default: extract_admin_id(newFieldName, "phone"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"phone",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"phone",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "phone");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Prefix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Suffix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>

				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-phone cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					<input value={phone} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #15
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let phone = e.target.value;

		props.setAttributes({ phone });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		phone,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages,
		messages: { invalid, empty },
		pattern,
		condition,
		enableCondition,
		adminId,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("phone", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "phone"),
					default: extract_admin_id(newFieldName, "phone"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"phone",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"phone",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "phone");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>

				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-phone cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<input value={phone} onChange={handleChange} />
			</div>
		</div>,
	];
}
Example #16
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let number = e.target.value;

		props.setAttributes({ number });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		number,
		isRequired,
		label,
		id,
		field_name,
		isRange,
		rangeMax,
		rangeMin,
		requiredLabel,
		messages: { invalid, empty },
		messages,
		steps,
		adminId,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detectSimilarFields(props.clientId, field_name)) {
			const newFieldName = getFieldName("number", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "number"),
					default: extract_admin_id(newFieldName, "number"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"number",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (
			field_name !== "" &&
			detectSimilarFields(props.clientId, field_name)
		) {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"number",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (
			field_name !== "" &&
			!detectSimilarFields(props.clientId, field_name)
		) {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"number",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "number");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => {
		getRootData();
	}, [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					</div>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
					<RangeControl
						min={0}
						max={10000}
						value={steps}
						step={0.01}
						onChange={(steps) => props.setAttributes({ steps })}
						label="Steps"
					/>
					<div className="cwp-option">
						<RangeControl
							min={0}
							max={10000}
							step={0.01}
							value={rangeMax}
							onChange={(m) => props.setAttributes({ rangeMax: m })}
							label={__("Range Max", "cwp-gutenberg-forms")}
						/>
						<RangeControl
							min={0}
							step={0.01}
							value={rangeMin}
							max={10000}
							onChange={(m) => props.setAttributes({ rangeMin: m })}
							label={__("Range Min", "cwp-gutenberg-forms")}
						/>
					</div>
				</PanelBody>
				<PanelBody title="Messages">
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Number Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-number cwp-field ${props.className}`}>
			{!!props.isSelected && (
				<div className="cwp-required">
					<h3>{__("Range Slider", "cwp-gutenberg-forms")}</h3>
					<FormToggle
						checked={isRange}
						onChange={() => props.setAttributes({ isRange: !isRange })}
					/>
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				{isRange ? (
					<div className="cwp-range-set">
						<input
							value={number}
							max={rangeMax}
							min={rangeMin}
							type="range"
							step={steps}
							onChange={handleChange}
						/>
						<input
							value={number}
							step={steps}
							type="number"
							max={rangeMax}
							min={rangeMin}
							onChange={handleChange}
						/>
					</div>
				) : (
					<input
						value={number}
						max={rangeMax}
						step={steps}
						min={rangeMin}
						type="number"
						onChange={handleChange}
					/>
				)}
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #17
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let name = e.target.value;

		props.setAttributes({ name });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		name,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty, invalidName },
		messages,
		pattern,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
		showHint,
		hint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("name", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "name"),
					default: extract_admin_id(newFieldName, "name"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"name",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"name",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "name");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody
					title={__("Field Settings", "cwp-gutenberg-forms")}
					initialOpen={true}
				>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Prefix", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Suffix", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Required", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<Fragment>
							<div className="cwp-option">
								<h3 className="cwp-heading">
									{__("Required Text", "cwp-gutenberg-forms")}
								</h3>
								<TextControl
									onChange={(label) =>
										props.setAttributes({ requiredLabel: label })
									}
									value={requiredLabel}
								/>
							</div>
						</Fragment>
					)}
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Name Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalidName", v)}
							value={invalidName}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__(
								"Use {{value}} to insert field value!",
								"cwp-gutenberg-forms"
							)}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-name cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}
			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					<input value={name} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
				<p className="cwp-hint">{hint}</p>
			)}
		</div>,
	];
}
Example #18
Source File: mob.js    From space-station-13-idle with GNU Affero General Public License v3.0 4 votes vote down vote up
export function createMobModule(mobType) {
	return {
		namespaced: true,
		modules: {
			swingCoroutine: createCoroutineModule(),
			regenCoroutine: createCoroutineModule()
		},
		state: {
			mobType,
			health: 100,
			ammoStreak: 0
		},
		getters: {
			health(state) {
				return state.health;
			},
			stats(state, getters, rootState, rootGetters) {
				let fullStats;
				if (state.mobType == "player") {
					fullStats = clone(PLAYER_BASE_STATS);
					fullStats.precision += Math.min(MAX_LEVEL, rootGetters["precision/level"]);
					if (rootGetters["combat/isRanged"]) {
						fullStats.power += Math.min(MAX_LEVEL, rootGetters["rangedPower/level"]);
					} else {
						fullStats.power += Math.min(MAX_LEVEL, rootGetters["meleePower/level"]);
					}
					fullStats.command += Math.min(MAX_LEVEL, rootGetters["command/level"]);
					fullStats.evasion += Math.min(MAX_LEVEL, rootGetters["evasion/level"]);
					fullStats[rootGetters["combat/focus"]] += 5;
					Object.values(rootGetters["inventory/equipment"]).forEach(equipment => {
						if (!equipment.itemId) return;
						let item = ITEMS[equipment.itemId];
						if (!item) return;
						if (!item.stats) return;
						let restricted = rootGetters["inventory/checkRestricted"](equipment.itemId);
						if (restricted) return;
						combineStats(fullStats, item.stats)
					});
				}
				else if (state.mobType == "enemy") {
					let targetEnemy = rootGetters["combat/targetEnemy"];
					if (!targetEnemy) return ENEMY_BASE_STATS;
					fullStats = Object.assign({}, ENEMY_BASE_STATS, ENEMIES[targetEnemy].stats);
				}
				fixProtection(fullStats);
				if (state.health > fullStats.maxHealth) state.health = fullStats.maxHealth;
				return fullStats;
			},
			targetStats(state, getters, rootState, rootGetters) {
				if (state.mobType == "player") {
					return rootGetters["enemyMob/stats"];
				} else if (state.mobType == "enemy") {
					return rootGetters["playerMob/stats"];
				}
				return null
			},
			baseDps() {
				return 3
			},
			powerRatio() {
				return .35;
			},
			dps(state, getters) {
				return getters.baseDps + getters.powerRatio * getters.stats.power;
			},
			targetProtection(state, getters, rootState, rootGetters) {
				var inverseMobType = state.mobType == "enemy" ? "player" : "enemy";
				var damageType = getters.stats.damageType;
				return rootGetters[inverseMobType + "Mob/stats"][damageType + "Protection"];
			},
			maxHit(state, getters) {
				let hit = getters.dps * getters.stats.attackSpeed * (1 - getters.targetProtection / 100);
				return hit;
			},
			minHit(state, getters) {
				return getters.maxHit * getters.stats.luck / 100;
			},
			hitSigma() {
				return 40;
			},
			hitDiff(state, getters) {
				return getters.stats.precision - getters.targetStats.evasion;
			},
			hitChance(state, getters) {
				return getZPercent(getters.hitDiff / getters.hitSigma);
			},
			baseFleeChance(state, getters, rootState, rootGetters) {
				var companionItemId = rootGetters["inventory/equipment"].companion.itemId;
				if (!companionItemId) return 0;
				return ITEMS[companionItemId].fleeChance / 100;
			},
			commandRatio() {
				return .01;
			},
			commandReduction(state, getters) {
				return getters.stats.command * getters["commandRatio"];
			},
			fleeChance(state, getters) {
				return Math.max(getters["baseFleeChance"] - getters["commandReduction"], 0);
			},
			regenTime(state, getters) {
				let regen = getters["stats"].regen;
				if (regen == 0) return 5;
				return 1 / Math.abs(regen);
			},
		},
		mutations: {
			_setHealth(state, health) {
				state.health = health;
			},
		},
		actions: {
			cancelActions({ dispatch }) {
				dispatch("swingCoroutine/cancel");
			},
			startCombat({ state, getters, commit, dispatch }) {
				if (state.mobType == "enemy") {
					commit("_setHealth", getters.stats.maxHealth);
				}
				dispatch("_startSwing");
			},
			pauseCombat({ dispatch }) {
				dispatch("swingCoroutine/cancel");
			},
			_resume({ rootGetters, dispatch }) {
				dispatch("_startRegen");
				if (!rootGetters["combat/targetEnemy"]) return;
				if (rootGetters["enemyMob/health"] == 0) return;
				dispatch("_startSwing");
			},
			_startSwing({ getters, dispatch, state }) {
				let duration = getters.stats.attackSpeed;
				dispatch("swingCoroutine/start",
					{
						duration: getters.stats.attackSpeed,
						onFinish: () => {
							dispatch("finishSwing");
							if (state.mobType == "player") dispatch("combat/trackTime", duration, { root: true });
						}
					});
			},
			finishSwing({ state, dispatch, getters, rootGetters }) {
				var inverseMobType = state.mobType == "enemy" ? "player" : "enemy";
				dispatch("_startSwing", getters.stats.attackSpeed)

				if (Math.random() <= getters.hitChance) {
					let damage = getters.minHit + (getters.maxHit - getters.minHit) * Math.random();
					let noOverkillDamage = Math.min(rootGetters[inverseMobType + "Mob/health"], damage);
					dispatch(inverseMobType + "Mob/getHit", damage, { root: true });
					if (state.mobType == "player") {
						dispatch("combat/addXP", noOverkillDamage, { root: true });
					}
				} else {
					EventBus.$emit("dodge", state.mobType == "enemy" ? "player" : "enemy");
				}

				EventBus.$emit("swing", state.mobType);

				// Use ammo
				var pocket = rootGetters["inventory/equipment"].pocket;
				if (state.mobType == "player" && pocket.itemId && !rootGetters["inventory/checkRestricted"](pocket.itemId)) {
					if (ITEMS[pocket.itemId].preserve == true) { }
					else if(rootGetters["upgrades/get"]("ammoSaver") > 0 && rootGetters["combat/isRanged"]) {
						state.ammoStreak += 1;
						if(state.ammoStreak == 5){
							state.ammoStreak = 0;
						} else {
							pocket.count -= 1;
						}
					} else {
						pocket.count -= 1;
					}
					if (pocket.count == 0) {
						pocket.itemId = null;
						EventBus.$emit("toast", { text: `Out of ammo!`, duration: 3000 });
						if (rootGetters["settings/pocketsEmptyStop"]) {
							dispatch("cancelAllActions", {}, { root: true });
						}
					}
				}
			},
			getHit({ state, commit, getters, dispatch, rootGetters }, damage) {
				commit("_setHealth", Math.max(state.health - damage, 0));

				// Handle flee chance while in combat (not while taking damage from graytding)
				if (state.mobType == "player" && rootGetters["combat/targetEnemy"]) {
					EventBus.$emit("toast", { icon: require("@/assets/art/combat/health.gif"), text: `-${Math.round(Math.max(damage, 1))} HP` })
					dispatch("_handleSlimeFlee");
				}

				if (state.health <= 0) {
					// Handle death
					if (state.mobType == "player") {
						commit("_setHealth", getters.stats.maxHealth / 2);
						dispatch("cancelAllActions", {}, { root: true });

						// Lose a random, equipped item
						dispatch("inventory/loseEquipmentPiece", {}, { root: true });
					} else {
						dispatch("validhunting/mobKilled", rootGetters["combat/targetEnemy"], { root: true })
						commit("completion/trackEnemy", rootGetters["combat/targetEnemy"], { root: true })
						dispatch("combat/pauseCombat", {}, { root: true });
						dispatch("combat/dropEnemyLoot", {}, { root: true })
					}
				} else {
					if (state.mobType == "player") {
						dispatch("combat/tryAutoEat", {}, { root: true });
					}
				}

				EventBus.$emit("getHit", state.mobType);
			},
			_startRegen({ dispatch, getters, rootGetters, state }) {
				dispatch("regenCoroutine/start",
					{
						duration: getters["regenTime"],
						onFinish: () => {
							dispatch("_startRegen");
							if (getters.health <= 0) return;
							let regen = getters["stats"].regen;
							if (regen == 0) return;
							let gain = Math.sign(regen);
							if (gain > 0)
								dispatch("addHealth", 1);
							else if (gain < 0)
								dispatch("getHit", 1);
						}
					});
			},
			_handleSlimeFlee({ rootGetters }) {
				var companion = rootGetters["inventory/equipment"].companion;
				if (!companion.count) return;
				if (Math.random() > rootGetters["playerMob/fleeChance"]) return;
				companion.count -= 1;

				EventBus.$emit("toast", { icon: ITEMS[companion.itemId].icon, text: `Your companion has fled!` });
				if (companion.count == 0) {
					companion.itemId = null;
				}
			},
			// Add health, like from healing
			addHealth({ getters, commit }, health) {
				commit("_setHealth", Math.min(getters.health + health, getters.stats.maxHealth))
			},
			clampHealth({ getters, commit }) {
				commit("_setHealth", Math.min(getters.health, getters.stats.maxHealth));
			}
		}
	}

}
Example #19
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let message = e.target.value;

		props.setAttributes({ message });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		message,
		isRequired,
		label,
		id,
		height,
		field_name,
		requiredLabel,
		messages: { invalid, empty },
		messages,
		pattern,
		condition,
		enableCondition,
		minimumLength,
		maximumLength,
		adminId,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("message", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "message"),
					default: extract_admin_id(newFieldName, "message"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"message",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"message",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "message");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}
		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
					<div className="cwp-option">
						<RangeControl
							label={__("Minimum Length (characters)", "cwp-gutenberg-forms")}
							value={minimumLength}
							initialPosition={0}
							onChange={(value) =>
								props.setAttributes({ minimumLength: value })
							}
							min={0}
							max={1000}
						/>
						<RangeControl
							label={__("Maximum Length (characters)", "cwp-gutenberg-forms")}
							value={maximumLength}
							onChange={(value) =>
								props.setAttributes({ maximumLength: value })
							}
							min={1}
							max={1000}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Message Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Validation", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<TextControl
							label={__("Pattern (RegExp)", "cwp-gutenberg-forms")}
							onChange={(pattern) => props.setAttributes({ pattern })}
							value={pattern}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
                    <div className="cwp-option">
                        <FormToggle
                            label="Show Hint"
                            checked={showHint}
                            onChange={() => props.setAttributes({ showHint: !showHint })}
                        />
                        {showHint && (
                            <Fragment>
                                <TextControl
                                    label={__("Hint Text", "cwp-gutenberg-forms")}
                                    onChange={(hint) => props.setAttributes({ hint })}
                                    value={hint}
                                />
                            </Fragment>
                        )}
                    </div>
				</PanelBody>

			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-message cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<ResizableBox
					size={{
						height,
						width: "100%",
					}}
					showHandle={true}
					minHeight="50"
					enable={{
						top: false,
						right: false,
						bottom: true,
						left: false,
						topRight: false,
						bottomRight: false,
						bottomLeft: false,
						topLeft: false,
					}}
					onResizeStop={(event, direction, elt, delta) => {
						props.setAttributes({
							height: parseInt(height + delta.height, 10),
						});
					}}
				>
					<textarea
						value={message}
						style={{ height: height }}
						onChange={handleChange}
					/>
				</ResizableBox>
			</div>
			{showHint && (
				<p className="cwp-hint">{hint}</p>
			)}
		</div>,
	];
}
Example #20
Source File: fieldPlotter.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function FieldPlotter({
	api_fields,
	clientId,
	data,
	name,
	fields,
	title,
	query_fields,
}) {
	const { integrations, actions } = data.attributes;

	const [error, setError] = useState("");

	useEffect(() => {
		if (!has(integrations, name)) {
			integrations[name] = {};
			data.setAttributes({ integrations });
		}
	}, []);

	const getOptions = (field) => {
		const root = getBlock(clientId);
		const child_fields = root.innerBlocks;
		const available_fields = serializeFields(child_fields);

		let options = available_fields.map((f, i) => {
			const fieldName = get(f, "fieldName"),
				blockName = get(f, "blockName"),
				adminId = get(f, "adminId");

			const field_label = isEmpty(fieldName)
				? get(adminId, "value")
				: fieldName;

			const option = {
				label: field_label,
				value: get(adminId, "value"),
				blockName,
			};

			return option;
		});

		const hasRestriction = has(field, "restriction"); // checking for field restrictions..

		if (hasRestriction && !isEmpty(get(field, "restriction"))) {
			const inRestrictionOptions = options.filter((option) =>
				isEqual(option.blockName, get(field, "restriction"))
			);
			return inRestrictionOptions;
		}

		return options;
	};

	const isFieldEmpty = (v, label = null) => {
		if (isEmpty(label)) {
			return isEqual("Select Field", v) || isEmpty(v);
		}

		return isEqual("Select Field", v) || isEmpty(v) || isEqual(label, v);
	};

	const testErrors = (updatedOptions) => {
		const f = Object.assign({}, api_fields, query_fields);

		let has_err = false;

		each(updatedOptions, (option, key) => {
			const hasKey = has(f, key);
			const isFieldRequired = get(get(f, key), "required");

			const field_label = get(get(f, key), "label");
			const fieldEmpty = isFieldEmpty(option, field_label);

			if (hasKey && isFieldRequired === true && fieldEmpty) {
				// this means a required field is not filled
				has_err = true;
			}
		});

		return has_err;
	};

	const handleFieldsChange = (key, val) => {
		// not mutating the original attribute
		const newIntegrations = clone(integrations);

		set(newIntegrations, name, {
			...get(integrations, name),
			[key]: val,
		});

		data.setAttributes({ integrations: newIntegrations });

		if (testErrors(get(newIntegrations, name))) {
			setError(__("Please Map All Required Fields", "cwp-gutenberg-forms"));
		} else {
			setError("");
		}
	};

	return (
		<div className="cwp-fields-plotter">
			{!isEmpty(error) && (
				<Notice status="error" isDismissible={false}>
					{error}
				</Notice>
			)}
			{map(query_fields, (field, key) => {
				const { label, value, type } = field;
				const currentValue = has(integrations[name], key)
					? integrations[name][key]
					: null;
				const field_label = (
					<span>
						{label}
						{has(field, "required") && get(field, "required") == true && (
							<strong color="red"> (Req)</strong>
						)}
					</span>
				);

				if (type === "select") {
					let mappedValues = value.map((v) => {
						return {
							value: v.value,
							label: v.name,
						};
					});

					let values = [
						{
							label,
							value: "",
						},
						...mappedValues,
					];

					return (
						<SelectControl
							label={__(field_label, "cwp-gutenberg-forms")}
							value={currentValue}
							options={values}
							onChange={(v) => handleFieldsChange(key, v)}
						/>
					);
				} else if (type === "text") {
					return (
						<TextControl
							label={__(label, "cwp-gutenberg-forms")}
							value={currentValue}
							onChange={(v) => handleFieldsChange(key, v)}
						/>
					);
				} else if (type === "tags") {
					const suggestions = has(value, "suggestions")
						? value.suggestions
						: [];

					const currentTokens = !isEmpty(currentValue) ? currentValue : [];
					const parsedValue =
						typeof currentTokens === "string"
							? currentTokens.split(",")
							: currentTokens;

					return (
						<FormTokenField
							label={__(field_label, "cwp-gutenberg-forms")}
							value={parsedValue}
							suggestions={suggestions}
							onChange={(tokens) => {
								handleFieldsChange(key, tokens);
							}}
						/>
					);
				}
			})}
			{map(api_fields, (field, key) => {
				const { label } = field;

				const value = has(integrations[name], key)
					? integrations[name][key]
					: null;

				const defaultValue = has(field, "default") ? field.default : "";

				const field_label = (
					<span>
						{label}
						{has(field, "required") && get(field, "required") == true && (
							<strong color="red"> (Req)</strong>
						)}
					</span>
				);

				return (
					<div className="cwp_field_plot">
						<SelectControl
							onChange={(val) => handleFieldsChange(key, val)}
							label={__(field_label, "cwp-gutenberg-forms")}
							value={value}
							options={[
								{
									label: "Select Field",
									value: defaultValue,
								},
								...getOptions(field),
							]}
						/>
					</div>
				);
			})}
		</div>
	);
}
Example #21
Source File: Inspector.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function Inspector(prop) {
	const props = prop.data;

	const {
		buttonSetting,
		email,
		successURL,
		successType,
		messages,
		successMessage,
		templateBuilder,
		theme,
		formType,
		hideFormOnSuccess,
		formLabel,
		cpt,
		saveToEntries,
		sendEmail,
		actions,
		spamProtections,
		buttonStyling,
		spamMessage,
		errorMessage,
		customAction
	} = props.attributes;

	const handleAlignment = (aln) => {
		props.setAttributes({
			buttonSetting: {
				...buttonSetting,
				alignment: aln,
			},
		});
	};

	const getAlignmentProps = (aln) => {
		if (buttonSetting.alignment === aln)
			return {
				isPrimary: true,
			};

		return {
			isDefault: true,
		};
	};

	const handleButtonSetting = (t, v) => {
		props.setAttributes({
			buttonSetting: {
				...buttonSetting,
				[t]: v,
			},
		});
	};

	const getSuccess = (t) => {
		return successType === t
			? {
					isPrimary: true,
			  }
			: {
					isDefault: true,
			  };
	};

	const handleMessagesChange = (t, v, i, fieldName) => {
		let newMessages = clone(messages);

		newMessages[i] = {
			...newMessages[i],
			[t]: v,
		};
		props.setAttributes({ messages: newMessages });
		changeChildValue(fieldName, props.clientId, newMessages[i], t, messages);
	};

	const handleStyling = (style, key) => {
		const themeStyling = clone(theme);

		set(themeStyling, key, style); //changing the color;

		props.setAttributes({ theme: themeStyling });
	};

	const handleProtection = (protection) => {
		const enabled = hasObject(spamProtections, protection);

		if (enabled === false) {
			const newProtections = clone(spamProtections);
			newProtections.push(protection);
			props.setAttributes({ spamProtections: newProtections });
		} else {
			const newProtections = clone(spamProtections);
			let disabled = newProtections.filter((p) => !isEqual(p, protection));

			props.setAttributes({ spamProtections: disabled });
		}
	};

	const handleButtonStyling = (v, t) => {
		const newStyling = clone(buttonStyling);

		set(newStyling, t, v);

		props.setAttributes({ buttonStyling: newStyling });
	};

	const handleActions = (actions) => {
		// only update actions of integrations that are available
		const globalIntegrations = get(window, "cwpGlobal.settings.integrations");
		const integrations_titles = map(globalIntegrations, "title");
		let isCurrentActionSupported = true;

		actions.forEach((action) => {
			const exceptionalCases = ["Record Entries", "Email Notification"];

			if (
				!includes(integrations_titles, action) &&
				!includes(exceptionalCases, action)
			) {
				isCurrentActionSupported = false;
			}
		});

		if (isCurrentActionSupported) {
			props.setAttributes({ actions });
		}
	};

	return (
		<InspectorControls>
			<PanelBody initialOpen={false} title={__("Form Design", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Accent Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.accentColor}
						onChange={(color) => handleStyling(color, "accentColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Text Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.textColor}
						onChange={(color) => handleStyling(color, "textColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Field Background Color", "cwp-gutenberg-forms")}
					</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.fieldBackgroundColor}
						onChange={(color) => handleStyling(color, "fieldBackgroundColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Button Background Color", "cwp-gutenberg-forms")}
					</h3>
					<ColorPalette
						value={buttonStyling.backgroundColor}
						onChange={(newbg) => handleButtonStyling(newbg, "backgroundColor")}
						colors={basicColorScheme}
					/>
				</div>
			</PanelBody>

			<PanelBody initialOpen={true} title={__("General", "cwp-gutenberg-forms")}>
				<TextControl
					disabled
					label={__("Form Label", "cwp-gutenberg-forms")}
					value={formLabel}
					onChange={(formLabel) => props.setAttributes({ formLabel })}
				/>

				{formType !== "multiStep" && (
					<div className="cwp-option">
						<PanelRow>
							<h3>{__("Disable Submit Button", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								checked={buttonSetting.disable}
								onChange={() =>
									handleButtonSetting("disable", !buttonSetting.disable)
								}
							/>
						</PanelRow>
					</div>
				)}
				{!buttonSetting.disable && (
					<Fragment>
						<div className="cwp-option column">
							<h3 className="cwp-heading">
								{__("Button Alignment", "cwp-gutenberg-forms")}
							</h3>
							<div className="cwp-column">
								<ButtonGroup>
									<Button
										{...getAlignmentProps("justify-start")}
										onClick={() => handleAlignment("justify-start")}
									>
										<Icon icon="editor-alignleft" />
									</Button>
									<Button
										{...getAlignmentProps("justify-center")}
										onClick={() => handleAlignment("justify-center")}
									>
										<Icon icon="editor-aligncenter" />
									</Button>
									<Button
										{...getAlignmentProps("justify-end")}
										onClick={() => handleAlignment("justify-end")}
									>
										<Icon icon="editor-alignright" />
									</Button>
								</ButtonGroup>
							</div>
						</div>
					</Fragment>
				)}
				<div className="cwp-option column">
					<h3>{__("Confirmation Type", "cwp-gutenberg-forms")}</h3>
					<div className="cwp-column">
						<ButtonGroup>
							<Button
								{...getSuccess("url")}
								onClick={() => props.setAttributes({ successType: "url" })}
							>
								{__("URL", "cwp-gutenberg-forms")}
							</Button>
							<Button
								{...getSuccess("message")}
								onClick={() => props.setAttributes({ successType: "message" })}
							>
								{__("Message", "cwp-gutenberg-forms")}
							</Button>
						</ButtonGroup>
					</div>
				</div>
				<div className="cwp-option">
					{successType === "url" ? (
						<TextControl
							label={__("Success Url (Redirect)", "cwp-gutenberg-forms")}
							value={successURL}
							onChange={(successURL) => props.setAttributes({ successURL })}
						/>
					) : (
						<Fragment>
							<TextareaControl
								label={__("Success Message", "cwp-gutenberg-forms")}
								value={successMessage}
								onChange={(successMessage) =>
									props.setAttributes({ successMessage })
								}
							/>
							<TextareaControl
								label={__("Spam Message", "cwp-gutenberg-forms")}
								value={spamMessage}
								onChange={(spamMessage) => props.setAttributes({ spamMessage })}
							/>
							<TextareaControl
								label={__("Error Message", "cwp-gutenberg-forms")}
								value={errorMessage}
								onChange={(errorMessage) =>
									props.setAttributes({ errorMessage })
								}
							/>
						</Fragment>
					)}
				</div>
				{successType === "message" && (
					<div className="cwp-option">
						<PanelRow>
							<h3>{__("Hide Form On Success", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								checked={hideFormOnSuccess}
								onChange={() =>
									props.setAttributes({ hideFormOnSuccess: !hideFormOnSuccess })
								}
							/>
						</PanelRow>
					</div>
				)}
			</PanelBody>

			{actions.includes("Email Notification") && (
				<PanelBody title={__("Email Notification", "cwp-gutenberg-forms")}>
					<TemplateBuilder clientId={props.clientId} data={props} />
				</PanelBody>
			)}

			<PanelBody title={__("Form Action", "cwp-gutenberg-forms")}>
				<FormTokenField
					value={actions}
					onChange={handleActions}
					suggestions={get_form_actions()}
				/>
				<TextControl
					label={__("Custom Form Action Name", "cwp-gutenberg-forms")}
					value={customAction}
					onChange={(customAction) => props.setAttributes({ customAction })}
				/>
			</PanelBody>

			{!isEmpty(get_spam_protectors()) && (
				<PanelBody title={__("Spam Protection", "cwp-gutenberg-forms")}>
					{get_spam_protectors().map((protection) => {
						const isEnabled = hasObject(spamProtections, protection);

						return (
							<div className="cwp-option">
								<PanelRow>
									<h3>{protection.title}</h3>
									<FormToggle
										value={isEnabled}
										checked={isEnabled}
										onChange={() => handleProtection(protection)}
									/>
								</PanelRow>
							</div>
						);
					})}
				</PanelBody>
			)}

			<PanelBody initialOpen={false} title={__("Messages", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<p>
						<Icon icon="info" />{" "}
						{__(
							"You can edit validations messages used for various field types here. Use {{ value }} to insert field value.",
							"cwp-gutenberg-forms"
						)}
					</p>
				</div>
				<MappedMessages val={messages} onChange={handleMessagesChange} />
			</PanelBody>
			<Integrations data={props} clientId={props.clientId} />
		</InspectorControls>
	);
}
Example #22
Source File: Inspector.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function Inspector(prop) {
	const props = prop.data,
		{
			styling,
			styling: {
				backgroundColor,
				color,
				padding,
				borderColor,
				borderWidth,
				borderRadius,
			},
			condition,
			enableCondition,
		} = props.attributes;

	const handleStyling = (style, key) => {
		const groupStyling = clone(styling);

		set(groupStyling, key, style); //changing the color;

		props.setAttributes({ styling: groupStyling });
	};

	return (
		<InspectorControls>
			{isChildFieldsRequired(props.clientId) && enableCondition && (
				<Notice status="error" isDismissible={false}>
					{__(
						"Do not have a required fields inside a conditional group.",
						"cwp-gutenberg-forms"
					)}
				</Notice>
			)}
			<PanelBody title={__("Styling")}>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Background Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={backgroundColor}
						onChange={(color) => handleStyling(color, "backgroundColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={color}
						onChange={(color) => handleStyling(color, "color")}
					/>
				</div>

				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Border Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={borderColor}
						onChange={(color) => handleStyling(color, "borderColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Border Width [px]", "cwp-gutenberg-forms")}
					</h3>
					<RangeControl
						value={borderWidth}
						min={0}
						max={20}
						onChange={(borderWidth) =>
							handleStyling(borderWidth, "borderWidth")
						}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Border Radius [px]", "cwp-gutenberg-forms")}
					</h3>
					<RangeControl
						value={borderRadius}
						min={0}
						max={100}
						initialPosition={0}
						onChange={(value) => handleStyling(value, "borderRadius")}
					/>
				</div>
				<div className="cwp-option">
					<RangeControl
						value={padding}
						label={__("Padding", "cwp-gutenberg-forms")}
						onChange={(padd) => handleStyling(padd, "padding")}
					/>
				</div>
			</PanelBody>
			<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
				<ConditionalLogic
					condition={condition}
					set={props.setAttributes}
					clientId={props.clientId}
					useCondition={props.attributes.enableCondition}
				/>
			</PanelBody>
		</InspectorControls>
	);
}
Example #23
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleLabel = label => {
		props.setAttributes({ label });
	};

	const {
		calculation,
		label,
		field_name,
		condition,
		styling,
		formulaBuilder,
		postfix,
		prefix,
		adminId,
		decimalPlaces
	} = props.attributes;

	const setStyling = (style, styleName) => {
		const newStyling = clone(styling);

		set(newStyling, styleName, style);

		props.setAttributes({ styling: newStyling });
	};


	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {

			const newFieldName = getFieldName("calculation", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, 'calculation'),
					default: extract_admin_id(newFieldName, 'calculation')
				}
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData("calculation", props.clientId, false, get_admin_id(adminId))
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData("calculation", extract_id(field_name), false, get_admin_id(adminId))
			});
		}
	}

	useEffect(() => {
		getRootData()
	}, []);

	useEffect(() => {
		getRootData()
	}, [props]);


	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_")
			}
		})
	}

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")}>

					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<h3>{__("Prefix", "cwp-gutenberg-forms")}</h3>

						<TextControl
							value={prefix}
							onChange={val => props.setAttributes({ prefix: val })}
						/>
					</div>
					<div className="cwp-option">
						<h3>{__("Postfix", "cwp-gutenberg-forms")}</h3>

						<TextControl
							value={postfix}
							onChange={val => props.setAttributes({ postfix: val })}
						/>
					</div>
					<div className="cwp-option">
						<PanelRow>
							<h3>{__("Formula Editor", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								checked={formulaBuilder}
								onChange={() =>
									props.setAttributes({ formulaBuilder: !formulaBuilder })
								}
							/>
						</PanelRow>
					</div>
					<div className="cwp-option">
						<RangeControl
							value={decimalPlaces}
							min={0}
							max={10}
							label={__("Decimal Places", "cwp-gutenberg-forms")}
							onChange={decimalPlaces => props.setAttributes({ decimalPlaces })}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Styling", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<RangeControl
							value={styling.fontSize}
							label={__("Font Size", "cwp-gutenberg-forms")}
							onChange={size => setStyling(size, "fontSize")}
						/>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && (
			<BlockControls>
				<Toolbar>
					<Tooltip
						text={__(formulaBuilder ? __("Preview Field", "cwp-gutenberg-forms") : __("Formula Editor", "cwp-gutenberg-forms"))}
					>
						<Button
							onClick={() => {
								props.setAttributes({ formulaBuilder: !formulaBuilder });
							}}
						>
							<BlockIcon icon={formulaBuilder ? "no" : "edit"} showColors />
						</Button>
					</Tooltip>
				</Toolbar>
			</BlockControls>
		),

		<div className={`cwp-calculation cwp-field ${props.className}`}>
			<div className="cwp-calc-toggle">
				<h3>{__("Formula Editor", "cwp-gutenberg-forms")}</h3>
				<FormToggle
					checked={formulaBuilder}
					onChange={() =>
						props.setAttributes({ formulaBuilder: !formulaBuilder })
					}
				/>
			</div>
			{formulaBuilder ? (
				<FormulaBuilder data={props} />
			) : (
					<div className="cwp-field-set">
						<RichText placeholder={__("Add a label", "cwp-gutenberg-forms")} tag="label" value={label} onChange={handleLabel} />
						<div className="cwp-result-wrap">
							{!isEmpty(prefix) && <span style={styling}>{prefix}</span>}
							<span className="cwp-calc-result" style={styling}>
								XX
							</span>
							{!isEmpty(postfix) && <span style={styling}>{postfix}</span>}
						</div>
					</div>
				)}
		</div>
	];
}
Example #24
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const {
		styling,
		styling: { backgroundColor, color, padding, borderRadius },
		label,
		action,
	} = props.attributes;

	const buttonStyling = {
		...styling,
		padding: `${Math.floor(padding / 3)}px ${padding}px `,
	};

	const handleStyling = (style, key) => {
		const buttonStyling = clone(styling);

		set(buttonStyling, key, style); //changing the color;

		props.setAttributes({ styling: buttonStyling });
	};

	const handleAction = (newAction) => {
		props.setAttributes({ action: newAction });

		if (strip_tags(label).toLowerCase() === action) {
			props.setAttributes({ label: firstCapital(newAction) });
		}
	};

	React.useEffect(() => {
		const rootBlock = getRootFormBlock(props.clientId);
		const rootBlockId = get(rootBlock, "attributes.id");

		props.setAttributes({
			parentId: rootBlockId,
		});
	});

	const getActions = () => {
		const rootForm = getRootFormBlock(props.clientId);
		const rootType = get(rootForm, "attributes.formType"); //getting the type of form i.e multistep,standard;

		let actions = [
			{
				label: __("Reset", "cwp-gutenberg-forms"),
				value: "reset",
			},
			{
				label: __("Submit", "cwp-gutenberg-forms"),
				value: "submit",
			},
		];

		if (rootType === "multiStep") {
			actions.push(
				...[
					{
						label: __("Next", "cwp-gutenberg-forms"),
						value: "next",
					},
					{
						label: __("Previous", "cwp-gutenberg-forms"),
						value: "previous",
					},
				]
			);
		}

		return actions;
	};

	let actionLabel = __(<span>{__("Action", "cwp-gutenberg-forms")}</span>);

	return [
		<InspectorControls>
			<PanelBody title={__("Settings", "cwp-gutenberg-forms")}>
				<div className="cwp-option column">
					<h3>Action</h3>
					<div className="cwp-column">
						<SelectControl
							value={action}
							options={getActions()}
							onChange={(action) => handleAction(action)}
						/>
					</div>
				</div>
			</PanelBody>
			<PanelBody title={__("Colors", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Background Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={backgroundColor}
						onChange={(color) => handleStyling(color, "backgroundColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={color}
						onChange={(color) => handleStyling(color, "color")}
					/>
				</div>
				<div className="cwp-option">
					<RangeControl
						min={0}
						max={100}
						label={__("Padding", "cwp-gutenberg-forms")}
						value={padding}
						onChange={(p) => handleStyling(p, "padding")}
					/>
				</div>
				<div className="cwp-option">
					<RangeControl
						min={0}
						max={100}
						label={__("Border Radius", "cwp-gutenberg-forms")}
						value={borderRadius}
						onChange={(p) => handleStyling(p, "borderRadius")}
					/>
				</div>
			</PanelBody>
		</InspectorControls>,
		<BlockControls>
			<Toolbar>
				<DropdownMenu
					label={__("Select Action", "cwp-gutenberg-forms")}
					menuLabel={__("Action", "cwp-gutenberg-forms")}
					icon={actionLabel}
				>
					{() => (
						<Fragment>
							<MenuGroup>
								{getActions().map((a) => {
									let activeIcon = action === a.value ? "yes" : "no";

									return (
										<MenuItem
											type="radio"
											role="menuitemradio"
											isSelected={action === a.value}
											icon={activeIcon}
											onClick={() => handleAction(a.value)}
										>
											{a.label}
										</MenuItem>
									);
								})}
							</MenuGroup>
						</Fragment>
					)}
				</DropdownMenu>
			</Toolbar>
		</BlockControls>,
		,
		<button style={buttonStyling} className={props.className}>
			<RichText
				placeholder={__("Add a label", "cwp-gutenberg-forms")}
				tag="span"
				value={label}
				onChange={(label) => props.setAttributes({ label })}
			/>
		</button>,
	];
}
Example #25
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = e => {
		let file = e.target.value;

		props.setAttributes({ file });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = label => {
		props.setAttributes({ label });
	};

	const {
		file,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty, invalid },
		messages,
		condition,
		enableCondition,
		allowedFormats,
		adminId
	} = props.attributes;

	useEffect(() => {
		// setting the root encryption for form-data;

		const rootForm = getRootFormBlock(props.clientId);

		updateBlockAttributes(rootForm.clientId, { encryption: "multipart/form-data" }); //? like a piece of cake

	}, [])

	const setRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {


			const newFieldName = getFieldName("file_upload", props.clientId);


			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, 'file_upload'),
					default: extract_admin_id(newFieldName, 'file_upload')
				}
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData("file_upload", props.clientId, isRequired, get_admin_id(adminId), JSON.stringify(allowedFormats))
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData("file_upload", extract_id(field_name), isRequired, get_admin_id(adminId), JSON.stringify(allowedFormats))
			});
		}
	}

	useEffect(() => {
		let rootMessages = getRootMessages(props.clientId, "file-upload");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}
		setRootData();
	}, []);

	useEffect(() => {
		setRootData();
	}, [props])

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const suggestions = [
		"jpg",
		"jpeg",
		"png",
		"gif",
		"pdf",
		"doc",
		"docx",
		"ppt",
		"pptx",
		"odt",
		"avi",
		"ogg",
		"m4a",
		"mov",
		"mp3",
		"mp4",
		"mpg",
		"wav",
		"wmv"
	];

	const handleFormats = (newFormats) => {

		for (const format of newFormats) {
			if (!suggestions.includes(format)) {
				return;
			}
		}

		props.setAttributes({ allowedFormats: newFormats });
	}

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_")
			}
		})
	}

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>

					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
							<div className="cwp-option">
								<p>
									<Icon icon="info" /> {__("You cannot set a conditional field required!", "cwp-gutenberg-forms")}
								</p>
							</div>
						)}
					{isRequired && (
						<Fragment>
							<div className="cwp-option">
								<h3 className="cwp-heading">{__("Required Text", "cwp-gutenberg-forms")}</h3>
								<TextControl
									onChange={label =>
										props.setAttributes({ requiredLabel: label })
									}
									value={requiredLabel}
								/>
							</div>
						</Fragment>
					)}
					<div className="cwp-option column">
						<h3>{__("Allowed Formats", "cwp-gutenberg-forms")}</h3>
						<div className="cwp-column">
							<FormTokenField
								value={allowedFormats}
								suggestions={suggestions}
								onChange={f => handleFormats(f)}
								placeholder="Allowed Format(s)"
							/>
						</div>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">{__("Required Error", "cwp-gutenberg-forms")}</h3>
							<TextControl
								onChange={label => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">{__("Invalid File Error", "cwp-gutenberg-forms")}</h3>
						<TextControl
							onChange={v => setMessages("invalid", v)}
							value={invalid}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" /> {__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-file cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}
			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText placeholder={__("Add a label", "cwp-gutenberg-forms")} tag="label" value={label} onChange={handleLabel} />
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<input type="file" disabled required={isRequired} />
			</div>
		</div>
	];
}
Example #26
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		const email = e.target.value;

		props.setAttributes({ email });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		email,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty, invalidEmail },
		messages,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
		hint,
		showHint
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("email", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "email"),
					default: extract_admin_id(newFieldName, "email"),
				},
			});

			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"email",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"email",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		const rootMessages = getRootMessages(props.clientId, "email");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		const newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Prefix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">{__("Suffix", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<Fragment>
							<div className="cwp-option">
								<h3 className="cwp-heading">
									{__("Required Text", "cwp-gutenberg-forms")}
								</h3>
								<TextControl
									onChange={(label) =>
										props.setAttributes({ requiredLabel: label })
									}
									value={requiredLabel}
								/>
							</div>
						</Fragment>
					)}
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Email Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalidEmail", v)}
							value={invalidEmail}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-email cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}

					<input value={email} onChange={handleChange} />
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #27
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		const email = e.target.value;

		props.setAttributes({ email });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};

	const {
		email,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		messages: { empty, invalidEmail },
		messages,
		condition,
		enableCondition,
		adminId,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "" || detect_similar_forms(props.clientId)) {
			const newFieldName = getFieldName("email", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "email"),
					default: extract_admin_id(newFieldName, "email"),
				},
			});

			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"email",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"email",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		const rootMessages = getRootMessages(props.clientId, "email");

		if (rootMessages) {
			const newMessages = clone(messages);

			assign(newMessages, rootMessages);

			props.setAttributes({ messages: newMessages });
		}

		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const setMessages = (type, m) => {
		const newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label="Required"
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<Fragment>
							<div className="cwp-option">
								<h3 className="cwp-heading">
									{__("Required Text", "cwp-gutenberg-forms")}
								</h3>
								<TextControl
									onChange={(label) =>
										props.setAttributes({ requiredLabel: label })
									}
									value={requiredLabel}
								/>
							</div>
						</Fragment>
					)}
				</PanelBody>
				<PanelBody title={__("Messages", "cwp-gutenberg-forms")}>
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					)}
					<div className="cwp-option">
						<h3 className="cwp-heading">
							{__("Invalid Email Error", "cwp-gutenberg-forms")}
						</h3>
						<TextControl
							onChange={(v) => setMessages("invalidEmail", v)}
							value={invalidEmail}
						/>
					</div>
					<div className="cwp-option">
						<p>
							<Icon icon="info" />{" "}
							{__("Use {{value}} to insert field value!", "cwp-gutenberg-forms")}
						</p>
					</div>
				</PanelBody>
				<PanelBody title={__("Condition", "cwp-gutenberg-forms")}>
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-email cwp-field ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<input value={email} onChange={handleChange} />
			</div>
		</div>,
	];
}
Example #28
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let placeholder = e.target.value;

		props.setAttributes({ placeholder });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};
	const inputField = React.useRef();

	const {
		placeholder,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		type,
		messages: { empty },
		messages,
		format,
		condition,
		enableCondition,
		adminId,
		prefix,
		suffix,
		hint,
		showHint,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "") {
			const newFieldName = getFieldName("datePicker", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "datePicker"),
					default: extract_admin_id(newFieldName, "datePicker"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"datePicker",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"datePicker",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const getTypeActive = (t) => {
		if (type === t) {
			return {
				isDefault: true,
			};
		}

		return {
			isPrimary: true,
		};
	};

	let getFieldType = () => {
		switch (type) {
			case "both":
				return "datetime-local";
			case "time":
				return "time";
			case "date":
				return "date";
		}
	};

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	const handleInputElementChange = (type, property, value) => {
		const newSuffix = clone(suffix);
		const newPrefix = clone(prefix);

		switch (type) {
			case "suffix":
				set(newSuffix, property, value);
				props.setAttributes({ suffix: newSuffix });

				break;
			case "prefix":
				set(newPrefix, property, value);
				props.setAttributes({ prefix: newPrefix });
		}
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody
					title={__("Field Settings", "cwp-gutenberg-forms")}
					initialOpen={true}
				>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Prefix", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label="Prefix"
								checked={prefix.enable}
								onChange={() =>
									handleInputElementChange("prefix", "enable", !prefix.enable)
								}
							/>
						</PanelRow>
					</div>

					<div className="cwp-option">
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Suffix", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label="Suffix"
								checked={suffix.enable}
								onChange={() =>
									handleInputElementChange("suffix", "enable", !suffix.enable)
								}
							/>
						</PanelRow>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">
								{__("Required", "cwp-gutenberg-forms")}
							</h3>
							<FormToggle
								label={__("Required", "cwp-gutenberg-forms")}
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
					<div className="cwp-option">
						<SelectControl
							label={__("Format", "cwp-gutenberg-forms")}
							value={format}
							options={[
								{
									label: __("Day Month Year", "cwp-gutenberg-forms"),
									value: "DD/MM/YYYY",
								},
								{
									label: __("Month Day Year", "cwp-gutenberg-forms"),
									value: "MM/DD/YYYY",
								},
								{
									label: __("Year Month Day", "cwp-gutenberg-forms"),
									value: "YYYY/MM/DD",
								},
							]}
							onChange={(format) => {
								props.setAttributes({ format });
							}}
						/>
					</div>
				</PanelBody>
				<PanelBody title={__("Show Hint", "cwp-gutenberg-forms")}>
					<div className="cwp-option">
						<FormToggle
							label="Show Hint"
							checked={showHint}
							onChange={() => props.setAttributes({ showHint: !showHint })}
						/>
						{showHint && (
							<Fragment>
								<TextControl
									label={__("Hint Text", "cwp-gutenberg-forms")}
									onChange={(hint) => props.setAttributes({ hint })}
									value={hint}
								/>
							</Fragment>
						)}
					</div>
				</PanelBody>
				<PanelBody title="Condition">
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				{isRequired && (
					<PanelBody title="Messages">
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					</PanelBody>
				)}
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-field cwp-datepicker ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				<div className="cwp-field-with-elements">
					{prefix.enable && (
						<Prefix prefix={prefix}>
							<RichText
								placeholder={__("Prefix", "cwp-gutenberg-forms")}
								tag="span"
								value={prefix.content}
								onChange={(newContent) =>
									handleInputElementChange("prefix", "content", newContent)
								}
							/>
						</Prefix>
					)}
					{format === "DD/MM/YYYY" && (
						<DatePicker
							format={format}
							value={placeholder}
							onChange={handleChange}
							setAttributes={props.setAttributes}
						/>
					)}
					{format === "MM/DD/YYYY" && (
						<DatePicker
							format={format}
							value={placeholder}
							onChange={handleChange}
							setAttributes={props.setAttributes}
						/>
					)}
					{format === "YYYY/MM/DD" && (
						<DatePicker
							setAttributes={props.setAttributes}
							format={format}
							value={placeholder}
							onChange={handleChange}
						/>
					)}
					{suffix.enable && (
						<Suffix suffix={suffix}>
							<RichText
								placeholder={__("Suffix", "cwp-gutenberg-forms")}
								tag="span"
								value={suffix.content}
								onChange={(newContent) =>
									handleInputElementChange("suffix", "content", newContent)
								}
							/>
						</Suffix>
					)}
				</div>
			</div>
			{showHint && (
                <p className="cwp-hint">{hint}</p>
            )}
		</div>,
	];
}
Example #29
Source File: edit.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function edit(props) {
	const handleChange = (e) => {
		let placeholder = e.target.value;

		props.setAttributes({ placeholder });
	};

	const handleRequired = () => {
		const { isRequired } = props.attributes;

		props.setAttributes({ isRequired: !isRequired });
	};

	const handleLabel = (label) => {
		props.setAttributes({ label });
	};
	const inputField = React.useRef();

	const {
		placeholder,
		isRequired,
		label,
		id,
		field_name,
		requiredLabel,
		type,
		messages: { empty },
		messages,
		format,
		condition,
		enableCondition,
		adminId,
	} = props.attributes;

	const getRootData = () => {
		if (field_name === "") {
			const newFieldName = getFieldName("datePicker", props.clientId);

			props.setAttributes({
				field_name: newFieldName,
				adminId: {
					value: extract_admin_id(newFieldName, "datePicker"),
					default: extract_admin_id(newFieldName, "datePicker"),
				},
			});
			props.setAttributes({
				id:
					props.clientId +
					"__" +
					getEncodedData(
						"datePicker",
						props.clientId,
						isRequired,
						get_admin_id(adminId)
					),
			});
		} else if (field_name !== "") {
			props.setAttributes({
				id:
					extract_id(field_name) +
					"__" +
					getEncodedData(
						"datePicker",
						extract_id(field_name),
						isRequired,
						get_admin_id(adminId)
					),
			});
		}
	};

	useEffect(() => {
		getRootData();
	}, []);

	useEffect(() => getRootData(), [props]);

	const getTypeActive = (t) => {
		if (type === t) {
			return {
				isDefault: true,
			};
		}

		return {
			isPrimary: true,
		};
	};

	let getFieldType = () => {
		switch (type) {
			case "both":
				return "datetime-local";
			case "time":
				return "time";
			case "date":
				return "date";
		}
	};

	const setMessages = (type, m) => {
		let newMessages = clone(messages);

		set(newMessages, type, m);

		props.setAttributes({ messages: newMessages });
	};

	const handleAdminId = (id) => {
		props.setAttributes({
			adminId: {
				...adminId,
				value: id.replace(/\s|-/g, "_"),
			},
		});
	};

	return [
		!!props.isSelected && (
			<InspectorControls>
				<PanelBody title={__("Field Settings", "cwp-gutenberg-forms")} initialOpen={true}>
					<div className="cwp-option">
						<TextControl
							placeholder={adminId.default}
							label={__("Field ID", "cwp-gutenberg-forms")}
							value={adminId.value}
							onChange={handleAdminId}
						/>
					</div>

					{!enableCondition ? (
						<PanelRow>
							<h3 className="cwp-heading">{__("Required", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								label={__("Required", "cwp-gutenberg-forms")}
								checked={isRequired}
								onChange={handleRequired}
							/>
						</PanelRow>
					) : (
						<div className="cwp-option">
							<p>
								<Icon icon="info" />{" "}
								{__(
									"You cannot set a conditional field required!",
									"cwp-gutenberg-forms"
								)}
							</p>
						</div>
					)}
					{isRequired && (
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Text", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) =>
									props.setAttributes({ requiredLabel: label })
								}
								value={requiredLabel}
							/>
						</div>
					)}
					<div className="cwp-option">
						<SelectControl
							label={__("Format", "cwp-gutenberg-forms")}
							value={format}
							options={[
								{
									label: __("Day Month Year", "cwp-gutenberg-forms"),
									value: "DD/MM/YYYY",
								},
								{
									label: __("Month Day Year", "cwp-gutenberg-forms"),
									value: "MM/DD/YYYY",
								},
								{
									label: __("Year Month Day", "cwp-gutenberg-forms"),
									value: "YYYY/MM/DD",
								},
							]}
							onChange={(format) => {
								props.setAttributes({ format });
							}}
						/>
					</div>
				</PanelBody>
				<PanelBody title="Condition">
					<ConditionalLogic
						condition={condition}
						set={props.setAttributes}
						clientId={props.clientId}
						useCondition={props.attributes.enableCondition}
					/>
				</PanelBody>
				{isRequired && (
					<PanelBody title="Messages">
						<div className="cwp-option">
							<h3 className="cwp-heading">
								{__("Required Error", "cwp-gutenberg-forms")}
							</h3>
							<TextControl
								onChange={(label) => setMessages("empty", label)}
								value={empty}
							/>
						</div>
					</PanelBody>
				)}
			</InspectorControls>
		),
		!!props.isSelected && <BlockControls></BlockControls>,
		<div className={`cwp-field cwp-datepicker ${props.className}`}>
			{!!props.isSelected && !enableCondition && (
				<div className="cwp-required">
					<h3>{__("Required", "cwp-gutenberg-forms")}</h3>
					<FormToggle checked={isRequired} onChange={handleRequired} />
				</div>
			)}

			<div className="cwp-field-set">
				<div className="cwp-label-wrap">
					<RichText
						placeholder={__("Add a label", "cwp-gutenberg-forms")}
						tag="label"
						value={label}
						onChange={handleLabel}
					/>
					{!props.isSelected && isRequired && !enableCondition && (
						<div className="cwp-required cwp-noticed">
							<h3>{requiredLabel}</h3>
						</div>
					)}
				</div>
				{format === "DD/MM/YYYY" && (
					<DatePicker
						format={format}
						value={placeholder}
						onChange={handleChange}
						setAttributes={props.setAttributes}
					/>
				)}
				{format === "MM/DD/YYYY" && (
					<DatePicker
						format={format}
						value={placeholder}
						onChange={handleChange}
						setAttributes={props.setAttributes}
					/>
				)}
				{format === "YYYY/MM/DD" && (
					<DatePicker
						setAttributes={props.setAttributes}
						format={format}
						value={placeholder}
						onChange={handleChange}
					/>
				)}
			</div>
		</div>,
	];
}