diff --git a/ui/src/pages/Generator/QRcode/index.tsx b/ui/src/pages/Generator/QRcode/index.tsx index 47a7623f..653f8f74 100644 --- a/ui/src/pages/Generator/QRcode/index.tsx +++ b/ui/src/pages/Generator/QRcode/index.tsx @@ -5,15 +5,16 @@ import { downloadQRCode } from "./utils/helper"; import style from "./QRcode.module.scss"; import DropdownDownloadButton from "components/General/DropdownDownloadButton"; import Warning from "components/General/Warning"; -import { detectData } from "pages/Tools/Sorting/utils/helper"; import ColorPickerWithInput from "components/General/ColorPickerWithInput"; import { ResponsiveInputWithLabel } from "components/General/FormComponents"; import { handleImageUpload } from "utils/helper-functions/files"; import QRCodeErrorBoundary from "./components/QRCodeErrorBoundary"; import { classNames } from "utils/helper-functions/string"; +import { DataDetection } from "utils/helper-classes/ DataDetection"; const { TextArea } = Input; +const detection = new DataDetection(["number", "string", "url"]); const QRcode: React.FC = () => { const [value, setValue] = useState(""); const [dataType, setDataType] = useState(""); @@ -25,7 +26,8 @@ const QRcode: React.FC = () => { const [iconSize, setIconSize] = useState(size / 4); useEffect(() => { - setDataType(detectData(value)); + detection.setData(value); + setDataType(detection.detect()); }, [value]); return ( diff --git a/ui/src/utils/helper-classes/ DataDetection.ts b/ui/src/utils/helper-classes/ DataDetection.ts new file mode 100644 index 00000000..fbcf665a --- /dev/null +++ b/ui/src/utils/helper-classes/ DataDetection.ts @@ -0,0 +1,60 @@ +export type DataType = + | "number" + | "string" + | "array" + | "boolean" + | "null" + | "object" + | "url" + | "No data" + | "Can't detect data"; + +export class DataDetection { + data: string | null = null; + typesToDetect: DataType[]; + + constructor(typesToDetect: DataType[]) { + this.typesToDetect = typesToDetect; + } + + setData(data: string): void { + this.data = data; + } + + private isUrl(): boolean { + const urlRegex = + /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/; + return urlRegex.test(this.data as string); + } + + detect(): DataType { + if (!this.data) { + return "No data"; + } + + if (this.typesToDetect.includes("url") && this.isUrl()) { + return "url"; + } + + try { + const parsedData = JSON.parse(this.data); + const actualType: DataType = Array.isArray(parsedData) + ? "array" + : parsedData === null + ? "null" + : (typeof parsedData as DataType); + + if (this.typesToDetect.includes(actualType)) { + return actualType; + } + } catch (error) { + if (this.typesToDetect.includes("string")) { + return "string"; + } + } + + if (this.data === "[]" || this.data === "{}") return "string"; + + return "Can't detect data"; + } +}