"use strict";
const React = require("react");
const reactDnd = require("react-dnd");
const toolkit = require("@reduxjs/toolkit");
const index = require("./index-3649838b.js");
const helperPlugin = require("@strapi/helper-plugin");
const get = require("lodash/get");
const isBoolean = require("lodash/isBoolean");
const isEmpty = require("lodash/isEmpty");
const isNaN = require("lodash/isNaN");
const toNumber = require("lodash/toNumber");
const yup = require("yup");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
function _interopNamespace(e) {
  if (e && e.__esModule)
    return e;
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const get__default = /* @__PURE__ */ _interopDefault(get);
const isBoolean__default = /* @__PURE__ */ _interopDefault(isBoolean);
const isEmpty__default = /* @__PURE__ */ _interopDefault(isEmpty);
const isNaN__default = /* @__PURE__ */ _interopDefault(isNaN);
const toNumber__default = /* @__PURE__ */ _interopDefault(toNumber);
const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
const getTrad = (id) => `content-manager.${id}`;
const getTrad$1 = getTrad;
React.createContext();
const useKeyboardDragAndDrop = (active, index2, { onCancel, onDropItem, onGrabItem, onMoveItem }) => {
  const [isSelected, setIsSelected] = React.useState(false);
  const handleMove = (movement) => {
    if (!isSelected) {
      return;
    }
    if (movement === "UP") {
      onMoveItem(index2 - 1, index2);
    } else if (movement === "DOWN") {
      onMoveItem(index2 + 1, index2);
    }
  };
  const handleDragClick = () => {
    if (isSelected) {
      if (onDropItem) {
        onDropItem(index2);
      }
      setIsSelected(false);
    } else {
      if (onGrabItem) {
        onGrabItem(index2);
      }
      setIsSelected(true);
    }
  };
  const handleCancel = () => {
    if (isSelected) {
      setIsSelected(false);
      if (onCancel) {
        onCancel(index2);
      }
    }
  };
  const handleKeyDown = (e) => {
    if (!active) {
      return;
    }
    if (e.key === "Tab" && !isSelected) {
      return;
    }
    e.preventDefault();
    switch (e.key) {
      case " ":
      case "Enter":
        handleDragClick();
        break;
      case "Escape":
        handleCancel();
        break;
      case "ArrowDown":
      case "ArrowRight":
        handleMove("DOWN");
        break;
      case "ArrowUp":
      case "ArrowLeft":
        handleMove("UP");
        break;
    }
  };
  return handleKeyDown;
};
const useDragAndDrop = (active, {
  type = "STRAPI_DND",
  index: index2,
  item = {},
  onStart,
  onEnd,
  onGrabItem,
  onDropItem,
  onCancel,
  onMoveItem,
  dropSensitivity = "regular"
}) => {
  const objectRef = React.useRef(null);
  const [{ handlerId }, dropRef] = reactDnd.useDrop({
    accept: type,
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId()
      };
    },
    hover(item2, monitor) {
      if (!objectRef.current) {
        return;
      }
      const dragIndex = item2.index;
      const newInd = index2;
      if (dragIndex === newInd) {
        return;
      }
      if (dropSensitivity === "regular") {
        const hoverBoundingRect = objectRef.current.getBoundingClientRect();
        const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
        const clientOffset = monitor.getClientOffset();
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;
        if (dragIndex < newInd && hoverClientY < hoverMiddleY) {
          return;
        }
        if (dragIndex > newInd && hoverClientY > hoverMiddleY) {
          return;
        }
      }
      onMoveItem(newInd, dragIndex);
      item2.index = newInd;
    }
  });
  const [{ isDragging }, dragRef, dragPreviewRef] = reactDnd.useDrag({
    type,
    item() {
      if (onStart) {
        onStart();
      }
      const { width } = objectRef.current?.getBoundingClientRect() ?? {};
      return { index: index2, width, ...item };
    },
    end() {
      if (onEnd) {
        onEnd();
      }
    },
    canDrag: active,
    /**
     * This is for useful when the item is in a virtualized list.
     * However, if we don't have an ID then we want the libraries
     * defaults to take care of this.
     */
    isDragging: item.id ? (monitor) => {
      return item.id === monitor.getItem().id;
    } : void 0,
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });
  const handleKeyDown = useKeyboardDragAndDrop(active, index2, {
    onGrabItem,
    onDropItem,
    onCancel,
    onMoveItem
  });
  return [{ handlerId, isDragging, handleKeyDown }, objectRef, dropRef, dragRef, dragPreviewRef];
};
const selectAppDomain = () => (state) => {
  return state["content-manager_app"] || index.initialState$1;
};
const makeSelectModelLinks = () => toolkit.createSelector(selectAppDomain(), (state) => ({
  collectionTypeLinks: state.collectionTypeLinks,
  singleTypeLinks: state.singleTypeLinks
}));
const makeSelectModelAndComponentSchemas = () => toolkit.createSelector(selectAppDomain(), ({ components, models }) => ({
  schemas: [...components, ...models]
}));
const selectFieldSizes = toolkit.createSelector(selectAppDomain(), (state) => state.fieldSizes);
const setRef = (ref, value) => {
  if (typeof ref === "function") {
    ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
};
const composeRefs = (...refs) => {
  return (node) => refs.forEach((ref) => setRef(ref, node));
};
function isFieldTypeNumber(type) {
  return ["integer", "biginteger", "decimal", "float", "number"].includes(type);
}
yup__namespace.addMethod(yup__namespace.mixed, "defined", function() {
  return this.test("defined", helperPlugin.translatedErrors.required, (value) => value !== void 0);
});
yup__namespace.addMethod(yup__namespace.array, "notEmptyMin", function(min) {
  return this.test("notEmptyMin", helperPlugin.translatedErrors.min, (value) => {
    if (isEmpty__default.default(value)) {
      return true;
    }
    return value.length >= min;
  });
});
yup__namespace.addMethod(yup__namespace.string, "isInferior", function(message, max) {
  return this.test("isInferior", message, function(value) {
    if (!value) {
      return true;
    }
    if (Number.isNaN(toNumber__default.default(value))) {
      return true;
    }
    return toNumber__default.default(max) >= toNumber__default.default(value);
  });
});
yup__namespace.addMethod(yup__namespace.string, "isSuperior", function(message, min) {
  return this.test("isSuperior", message, function(value) {
    if (!value) {
      return true;
    }
    if (Number.isNaN(toNumber__default.default(value))) {
      return true;
    }
    return toNumber__default.default(value) >= toNumber__default.default(min);
  });
});
const getAttributes = (data) => get__default.default(data, ["attributes"], {});
const createYupSchema = (model, { components }, options = {
  isCreatingEntry: true,
  isDraft: true,
  isFromComponent: false,
  isJSONTestDisabled: false
}) => {
  const attributes = getAttributes(model);
  return yup__namespace.object().shape(
    Object.keys(attributes).reduce((acc, current) => {
      const attribute = attributes[current];
      if (attribute.type !== "relation" && attribute.type !== "component" && attribute.type !== "dynamiczone") {
        const formatted = createYupSchemaAttribute(attribute.type, attribute, options);
        acc[current] = formatted;
      }
      if (attribute.type === "relation") {
        acc[current] = [
          "oneWay",
          "oneToOne",
          "manyToOne",
          "oneToManyMorph",
          "oneToOneMorph"
        ].includes(attribute.relationType) ? yup__namespace.object().nullable() : yup__namespace.array().nullable();
      }
      if (attribute.type === "component") {
        const componentFieldSchema = createYupSchema(
          components[attribute.component],
          {
            components
          },
          { ...options, isFromComponent: true }
        );
        if (attribute.repeatable === true) {
          const { min, max, required } = attribute;
          let componentSchema2 = yup__namespace.lazy((value) => {
            let baseSchema = yup__namespace.array().of(componentFieldSchema);
            if (min) {
              if (required) {
                baseSchema = baseSchema.min(min, helperPlugin.translatedErrors.min);
              } else if (required !== true && isEmpty__default.default(value)) {
                baseSchema = baseSchema.nullable();
              } else {
                baseSchema = baseSchema.min(min, helperPlugin.translatedErrors.min);
              }
            } else if (required && !options.isDraft) {
              baseSchema = baseSchema.min(1, helperPlugin.translatedErrors.required);
            }
            if (max) {
              baseSchema = baseSchema.max(max, helperPlugin.translatedErrors.max);
            }
            return baseSchema;
          });
          acc[current] = componentSchema2;
          return acc;
        }
        const componentSchema = yup__namespace.lazy((obj) => {
          if (obj !== void 0) {
            return attribute.required === true && !options.isDraft ? componentFieldSchema.defined() : componentFieldSchema.nullable();
          }
          return attribute.required === true ? yup__namespace.object().defined() : yup__namespace.object().nullable();
        });
        acc[current] = componentSchema;
        return acc;
      }
      if (attribute.type === "dynamiczone") {
        let dynamicZoneSchema = yup__namespace.array().of(
          yup__namespace.lazy(({ __component }) => {
            return createYupSchema(
              components[__component],
              { components },
              { ...options, isFromComponent: true }
            );
          })
        );
        const { max, min } = attribute;
        if (min) {
          if (attribute.required) {
            dynamicZoneSchema = dynamicZoneSchema.test("min", helperPlugin.translatedErrors.min, (value) => {
              if (options.isCreatingEntry) {
                return value && value.length >= min;
              }
              if (value === void 0) {
                return true;
              }
              return value !== null && value.length >= min;
            }).test("required", helperPlugin.translatedErrors.required, (value) => {
              if (options.isCreatingEntry) {
                return value !== null || value !== void 0;
              }
              if (value === void 0) {
                return true;
              }
              return value !== null;
            });
          } else {
            dynamicZoneSchema = dynamicZoneSchema.notEmptyMin(min);
          }
        } else if (attribute.required && !options.isDraft) {
          dynamicZoneSchema = dynamicZoneSchema.test("required", helperPlugin.translatedErrors.required, (value) => {
            if (options.isCreatingEntry) {
              return value !== null || value !== void 0;
            }
            if (value === void 0) {
              return true;
            }
            return value !== null;
          });
        }
        if (max) {
          dynamicZoneSchema = dynamicZoneSchema.max(max, helperPlugin.translatedErrors.max);
        }
        acc[current] = dynamicZoneSchema;
      }
      return acc;
    }, {})
  );
};
const createYupSchemaAttribute = (type, validations, options) => {
  let schema = yup__namespace.mixed();
  if (["string", "uid", "text", "richtext", "email", "password", "enumeration"].includes(type)) {
    schema = yup__namespace.string();
  }
  if (type === "blocks") {
    schema = yup__namespace.mixed().test("isJSON", helperPlugin.translatedErrors.json, (value) => {
      if (options.isJSONTestDisabled) {
        return true;
      }
      if (options.isDraft) {
        return true;
      }
      if (value && !Array.isArray(value)) {
        return false;
      }
      return true;
    });
  }
  if (type === "json") {
    schema = yup__namespace.mixed(helperPlugin.translatedErrors.json).test("isJSON", helperPlugin.translatedErrors.json, (value) => {
      if (options.isJSONTestDisabled) {
        return true;
      }
      if (!value || !value.length) {
        return true;
      }
      try {
        JSON.parse(value);
        return true;
      } catch (err) {
        return false;
      }
    }).nullable().test("required", helperPlugin.translatedErrors.required, (value) => {
      if (validations.required && (!value || !value.length)) {
        return false;
      }
      return true;
    });
  }
  if (type === "email") {
    schema = schema.email(helperPlugin.translatedErrors.email);
  }
  if (["number", "integer", "float", "decimal"].includes(type)) {
    schema = yup__namespace.number().transform((cv) => isNaN__default.default(cv) ? void 0 : cv).typeError();
  }
  if (type === "biginteger") {
    schema = yup__namespace.string().matches(/^-?\d*$/);
  }
  if (["date", "datetime"].includes(type)) {
    schema = yup__namespace.date();
  }
  Object.keys(validations).forEach((validation) => {
    const validationValue = validations[validation];
    if (!!validationValue || !isBoolean__default.default(validationValue) && Number.isInteger(Math.floor(validationValue)) || validationValue === 0) {
      switch (validation) {
        case "required": {
          if (!options.isDraft) {
            if (type === "password" && options.isCreatingEntry) {
              schema = schema.required(helperPlugin.translatedErrors.required);
            }
            if (type !== "password") {
              if (options.isCreatingEntry) {
                schema = schema.required(helperPlugin.translatedErrors.required);
              } else {
                schema = schema.test("required", helperPlugin.translatedErrors.required, (value) => {
                  if (value === void 0 && !options.isFromComponent) {
                    return true;
                  }
                  if (isFieldTypeNumber(type)) {
                    if (value === 0) {
                      return true;
                    }
                    return !!value;
                  }
                  if (type === "boolean") {
                    return value !== null && value !== void 0;
                  }
                  if (type === "date" || type === "datetime") {
                    if (typeof value === "string") {
                      return !isEmpty__default.default(value);
                    }
                    return !isEmpty__default.default(value?.toString());
                  }
                  return !isEmpty__default.default(value);
                });
              }
            }
          }
          break;
        }
        case "max": {
          if (type === "biginteger") {
            schema = schema.isInferior(helperPlugin.translatedErrors.max, validationValue);
          } else {
            schema = schema.max(validationValue, helperPlugin.translatedErrors.max);
          }
          break;
        }
        case "maxLength":
          schema = schema.max(validationValue, helperPlugin.translatedErrors.maxLength);
          break;
        case "min": {
          if (type === "biginteger") {
            schema = schema.isSuperior(helperPlugin.translatedErrors.min, validationValue);
          } else {
            schema = schema.min(validationValue, helperPlugin.translatedErrors.min);
          }
          break;
        }
        case "minLength": {
          if (!options.isDraft) {
            schema = schema.min(validationValue, helperPlugin.translatedErrors.minLength);
          }
          break;
        }
        case "regex":
          schema = schema.matches(new RegExp(validationValue), {
            message: helperPlugin.translatedErrors.regex,
            excludeEmptyString: !validations.required
          });
          break;
        case "lowercase":
          if (["text", "textarea", "email", "string"].includes(type)) {
            schema = schema.strict().lowercase();
          }
          break;
        case "uppercase":
          if (["text", "textarea", "email", "string"].includes(type)) {
            schema = schema.strict().uppercase();
          }
          break;
        case "positive":
          if (isFieldTypeNumber(type)) {
            schema = schema.positive();
          }
          break;
        case "negative":
          if (isFieldTypeNumber(type)) {
            schema = schema.negative();
          }
          break;
        default:
          schema = schema.nullable();
      }
    }
  });
  return schema;
};
exports.composeRefs = composeRefs;
exports.createYupSchema = createYupSchema;
exports.getTrad = getTrad$1;
exports.isFieldTypeNumber = isFieldTypeNumber;
exports.makeSelectModelAndComponentSchemas = makeSelectModelAndComponentSchemas;
exports.makeSelectModelLinks = makeSelectModelLinks;
exports.selectAppDomain = selectAppDomain;
exports.selectFieldSizes = selectFieldSizes;
exports.useDragAndDrop = useDragAndDrop;
//# sourceMappingURL=schema-34663b27.js.map
