aexol-studio / react-pdf-editor

Pdf editor react component
79 stars 16 forks source link

Add style validator #44

Open aexol opened 4 years ago

aexol commented 4 years ago

Add style validator so you cannot pass incorrect values to React PDF Editor

aexol commented 4 years ago

To start validator for number values

import ReactPDF from "@react-pdf/renderer";

/**
 * If style does not validate replace incorrect values with undefined to keep the up running and throw console.error only
 */
export const ReactPDFStyleValidator = (
  style: ReactPDF.Style
): ReactPDF.Style => {
  const copyStyle: ReactPDF.Style = {};
  const validateNumberValue = (v: string) => {
    const validatedNumber = parseFloat(v);
    if (!isNaN(validatedNumber)) {
      return v;
    }
    return undefined;
  };
  const numberKeys: Array<keyof ReactPDF.Style> = [
    "borderBottomLeftRadius",
    "borderBottomRightRadius",
    "borderBottomWidth",
    "borderRadius",
    "borderRightWidth",
    "borderTopLeftRadius",
    "borderTopRightRadius",
    "borderTopWidth",
    "borderWidth",
    "bottom",
    "fontSize",
    "height",
    "left",
    "letterSpacing",
    "lineHeight",
    "margin",
    "marginBottom",
    "marginHorizontal",
    "marginLeft",
    "marginRight",
    "marginTop",
    "marginVertical",
    "maxHeight",
    "minHeight",
    "minWidth",
    "maxWidth",
    "opacity",
    "order",
    "padding",
    "paddingBottom",
    "paddingHorizontal",
    "paddingLeft",
    "paddingRight",
    "paddingTop",
    "paddingVertical",
    "right",
    "width"
  ];
  numberKeys.forEach(k => {
    if (style[k]) {
      const v = validateNumberValue(style[k]);
      if (v) {
        copyStyle[k] = v;
      } else {
        console.error(`Key "${k}" has the incorrect value`);
      }
    }
  });
  return copyStyle;
};