diff --git a/.idea/workspace.xml b/.idea/workspace.xml index b03acf61..4a41825b 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,16 +4,22 @@ - + - - + + + + + + + + @@ -366,11 +372,15 @@ + + + + { "associatedIndex": 0 } - + @@ -391,9 +401,12 @@ "Playwright.Create transparent PNG.should make png color transparent.executor": "Run", "Playwright.JoinText Component.executor": "Run", "Playwright.JoinText Component.should merge text pieces with specified join character.executor": "Run", + "RunOnceActivity.MCP Project settings loaded": "true", "RunOnceActivity.OpenProjectViewOnStart": "true", "RunOnceActivity.ShowReadmeOnStart": "true", + "RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true", "RunOnceActivity.git.unshallow": "true", + "RunOnceActivity.typescript.service.memoryLimit.init": "true", "Vitest.compute function (1).executor": "Run", "Vitest.compute function.executor": "Run", "Vitest.generatePassword.executor": "Run", @@ -407,8 +420,10 @@ "Vitest.replaceText function (regexp mode).should return the original text when passed an invalid regexp.executor": "Run", "Vitest.replaceText function.executor": "Run", "Vitest.timeBetweenDates.executor": "Run", + "com.intellij.ml.llm.matterhorn.ej.ui.settings.DefaultModelSelectionForGA.v1": "true", "git-widget-placeholder": "main", "ignore.virus.scanning.warn.message": "true", + "junie.onboarding.icon.badge.shown": "true", "kotlin-language-version-configured": "true", "last_opened_file_path": "C:/Users/Ibrahima/IdeaProjects/omni-tools", "node.js.detected.package.eslint": "true", @@ -434,6 +449,7 @@ "project.structure.proportion": "0.0", "project.structure.side.proportion": "0.2", "settings.editor.selected.configurable": "preferences.pluginManager", + "to.speed.mode.migration.done": "true", "ts.external.directory.path": "C:\\Users\\Ibrahima\\IdeaProjects\\omni-tools\\node_modules\\typescript\\lib", "ts.rename.search.for.js.occurrences": "false", "vue.rearranger.settings.migration": "true" @@ -464,7 +480,7 @@ - + @@ -527,16 +543,16 @@ + + - - - + @@ -546,8 +562,8 @@ - - + + @@ -660,31 +676,12 @@ - - - - - 1752026153328 - - - - 1752026153328 - - - - 1752032092273 - - - - 1752032092274 - - - - 1752071147050 - - - - 1752071147050 + + + + + + @@ -1054,7 +1051,31 @@ 1759503051936 - + + + 1759503311355 + + + + 1759503311355 + + + + 1775676005437 + + + + 1775676005437 + + + + 1775769625178 + + + + 1775769625180 + + @@ -1118,11 +1139,6 @@ - - - - - @@ -1138,12 +1154,17 @@ - - - + + + + + + + + false @@ -1153,4 +1174,12 @@ + + + + + + + + \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 91491f32..919848c0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "omni-tools", - "version": "0.1.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "omni-tools", - "version": "0.1.0", + "version": "0.6.0", "dependencies": { "@emotion/react": "^11.11.4", "@emotion/styled": "^11.11.5", @@ -43,6 +43,7 @@ "i18next-http-backend": "^3.0.2", "jimp": "^0.22.12", "js-quantities": "^1.8.0", + "json5": "^2.2.3", "jspdf": "^3.0.3", "jszip": "^3.10.1", "lint-staged": "^15.4.3", @@ -69,6 +70,7 @@ "react-router-dom": "^6.23.1", "styled-components": "^6.1.19", "tesseract.js": "^6.0.0", + "to-words": "^5.6.1", "type-fest": "^4.35.0", "use-deep-compare-effect": "^1.8.1", "yup": "^1.4.0" @@ -8675,6 +8677,18 @@ "dev": true, "license": "MIT" }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/jsonparse": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", @@ -13031,6 +13045,22 @@ "node": ">=8.0" } }, + "node_modules/to-words": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/to-words/-/to-words-5.6.1.tgz", + "integrity": "sha512-I2tQDzfUjFUbBiRFkoN4qYvm88us5h/hXayyfsszlWK21NY5fGRU0BOURrejmh55isf6lEt1rCstW9ezkdXFyw==", + "license": "MIT", + "bin": { + "to-words": "dist/cjs/cli.js" + }, + "engines": { + "node": ">=20.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/mastermunj" + } + }, "node_modules/token-types": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/token-types/-/token-types-4.2.1.tgz", diff --git a/package.json b/package.json index 059f9e2d..8f956406 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "omni-tools", "description": "This project offers a variety of online tools to help with everyday tasks, \nall available for free and open for community contributions", - "version": "0.1.0", + "version": "0.6.0", "private": true, "author": { "name": "Ibrahima Gaye Coulibaly", @@ -62,6 +62,7 @@ "i18next-http-backend": "^3.0.2", "jimp": "^0.22.12", "js-quantities": "^1.8.0", + "json5": "^2.2.3", "jspdf": "^3.0.3", "jszip": "^3.10.1", "lint-staged": "^15.4.3", @@ -88,6 +89,7 @@ "react-router-dom": "^6.23.1", "styled-components": "^6.1.19", "tesseract.js": "^6.0.0", + "to-words": "^5.6.1", "type-fest": "^4.35.0", "use-deep-compare-effect": "^1.8.1", "yup": "^1.4.0" diff --git a/public/locales/de/audio.json b/public/locales/de/audio.json index e5fd99dc..e9cfc087 100644 --- a/public/locales/de/audio.json +++ b/public/locales/de/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Geschwindigkeit einstellen", "shortDescription": "Ändern Sie die Geschwindigkeit von Audiodateien", "speedDescription": "Standardmultiplikator: 2 bedeutet 2x schneller", - "title": "Audiogeschwindigkeit ändern", - "toolInfo": { - "title": "Was ist {{title}}?" - } + "title": "Audiogeschwindigkeit ändern" }, "extractAudio": { "description": "Extrahieren Sie Audiospuren aus Videodateien.", @@ -31,7 +28,6 @@ "description": "Kombinieren Sie mehrere Audiodateien zu einer einzigen Audiodatei, indem Sie sie der Reihe nach aneinanderreihen.", "inputTitle": "Audiodateien eingeben", "longDescription": "Mit diesem Tool können Sie mehrere Audiodateien in der Reihenfolge des Hochladens zu einer einzigen Datei zusammenfügen. Ideal zum Kombinieren von Podcast-Segmenten, Musiktiteln oder anderen Audiodateien. Unterstützt verschiedene Audioformate, darunter MP3, AAC und WAV.", - "mergingAudio": "Audio zusammenführen", "outputFormat": "Ausgabeformat", "resultTitle": "Zusammengeführtes Audio", "shortDescription": "Mehrere Audiodateien zu einer zusammenführen (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Audio trimmen", "toolInfo": { "title": "Was ist {{title}}?" - }, - "trimmingAudio": "Audio trimmen" + } } } diff --git a/public/locales/de/string.json b/public/locales/de/string.json index dbf0e8bb..112e57eb 100644 --- a/public/locales/de/string.json +++ b/public/locales/de/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Zahlen einschließen (0-9)", "includeSymbols": "Sonderzeichen einschließen", "includeUppercase": "Großbuchstaben einschließen (A-Z)", - "lengthDesc": "Länge des Passwortes", + "lengthDesc": "Länge des Passwortes (>3 & <257)", "lengthPlaceholder": "z.B. 12", "optionsTitle": "Passwortoptionen", "resultTitle": "Generiertes Passwort", diff --git a/public/locales/de/time.json b/public/locales/de/time.json index 2deb733b..5d4d6d1a 100644 --- a/public/locales/de/time.json +++ b/public/locales/de/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Datum → Unix", "description": "Unix-Zeitstempel in lesbare Daten und Datumsangaben in Unix-Zeitstempel konvertieren (beide Richtungen).", "optionsTitle": "Konvertierungsmodus", - "outputOptions": "Ausgabeoptionen", "shortDescription": "Unix-Zeitstempel und Daten in beide Richtungen konvertieren.", "title": "Unix ↔ Datum konvertieren", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "UTC verwenden" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Analysieren und erklären Sie Cron-Ausdrücke auf Deutsch. Verstehen Sie sofort, was ein Cron-Zeitplan bewirkt, validieren Sie die Syntax und verarbeiten Sie mehrere Ausdrücke gleichzeitig.", + "longDescription": "Crontab Guru ist ein Cron-Ausdruck-Parser und -Validator, der komplexe Cron-Syntax in klare, lesbare Beschreibungen übersetzt. Egal ob Sie automatische Backups, Systemwartungsaufgaben oder CI/CD-Pipelines planen – dieses Tool hilft Ihnen zu verstehen, wann genau Ihre Jobs ausgeführt werden. Unterstützt standardmäßige 5-Feld-Cron-Ausdrücke, validiert die Syntax in Echtzeit und verarbeitet mehrere Ausdrücke gleichzeitig – einen pro Zeile. Verfügbar auf Englisch, Französisch, Spanisch, Deutsch, Japanisch, Chinesisch, Portugiesisch, Niederländisch und Russisch.", "shortDescription": "Cron-Ausdrücke analysieren und verständlich erklären", - "longDescription": "Crontab Guru ist ein Cron-Ausdruck-Parser und -Validator, der komplexe Cron-Syntax in klare, lesbare Beschreibungen übersetzt. Egal ob Sie automatische Backups, Systemwartungsaufgaben oder CI/CD-Pipelines planen – dieses Tool hilft Ihnen zu verstehen, wann genau Ihre Jobs ausgeführt werden. Unterstützt standardmäßige 5-Feld-Cron-Ausdrücke, validiert die Syntax in Echtzeit und verarbeitet mehrere Ausdrücke gleichzeitig – einen pro Zeile. Verfügbar auf Englisch, Französisch, Spanisch, Deutsch, Japanisch, Chinesisch, Portugiesisch, Niederländisch und Russisch." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Berechnen Sie die Zeitdifferenz zwischen zwei Daten. Ermitteln Sie die genaue Dauer in Tagen, Stunden, Minuten und Sekunden.", diff --git a/public/locales/de/translation.json b/public/locales/de/translation.json index 5292eb0e..4b8189a0 100644 --- a/public/locales/de/translation.json +++ b/public/locales/de/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Video zuschneiden" }, "search": { - "placeholder": "Alle Tools durchsuchen", - "noResult": "Keine Ergebnisse gefunden, versuchen Sie Ihre Suche oder Filterkriterien anzupassen" + "noResult": "Keine Ergebnisse gefunden, versuchen Sie Ihre Suche oder Filterkriterien anzupassen", + "placeholder": "Alle Tools durchsuchen" }, "title": "Erledigen Sie Dinge schnell mit" }, @@ -229,9 +229,9 @@ "result": "Ergebnis" }, "toolMultipleInput": { + "deleteFile": "Datei löschen", "inputTitle": "Eingabe {{type}}", - "noFilesSelected": "Keine Dateien ausgewählt", - "deleteFile": "Datei löschen" + "noFilesSelected": "Keine Dateien ausgewählt" }, "toolOptions": { "title": "Werkzeugoptionen" diff --git a/public/locales/de/video.json b/public/locales/de/video.json index 69cd41e0..2fa97fae 100644 --- a/public/locales/de/video.json +++ b/public/locales/de/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Standardmultiplikator: 2 bedeutet 2x schneller", "description": "Ändern Sie die Wiedergabegeschwindigkeit von Videodateien. Beschleunigen oder verlangsamen Sie Videos, während die Audiosynchronisation erhalten bleibt. Unterstützt verschiedene Geschwindigkeitsmultiplikatoren und gängige Videoformate.", "inputTitle": "Eingangsvideo", - "newVideoSpeed": "Neue Videogeschwindigkeit", "resultTitle": "Bearbeitetes Video", - "settingSpeed": "Geschwindigkeit einstellen", "shortDescription": "Ändern der Videowiedergabegeschwindigkeit", "title": "Videogeschwindigkeit ändern", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Drehen Sie Videodateien horizontal oder vertikal. Spiegeln Sie Videos für Spezialeffekte oder zum Korrigieren von Ausrichtungsproblemen.", - "flippingVideo": "Video spiegeln", "horizontalLabel": "Horizontal (Spiegel)", "inputTitle": "Eingangsvideo", "orientation": "Orientierung", @@ -73,7 +69,6 @@ "loop": { "description": "Erstellen Sie ein Loop-Video, indem Sie das Originalvideo mehrmals wiederholen.", "inputTitle": "Eingangsvideo", - "loopingVideo": "Videoschleife", "loops": "Schleifen", "numberOfLoops": "Anzahl der Schleifen", "resultTitle": "Videoschleife", @@ -97,7 +92,6 @@ "description": "Drehen Sie Videodateien um 90, 180 oder 270 Grad. Korrigieren Sie die Videoausrichtung oder erstellen Sie Spezialeffekte mit präziser Rotationssteuerung.", "inputTitle": "Eingangsvideo", "resultTitle": "Gedrehtes Video", - "rotatingVideo": "Rotierendes Video", "rotation": "Drehung", "shortDescription": "Video um angegebene Gradzahlen drehen", "title": "Video drehen" @@ -111,10 +105,5 @@ "startTime": "Startzeit", "timestamps": "Zeitstempel", "title": "Video trimmen" - }, - "videoToGif": { - "description": "Konvertieren Sie Videodateien in das animierte GIF-Format. Extrahieren Sie bestimmte Zeitbereiche und erstellen Sie gemeinsam nutzbare animierte Bilder.", - "shortDescription": "Video in animiertes GIF konvertieren", - "title": "Video zu GIF" } } diff --git a/public/locales/en/audio.json b/public/locales/en/audio.json index 5984b69b..faa776ed 100644 --- a/public/locales/en/audio.json +++ b/public/locales/en/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Setting Speed", "shortDescription": "Change the speed of audio files", "speedDescription": "Default multiplier: 2 means 2x faster", - "title": "Change audio speed", - "toolInfo": { - "title": "What is {{title}}?" - } + "title": "Change audio speed" }, "extractAudio": { "description": "Extract audio track from video files.", @@ -31,7 +28,6 @@ "description": "Combine multiple audio files into a single audio file by concatenating them in sequence.", "inputTitle": "Input Audio Files", "longDescription": "This tool allows you to merge multiple audio files into a single file by concatenating them in the order you upload them. Perfect for combining podcast segments, music tracks, or any audio files that need to be joined together. Supports various audio formats including MP3, AAC, and WAV.", - "mergingAudio": "Merging Audio", "outputFormat": "Output Format", "resultTitle": "Merged Audio", "shortDescription": "Merge multiple audio files into one (MP3, AAC, WAV).", @@ -54,8 +50,8 @@ "timeSettings": "Time Settings", "title": "Trim Audio", "toolInfo": { + "longDescription": "This tool allows you to trim audio files by specifying start and end times with sub-second precision. You can extract specific segments from longer audio files, remove unwanted parts, or create shorter clips. Supports various audio formats including MP3, AAC, and WAV. Perfect for podcast editing, music production, or any audio editing needs.", "title": "What is {{title}}?" - }, - "trimmingAudio": "Trimming Audio" + } } } diff --git a/public/locales/en/converters.json b/public/locales/en/converters.json index a2943af4..652e739f 100644 --- a/public/locales/en/converters.json +++ b/public/locales/en/converters.json @@ -36,5 +36,22 @@ "resultTitle": "WEBP Images", "shortDescription": "Convert Images to WebP Format with quality control.", "title": "Convert Images to WebP" + }, + "videoToGif": { + "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", + "inputTitle": "Input Video", + "options": { + "endTime": "End Time", + "high": "High", + "low": "Low", + "mid": "Medium", + "quality": "Quality", + "startTime": "Start Time", + "timestamps": "Timestamps", + "ultra": "Ultra" + }, + "resultTitle": "Output GIF", + "shortDescription": "Convert video to animated GIF", + "title": "Video to GIF" } } diff --git a/public/locales/en/image.json b/public/locales/en/image.json index e99cb111..c887a62e 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -1,22 +1,22 @@ { "changeColors": { "description": "Change specific colors in an image by selecting a source color and replacing it with a new one.", - "shortDescription": "Quickly swap colors in a image", - "title": "Change colors in image", + "fromColor": { + "colorOption": "Replace a specific color", + "selectorDescription": "Replace this color (from color)", + "similarityDescription": "Match this % of similar colors of the from color. For example, 10% white will match white and a little bit of gray.", + "title": "From color", + "transparentOption": "Replace transparent pixels" + }, "inputTitle": "Input image", "resultTitle": "Result image", - "fromColor": { - "title": "From color", - "colorOption": "Replace a specific color", - "transparentOption": "Replace transparent pixels", - "selectorDescription": "Replace this color (from color)", - "similarityDescription": "Match this % of similar colors of the from color. For example, 10% white will match white and a little bit of gray." - }, + "shortDescription": "Quickly swap colors in a image", + "title": "Change colors in image", "toColor": { - "title": "To color", "colorOption": "Replace with a specific color", - "transparentOption": "Replace with transparent", - "selectorDescription": "With this color (to color)" + "selectorDescription": "With this color (to color)", + "title": "To color", + "transparentOption": "Replace with transparent" } }, "changeOpacity": { @@ -74,6 +74,127 @@ }, "qrCode": { "description": "Generate QR codes for different data types: URL, Text, Email, Phone, SMS, WiFi, vCard, and more.", + "groups": { + "details": { + "email": { + "address": { + "description": "Email Address", + "placeholder": "example@example.com" + }, + "body": { + "description": "Email Body (optional)", + "placeholder": "Body text" + }, + "subject": { + "description": "Email Subject (optional)", + "placeholder": "Subject line" + } + }, + "phone": { + "description": "Phone Number", + "placeholder": "+1234567890" + }, + "sms": { + "message": { + "description": "Message (optional)", + "placeholder": "Your message here" + }, + "number": { + "description": "Phone Number", + "placeholder": "+1234567890" + } + }, + "text": { + "description": "Enter the text", + "placeholder": "Enter your text here" + }, + "title": "{{type}} Details", + "url": { + "description": "Enter the URL", + "placeholder": "https://example.com" + }, + "vcard": { + "address": { + "description": "Address", + "placeholder": "123 Main St, City, Country" + }, + "company": { + "description": "Company (optional)", + "placeholder": "Company name" + }, + "email": { + "description": "Email", + "placeholder": "john@example.com" + }, + "name": { + "description": "Full Name", + "placeholder": "John Doe" + }, + "phone": { + "description": "Phone", + "placeholder": "+1234567890" + }, + "title": { + "description": "Job Title (optional)", + "placeholder": "Software Developer" + }, + "website": { + "description": "Website (optional)", + "placeholder": "https://example.com" + } + }, + "wifi": { + "encryption": { + "label": "Encryption Type", + "options": { + "none": "None", + "wep": "WEP", + "wpa": "WPA" + } + }, + "password": { + "description": "Password", + "placeholder": "Password" + }, + "ssid": { + "description": "Network Name (SSID)", + "placeholder": "Network name" + } + } + }, + "settings": { + "bgColor": "Background Color", + "correctionLevel": { + "helperText": "Higher levels survive more damage but encode less data", + "label": "Error Correction Level", + "options": { + "h": "H (~30%)", + "l": "L (~7%)", + "m": "M (~15%)", + "q": "Q (~25%)" + } + }, + "fgColor": "Foreground Color", + "size": { + "description": "Size in pixels (100-1000)" + }, + "title": "QR Code Settings" + }, + "type": { + "label": "Select QR Code Type", + "options": { + "email": "Email", + "phone": "Phone", + "sms": "SMS", + "text": "Text", + "url": "URL", + "vcard": "vCard (Contact)", + "wifi": "WiFi" + }, + "title": "QR Code Type" + } + }, + "longDescription": "Generate QR codes for different data types: URL, Text, Email, Phone, SMS, WiFi, vCard, and more. Customize the size and colors to create the perfect QR code for your needs.", "options": { "address": "Address", "company": "Company (optional)", @@ -94,6 +215,9 @@ "url": "Enter the URL", "website": "Website (optional)" }, + "result": { + "title": "Generated QR code" + }, "resultOutput": "Generated QR code", "shortDescription": "Create customized QR codes for various data formats.", "title": "QR Code Generator" @@ -132,47 +256,89 @@ }, "rotate": { "description": "Rotate an image by a specified angle.", + "inputTitle": "Input Images", + "options": { + "angle": "Angle", + "customDesc": "Rotate by a custom angle in degrees.", + "customTitle": "Custom Angle", + "method": "Rotation Method", + "presetDesc": "Rotate by a specific angle in degrees.", + "presetTitle": "Preset Angle" + }, + "resultTitle": "Rotated images", "shortDescription": "Rotate an image easily.", "title": "Rotate Image" }, "split": { - "title": "Split Image into Pages", - "shortDescription": "Split a large image into multiple pages (PDF).", "description": "Split a map or large image into pages matching the selected paper format and padding. Specify pixels per printing square and square count to scale the image correctly.", "inputTitle": "Input image", - "resultTitle": "Split PDF", "loadingText": "Loading... This may take a moment.", "pageParameters": { - "title": "Page parameters", - "selectPageFormat": "Select page format", "padding": { - "label": "Padding", - "description": "Padding around the map on each page (in selected units)" - } + "description": "Padding around the map on each page (in selected units)", + "label": "Padding" + }, + "selectPageFormat": "Select page format", + "title": "Page parameters" }, + "resultTitle": "Split PDF", "scaleParameters": { - "title": "Scale parameters", "pxPerSquareQuantity": { - "label": "Pixels per squares quantity", - "description": "How many pixels correspond to the specified number of squares on the original image (horizontal or vertical)" + "description": "How many pixels correspond to the specified number of squares on the original image (horizontal or vertical)", + "label": "Pixels per squares quantity" }, "squareQuantity": { - "label": "Squares quantity", - "description": "Number of play squares across (horizontal or vertical) used for scaling" + "description": "Number of play squares across (horizontal or vertical) used for scaling", + "label": "Squares quantity" }, + "title": "Scale parameters", "unitsPerOneSquare": { - "label": "Units per square", - "description": "Physical size of one square in the selected units" + "description": "Physical size of one square in the selected units", + "label": "Units per square" } }, + "shortDescription": "Split a large image into multiple pages (PDF).", + "title": "Split Image into Pages", "units": { - "title": "Units", - "select": "Select measurement units", "options": { - "pt": "Points (pt)", + "in": "Inches (in)", "mm": "Millimeters (mm)", - "in": "Inches (in)" - } + "pt": "Points (pt)" + }, + "select": "Select measurement units", + "title": "Units" + } + }, + "watermark": { + "description": "Add text watermarks to one or more images using each filename or custom text.", + "failedToProcess": "Failed to watermark one or more images. Please try again.", + "inputTitle": "Input Images", + "options": { + "color": "Watermark color.", + "customStringWatermarkDesc": "Apply the same custom text to every image.", + "customStringWatermarkTitle": "Use Custom Watermark", + "filenameWatermarkDesc": "Use each image's filename as the watermark.", + "filenameWatermarkTitle": "Use Filename", + "fontSize": "Font size.", + "opacity": "Watermark transparency.", + "position": { + "bottomLeft": "Bottom Left", + "bottomRight": "Bottom Right", + "center": "Center", + "topLeft": "Top Left", + "topRight": "Top Right" + }, + "positionTitle": "Position", + "styleTitle": "Style", + "watermark": "Watermark text.", + "watermarkTitle": "Source" + }, + "outputTitle": "Watermarked Images", + "shortDescription": "Add text watermarks to images", + "title": "Watermark Images", + "toolInfo": { + "longDescription": "An image watermark tool lets you add customizable text watermarks to one or more images. You can automatically use each image's filename as the watermark or apply the same custom text to every image. Watermarks help protect your work, identify ownership, promote your brand, and organize image collections. Customize the font size, opacity, color, and position while preserving the original image quality.", + "title": "What is Watermark Images ?" } } } diff --git a/public/locales/en/json.json b/public/locales/en/json.json index f4df20c1..e3ad424c 100644 --- a/public/locales/en/json.json +++ b/public/locales/en/json.json @@ -6,8 +6,13 @@ }, "escapeJson": { "description": "Escape special characters in JSON strings. Convert JSON data to properly escaped format for safe transmission or storage.", + "inputTitle": "Input JSON", + "longDescription": "JSON escaping converts special characters inside JSON data into escaped sequences that can be safely stored, transmitted, or embedded inside another JSON document or programming language string. This tool escapes characters such as double quotes, backslashes, and line breaks while preserving the original data structure. Use it when you need to transform JSON into a string-safe representation for APIs, configuration files, databases, or source code.", + "resultTitle": "Escaped JSON String", "shortDescription": "Escape special characters in JSON", - "title": "Escape JSON" + "title": "Escape JSON", + "wrapOutputDescription": "Add double quotes around the escaped JSON output to create a JSON string.", + "wrapOutputTitle": "Wrap Output In Quotes" }, "jsonToCsv": { "delimiterOption": "Delimiter", @@ -36,6 +41,20 @@ }, "jsonToXml": { "description": "Convert JSON data to XML format. Transform structured JSON objects into well-formed XML documents.", + "inputTitle": "Input JSON", + "options": { + "addMetaTagDesc": "Add a meta tag at the beginning of the XML output", + "addMetaTagTitle": "Add an XML Meta Tag", + "indentationTitle": "Indentation Options", + "metaInfoTitle": "XML Meta Information", + "noIdentDesc": "Output XML without any indentation.", + "noIdentTitle": "No indentation", + "useSpaceDesc": "Use spaces to visualize the hierarchical structure of XML.", + "useSpaceTitle": "Use Spaces for indentation", + "useTabDesc": "Use tabs to visualize the hierarchical structure of XML.", + "useTabTitle": "Use Tabs for indentation" + }, + "outputTitle": "Output XML", "shortDescription": "Convert JSON to XML format", "title": "JSON to XML" }, @@ -66,10 +85,44 @@ "useTabs": "Use Tabs", "useTabsDescription": "Indent output with tabs." }, + "sortJson": { + "description": "Sort JSON data by organizing arrays of objects based on a selected key in ascending or descending order, or alphabetically sort the keys of a JSON object.", + "inputTitle": "Input JSON", + "longDescription": "This tool allows you to easily sort JSON data in a structured and predictable way. You can sort an array of objects by any key, choosing either ascending or descending order, which is useful for organizing data such as lists of users, products, or records. Alternatively, you can sort the keys of a JSON object alphabetically to improve readability and consistency. The tool supports flexible sorting modes and handles common JSON structures, making it ideal for developers, data analysts, and anyone working with JSON data who needs clean, ordered output.", + "options": { + "ascending": "Ascending (A → Z)", + "descending": "Descending (Z → A)", + "keyDescription": "Select the key to sort by", + "modeDescription": "Choose whether to sort array items by a key's value, or sort the keys of an object alphabetically", + "orderDescription": "Choose the sort order", + "sortByKey": "Sort object keys alphabetically", + "sortByValue": "Sort array by key value", + "title": "Sorting Options" + }, + "resultTitle": "Sorted JSON", + "shortDescription": "Sort JSON arrays by value or object keys alphabetically", + "title": "Sort JSON" + }, "stringify": { "description": "Convert JavaScript objects to JSON string format. Serialize data structures into JSON strings for storage or transmission.", + "inputTitle": "JavaScript Object/Array", + "options": { + "escapeHtmlDesc": "Convert HTML special characters to their entity references", + "escapeHtmlTitle": "Escape HTML Characters", + "indentationTitle": "Indentation Options", + "optionsTitle": "Options", + "useSpaceDesc": "Indent output with spaces", + "useSpaceTitle": "Use Spaces", + "useTabDesc": "Indent output with tabs", + "useTabTitle": "Use Tabs for indentation" + }, + "resultTitle": "JSON String", "shortDescription": "Convert objects to JSON string", - "title": "Stringify JSON" + "title": "Stringify JSON", + "toolInfo": { + "description": "JSON Stringify is a tool that converts JavaScript objects and arrays into their JSON string representation. It properly formats the output with customizable indentation and offers the option to escape HTML special characters, making it safe for web usage. This tool is particularly useful when you need to serialize data structures for storage or transmission, or when you need to prepare JSON data for HTML embedding.", + "title": "What Is JSON Stringify ?" + } }, "tsvToJson": { "description": "Convert TSV (Tab-Separated Values) data to JSON format. Transform tabular data into structured JSON objects.", @@ -88,23 +141,5 @@ "title": "What is JSON Validation?" }, "validJson": "✅ Valid JSON" - }, - "sortJson": { - "title": "Sort JSON", - "description": "Sort JSON data by organizing arrays of objects based on a selected key in ascending or descending order, or alphabetically sort the keys of a JSON object.", - "shortDescription": "Sort JSON arrays by value or object keys alphabetically", - "longDescription": "This tool allows you to easily sort JSON data in a structured and predictable way. You can sort an array of objects by any key, choosing either ascending or descending order, which is useful for organizing data such as lists of users, products, or records. Alternatively, you can sort the keys of a JSON object alphabetically to improve readability and consistency. The tool supports flexible sorting modes and handles common JSON structures, making it ideal for developers, data analysts, and anyone working with JSON data who needs clean, ordered output.", - "inputTitle": "Input JSON", - "resultTitle": "Sorted JSON", - "options": { - "title": "Sorting Options", - "sortByKey": "Sort object keys alphabetically", - "sortByValue": "Sort array by key value", - "ascending": "Ascending (A → Z)", - "descending": "Descending (Z → A)", - "modeDescription": "Choose whether to sort array items by a key's value, or sort the keys of an object alphabetically", - "keyDescription": "Select the key to sort by", - "orderDescription": "Choose the sort order" - } } } diff --git a/public/locales/en/number.json b/public/locales/en/number.json index 559fa088..271c9793 100644 --- a/public/locales/en/number.json +++ b/public/locales/en/number.json @@ -44,6 +44,24 @@ "title": "Generate numbers" } }, + "numberToWords": { + "description": "Convert numbers into words in your selected language. The output automatically matches your current app language.", + "inputTitle": "Numbers", + "options": { + "title": "Options", + "uppercase": "Uppercase", + "uppercaseDescription": "Display the converted words in uppercase, commonly used for cheques, invoices, and legal documents.", + "useAnd": "Include \"and\"", + "useAndDescription": "Insert \"and\" where appropriate (for example, \"One Hundred and Twenty\" in English)." + }, + "outputTitle": "Words", + "shortDescription": "Convert numbers to words", + "title": "Number to Words", + "toolInfo": { + "description": "This tool converts numeric values into their written form. The output automatically follows your current app language, so no additional configuration is required. Enter one number per line to convert multiple values independently.", + "title": "What Is a Number to Words Converter?" + } + }, "ohmsLaw": { "description": "Calculates voltage, current and resistance", "longDescription": "This calculator applies Ohm's Law (V = I × R) to determine any of the three electrical parameters when the other two are known. Ohm's Law is a fundamental principle in electrical engineering that describes the relationship between voltage (V), current (I), and resistance (R). This tool is essential for electronics hobbyists, electrical engineers, and students working with circuits to quickly solve for unknown values in their electrical designs.", diff --git a/public/locales/en/pdf.json b/public/locales/en/pdf.json index e84a0519..4c0b4492 100644 --- a/public/locales/en/pdf.json +++ b/public/locales/en/pdf.json @@ -43,6 +43,14 @@ "shortDescription": "Edit PDFs with advanced annotation, signing and editing tools", "title": "PDF Editor" }, + "extractImagesFromPdf": { + "description": "Extract all embedded images from your PDF file in their original quality.", + "inputTitle": "Input PDF", + "longDescription": "Upload a PDF document to automatically extract all embedded images. The tool preserves the original image quality and supports common formats such as JPG, PNG, and more. Ideal for recovering illustrations, photos, scanned pages, or assets from PDF documents.", + "resultTitle": "Extracted Images", + "shortDescription": "Extract images from a PDF file.", + "title": "Extract Images from PDF" + }, "merge": { "inputTitle": "Input PDF", "loadingText": "Extracting pages", @@ -127,13 +135,5 @@ "description": "This tool allows you to extract specific pages from a PDF document. You can specify individual pages or ranges of pages to extract.", "title": "Split PDF" } - }, - "extractImagesFromPdf": { - "description": "Extract all embedded images from your PDF file in their original quality.", - "shortDescription": "Extract images from a PDF file.", - "longDescription": "Upload a PDF document to automatically extract all embedded images. The tool preserves the original image quality and supports common formats such as JPG, PNG, and more. Ideal for recovering illustrations, photos, scanned pages, or assets from PDF documents.", - "title": "Extract Images from PDF", - "inputTitle": "Input PDF", - "resultTitle": "Extracted Images" } } diff --git a/public/locales/en/string.json b/public/locales/en/string.json index 86e5bf20..3accafce 100644 --- a/public/locales/en/string.json +++ b/public/locales/en/string.json @@ -23,6 +23,16 @@ "shortDescription": "Create text that reads the same forward and backward", "title": "Create palindrome" }, + "emailExtractor": { + "description": "Extract all email addresses from any text. Simply paste your text and instantly get a clean list of the email addresses found.", + "options": { + "title": "Extraction options", + "uniqueDesc": "Keep only unique email addresses in the results", + "uniqueTitle": "Remove duplicates" + }, + "shortDescription": "Extract email addresses from text", + "title": "Email Extractor" + }, "extractSubstring": { "description": "World's simplest browser-based utility for extracting substrings from text. Input your text and specify start and end positions to extract the desired portion. Perfect for data processing, text analysis, or extracting specific content from larger text blocks.", "shortDescription": "Extract a portion of text between specified positions", @@ -84,7 +94,7 @@ "includeNumbers": "Include numbers (0-9)", "includeSymbols": "Include special characters", "includeUppercase": "Include uppercase letters (A-Z)", - "lengthDesc": "Length of the password", + "lengthDesc": "Length of the password (>3 & <257)", "lengthPlaceholder": "e.g. 12", "optionsTitle": "Password Options", "resultTitle": "Generated Password", @@ -235,6 +245,20 @@ "wordFrequencyAnalysis": "Word Frequency Analysis", "wordFrequencyAnalysisDescription": "Count how often each word appears in the text" }, + "textCompare": { + "description": "Analyze two text blocks to highlight differences, including additions, deletions, and changes.", + "inputTitle": "Input Text", + "longDescription": "This tool helps you quickly identify differences between two versions of a text. It highlights inserted, removed, and modified content, making it ideal for reviewing edits, tracking changes, or comparing documents. You can choose the level of precision to detect differences at the word or character level depending on your needs.", + "options": { + "charLevel": "Character level", + "levelDesc": "Choose how detailed the comparison should be. Word level highlights changes by words, while character level detects more granular differences.", + "title": "Comparison Settings", + "wordLevel": "Word level" + }, + "resultTitle": "Highlighted differences", + "shortDescription": "Compare two texts and spot differences instantly", + "title": "Compare Texts" + }, "textReplacer": { "description": "Replace text patterns with new content.", "findPatternInText": "Find This Pattern in Text", @@ -322,6 +346,36 @@ "title": "String URL decoder" } }, + "urlEditor": { + "addParameter": "Add Parameter", + "credentialsNotSupported": "URLs with username or password are not supported.", + "delete": "Delete", + "deleteParamAriaLabel": "Delete parameter row {{row}}", + "generatedUrl": "Generated URL", + "hash": "Fragment", + "hashPlaceholder": "section", + "host": "Host", + "hostPlaceholder": "example.com", + "inputTitle": "Enter URL", + "invalidUrl": "Invalid URL", + "key": "Key", + "noParameters": "No query parameters", + "paramKeyAriaLabel": "Parameter key, row {{row}}", + "paramValueAriaLabel": "Parameter value, row {{row}}", + "parseButton": "Parse URL", + "path": "Path", + "pathPlaceholder": "search", + "protocol": "Protocol", + "queryParameters": "Query Parameters", + "toolInfo": { + "description": "Paste a URL and click \"Parse URL\" to inspect and edit its components.", + "longDescription": "This tool parses a URL into its components and lets you edit the protocol, host, path, fragment, and query parameters visually. After changing the input URL, click \"Parse URL\" again to refresh the parsed details. You can add, remove, or modify any part and copy the generated URL. No server requests.", + "shortDescription": "Inspect and edit URL components and query parameters.", + "title": "URL Editor" + }, + "urlDetails": "URL Details", + "value": "Value" + }, "urlEncode": { "encodingOption": { "nonSpecialCharDescription": "If selected, then all characters in the input string will be converted to URL-encoding (not just special).", @@ -336,19 +390,5 @@ "shortDescription": "Quickly URL-escape a string.", "title": "String URL encoder" } - }, - "textCompare": { - "title": "Compare Texts", - "description": "Analyze two text blocks to highlight differences, including additions, deletions, and changes.", - "shortDescription": "Compare two texts and spot differences instantly", - "longDescription": "This tool helps you quickly identify differences between two versions of a text. It highlights inserted, removed, and modified content, making it ideal for reviewing edits, tracking changes, or comparing documents. You can choose the level of precision to detect differences at the word or character level depending on your needs.", - "inputTitle": "Input Text", - "resultTitle": "Highlighted differences", - "options": { - "title": "Comparison Settings", - "wordLevel": "Word level", - "charLevel": "Character level", - "levelDesc": "Choose how detailed the comparison should be. Word level highlights changes by words, while character level detects more granular differences." - } } } diff --git a/public/locales/en/time.json b/public/locales/en/time.json index 72290674..84d08c66 100644 --- a/public/locales/en/time.json +++ b/public/locales/en/time.json @@ -12,6 +12,19 @@ "title": "What is a Leap Year?" } }, + "convertDateToUnix": { + "description": "Convert a human-readable date to a Unix Timestamp.", + "options": "Options", + "outputOptions": "Output Options", + "shortDescription": "Convert date to Unix timestamp.", + "title": "Convert Date to Unix", + "toolInfo": { + "description": "This tool converts a human-readable date format (e.g., YYYY-MM-DD HH:MM:SS) into a Unix Timestamp. The user can choose to specify a given UTC offset (e.g., YYYY-MM-DD HH:MM:SS +XX:XX) or use the local timezone. If the user doesn't provide either an offset or choose to use the local timezone, the result is given with an offset of +00:00. ", + "title": "Convert Date to Unix" + }, + "useLocalTime": "Use Local Time", + "useLocalTimeDescription": "The input time and date is processed as your browser's time zone. Additional specifications will be ignored." + }, "convertDaysToHours": { "addHoursName": "Add Hours Name", "addHoursNameDescription": "Append the string hours to output values", @@ -67,26 +80,108 @@ "convertUnixToDate": { "addUtcLabel": "Add 'UTC' suffix", "addUtcLabelDescription": "Append 'UTC' after the converted date (available only in UTC mode)", + "date-to-unix": "Date → Unix", "description": "Convert Unix timestamps to readable dates and convert dates back to Unix timestamps.", + "optionsTitle": "Conversion Mode", "shortDescription": "Convert Unix timestamps and dates in both directions.", "title": "Convert Unix ↔ Date", "toolInfo": { - "title": "Convert Unix ↔ Date", - "description": "This tool converts Unix timestamps (in seconds) into human-readable date formats such as YYYY-MM-DD HH:MM:SS, and also converts formatted dates back into Unix timestamps. You can choose UTC output, local timezone output, or provide a custom UTC offset (for example: YYYY-MM-DD HH:MM:SS +XX:XX). If no offset is provided and local timezone is not selected, UTC (+00:00) is used by default." + "description": "This tool converts Unix timestamps (in seconds) into human-readable date formats such as YYYY-MM-DD HH:MM:SS, and also converts formatted dates back into Unix timestamps. You can choose UTC output, local timezone output, or provide a custom UTC offset (for example: YYYY-MM-DD HH:MM:SS +XX:XX). If no offset is provided and local timezone is not selected, UTC (+00:00) is used by default.", + "title": "Convert Unix ↔ Date" }, - "useLocalTime": "Use Local Time", - "useUTC": "Use UTC", - "useLocalTimeDescription": "Display the converted date in your local timezone instead of UTC", "tzOptions": "Timezone Options", - "optionsTitle": "Conversion Mode", - "date-to-unix": "Date → Unix", - "unix-to-date": "Unix → Date" + "unix-to-date": "Unix → Date", + "useLocalTime": "Use Local Time", + "useLocalTimeDescription": "Display the converted date in your local timezone instead of UTC", + "useUTC": "Use UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Parse and explain cron expressions in plain English. Instantly understand what any cron schedule does, validate syntax, and process multiple expressions at once.", + "longDescription": "Crontab Guru is a cron expression parser and validator that translates complex cron syntax into plain, human-readable descriptions. Whether you're scheduling automated backups, system maintenance tasks, or CI/CD pipelines, this tool helps you understand exactly when your jobs will run. Supports standard 5-field cron expressions, validates syntax in real time, and processes multiple expressions at once — one per line. Available in English, French, Spanish, German, Japanese, Chinese, Portuguese, Dutch, and Russian.", "shortDescription": "Parse and explain cron expressions in plain English", - "longDescription": "Crontab Guru is a cron expression parser and validator that translates complex cron syntax into plain, human-readable descriptions. Whether you're scheduling automated backups, system maintenance tasks, or CI/CD pipelines, this tool helps you understand exactly when your jobs will run. Supports standard 5-field cron expressions, validates syntax in real time, and processes multiple expressions at once — one per line. Available in English, French, Spanish, German, Japanese, Chinese, Portuguese, Dutch, and Russian." + "title": "Crontab Guru" + }, + "dateWeekdayCalculator": { + "dateSelection": "Date", + "dayDescription": "Day", + "description": "Find every year in a range where a month and day fall on a chosen weekday.", + "endYearDescription": "End year", + "errors": { + "emptyInput": "All fields are required", + "fallback": "Invalid input", + "invalidDate": "Invalid day for the selected month", + "invalidDay": "Day must be between 1 and 31", + "invalidMonth": "Month must be between 1 and 12", + "invalidWeekday": "Invalid weekday", + "invalidYear": "Years must be integers between 1 and 9999", + "invalidYearRange": "Start year must be less than or equal to end year" + }, + "foundMatches_one": "Found {{count}} matching year", + "foundMatches_other": "Found {{count}} matching years", + "longDescription": "Select a month, day, and target weekday, then choose a start and end year. The calculator scans each year in the range and lists every match as a full formatted date. February 29 is supported: non-leap years are skipped automatically. Invalid dates (such as April 31) and invalid year ranges show clear error messages.", + "monthDescription": "Month", + "months": [ + null, + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + "noMatches": "No matching years found in the selected range.", + "resultTitle": "Matching years", + "shortDescription": "Find years when a date falls on a weekday", + "startYearDescription": "Start year", + "title": "Date Weekday Calculator", + "toolInfo": { + "title": "What is a {{title}}?" + }, + "weekdayDescription": "Target weekday", + "weekdaySelection": "Weekday", + "weekdays": { + "friday": "Friday", + "monday": "Monday", + "saturday": "Saturday", + "sunday": "Sunday", + "thursday": "Thursday", + "tuesday": "Tuesday", + "wednesday": "Wednesday" + }, + "yearRange": "Year range" + }, + "discordTimestamp": { + "description": "Convert dates and times into Discord's special timestamp format that automatically adapts to each user's local timezone and language", + "formats": { + "description": "Choose how the timestamp will appear in Discord — hover over each option to see an example", + "long_date": "Long Date (ex: 1 January 2025)", + "long_datetime": "Long Date & Time (ex: Monday, 1 January 2025 14:30)", + "long_time": "Long Time (ex: 14:30:00)", + "relative": "Relative (ex: 2 hours ago)", + "short_date": "Short Date (ex: 01/01/2025)", + "short_datetime": "Short Date & Time (ex: 1 January 2025 14:30)", + "short_time": "Short Time (ex: 14:30)", + "title": "Timestamp Format" + }, + "inputTitle": "Input Datetimes", + "name": "Discord Timestamp Generator", + "outputTitle": "Discord Timestamps", + "shortDescription": "Generate Discord timestamps from dates", + "toolInfo": { + "description": "Discord timestamps are a special syntax that displays dates and times dynamically. Instead of showing a fixed time, they automatically convert to each viewer's local timezone and language — so everyone sees the correct time for their location. Simply enter one datetime per line, choose a format, and paste the results directly into Discord. The tool processes each line independently — blank lines are preserved in the output, invalid lines are flagged with ❌, and valid datetimes are converted instantly. Enable UTC mode to ensure consistent results regardless of your local timezone.", + "title": "What is a Discord Timestamp?" + }, + "utc": { + "description": "Treat input datetimes as UTC. Disable to use your local timezone instead", + "label": "Enforce UTC", + "title": "Input Options" + } }, "timeBetweenDates": { "description": "Calculate the time difference between two dates. Get the exact duration in days, hours, minutes, and seconds.", @@ -123,45 +218,5 @@ "zeroPaddingDescription": "Make all time components always be two digits wide.", "zeroPrintDescription": "Display the dropped parts as zero values \"00\".", "zeroPrintTruncatedParts": "Zero-print Truncated Parts" - }, - "discordTimestamp": { - "name": "Discord Timestamp Generator", - "description": "Convert dates and times into Discord's special timestamp format that automatically adapts to each user's local timezone and language", - "shortDescription": "Generate Discord timestamps from dates", - "inputTitle": "Input Datetimes", - "outputTitle": "Discord Timestamps", - "formats": { - "title": "Timestamp Format", - "description": "Choose how the timestamp will appear in Discord — hover over each option to see an example", - "short_time": "Short Time (ex: 14:30)", - "long_time": "Long Time (ex: 14:30:00)", - "short_date": "Short Date (ex: 01/01/2025)", - "long_date": "Long Date (ex: 1 January 2025)", - "short_datetime": "Short Date & Time (ex: 1 January 2025 14:30)", - "long_datetime": "Long Date & Time (ex: Monday, 1 January 2025 14:30)", - "relative": "Relative (ex: 2 hours ago)" - }, - "utc": { - "title": "Input Options", - "label": "Enforce UTC", - "description": "Treat input datetimes as UTC. Disable to use your local timezone instead" - }, - "toolInfo": { - "title": "What is a Discord Timestamp?", - "description": "Discord timestamps are a special syntax that displays dates and times dynamically. Instead of showing a fixed time, they automatically convert to each viewer's local timezone and language — so everyone sees the correct time for their location. Simply enter one datetime per line, choose a format, and paste the results directly into Discord. The tool processes each line independently — blank lines are preserved in the output, invalid lines are flagged with ❌, and valid datetimes are converted instantly. Enable UTC mode to ensure consistent results regardless of your local timezone." - } - }, - "convertDateToUnix": { - "description": "Convert a human-readable date to a Unix Timestamp.", - "outputOptions": "Output Options", - "shortDescription": "Convert date to Unix timestamp.", - "title": "Convert Date to Unix", - "toolInfo": { - "description": "This tool converts a human-readable date format (e.g., YYYY-MM-DD HH:MM:SS) into a Unix Timestamp. The user can choose to specify a given UTC offset (e.g., YYYY-MM-DD HH:MM:SS +XX:XX) or use the local timezone. If the user doesn't provide either an offset or choose to use the local timezone, the result is given with an offset of +00:00. ", - "title": "Convert Date to Unix" - }, - "useLocalTime": "Use Local Time", - "useLocalTimeDescription": "The input time and date is processed as your browser's time zone. Additional specifications will be ignored.", - "options": "Options" } } diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 60663596..5b4efe41 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -107,8 +107,8 @@ "trimVideo": "Trim video" }, "search": { - "placeholder": "Search all tools", - "noResult": "No results found, Try adjusting your search or filter criteria" + "noResult": "No results found, Try adjusting your search or filter criteria", + "placeholder": "Search all tools" }, "title": "Get Things Done Quickly with" }, @@ -241,9 +241,9 @@ "result": "Result" }, "toolMultipleInput": { + "deleteFile": "Delete file", "inputTitle": "Input {{type}}", - "noFilesSelected": "No files selected", - "deleteFile": "Delete file" + "noFilesSelected": "No files selected" }, "toolOptions": { "title": "Tool options" diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 6b37b38b..523b5705 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -29,15 +29,15 @@ "volumeDesc": "Volume level for the new audio track." }, "changeSpeed": { - "defaultMultiplier": "Default multiplier: 2 means 2x faster", "description": "Change the playback speed of video files. Speed up or slow down videos while maintaining audio synchronization. Supports various speed multipliers and common video formats.", "inputTitle": "Input Video", - "newVideoSpeed": "New Video Speed", + "options": "Options", "resultTitle": "Edited Video", - "settingSpeed": "Setting Speed", "shortDescription": "Change video playback speed", + "speedLabel": "Speed : x", "title": "Change Video Speed", "toolInfo": { + "longDescription": "{{title}} allows you to adjust the playback speed of your videos directly in your browser. Speed up videos for fast-motion effects or slow them down for slow-motion playback while keeping the audio synchronized. Choose a speed multiplier between 0.25x and 4x to customize your video, then process it easily without installing additional software. This tool supports common video formats and preserves the original video quality as much as possible during processing.", "title": "What is a {{title}}?" } }, @@ -83,7 +83,6 @@ }, "flip": { "description": "Flip video files horizontally or vertically. Mirror videos for special effects or correct orientation issues.", - "flippingVideo": "Flipping Video", "horizontalLabel": "Horizontal (Mirror)", "inputTitle": "Input Video", "orientation": "Orientation", @@ -95,6 +94,12 @@ "gif": { "changeSpeed": { "description": "Change the playback speed of GIF animations. Speed up or slow down GIFs while maintaining smooth animation.", + "inputTitle": "Input GIF", + "options": { + "speedLabel": "Speed : x", + "title": "Options" + }, + "resultTitle": "output GIF", "shortDescription": "Change GIF animation speed", "title": "Change GIF Speed" }, @@ -112,7 +117,6 @@ "loop": { "description": "Create a looping video by repeating the original video multiple times.", "inputTitle": "Input Video", - "loopingVideo": "Looping Video", "loops": "Loops", "numberOfLoops": "Number of Loops", "resultTitle": "Looped Video", @@ -120,12 +124,14 @@ "title": "Loop Video", "toolInfo": { "description": "This tool allows you to create a looping video by repeating the original video multiple times. You can specify how many times the video should loop.", - "title": "What is a {{title}}?" + "title": "What is {{title}}?" } }, "mergeVideo": { "description": "Combine multiple video files into one continuous video.", + "inputTitle": "Input Videos", "longDescription": "This tool allows you to merge or append multiple video files into a single continuous video. Simply upload your video files, arrange them in the desired order, and merge them into one file for easy sharing or editing.", + "resultTitle": "Merged Video", "shortDescription": "Append and merge videos easily.", "title": "Merge videos" }, @@ -136,7 +142,6 @@ "description": "Rotate video files by 90, 180, or 270 degrees. Correct video orientation or create special effects with precise rotation control.", "inputTitle": "Input Video", "resultTitle": "Rotated Video", - "rotatingVideo": "Rotating Video", "rotation": "Rotation", "shortDescription": "Rotate video by specified degrees", "title": "Rotate Video" @@ -150,10 +155,5 @@ "startTime": "Start Time", "timestamps": "Timestamps", "title": "Trim Video" - }, - "videoToGif": { - "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", - "shortDescription": "Convert video to animated GIF", - "title": "Video to GIF" } } diff --git a/public/locales/es/audio.json b/public/locales/es/audio.json index 091b38ca..2771ba6f 100644 --- a/public/locales/es/audio.json +++ b/public/locales/es/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Ajuste de velocidad", "shortDescription": "Cambiar la velocidad de los archivos de audio", "speedDescription": "Multiplicador predeterminado: 2 significa 2 veces más rápido", - "title": "Cambiar la velocidad del audio", - "toolInfo": { - "title": "Qué es {{title}}?" - } + "title": "Cambiar la velocidad del audio" }, "extractAudio": { "description": "Extraer pistas de audio de archivos de vídeo.", @@ -31,7 +28,6 @@ "description": "Combine varios archivos de audio en un solo archivo de audio concatenándolos en secuencia.", "inputTitle": "Archivos de audio de entrada", "longDescription": "Esta herramienta te permite fusionar varios archivos de audio en uno solo concatenándolos en el orden en que los subes. Es perfecta para combinar segmentos de podcast, pistas de música o cualquier archivo de audio que necesite unirse. Admite varios formatos de audio, como MP3, AAC y WAV.", - "mergingAudio": "Fusión de audio", "outputFormat": "Formato de salida", "resultTitle": "Audio fusionado", "shortDescription": "Fusionar varios archivos de audio en uno (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Recortar audio", "toolInfo": { "title": "Qué es {{title}}?" - }, - "trimmingAudio": "Recorte de audio" + } } } diff --git a/public/locales/es/string.json b/public/locales/es/string.json index 217823b0..d05af9b3 100644 --- a/public/locales/es/string.json +++ b/public/locales/es/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Incluir números (0-9)", "includeSymbols": "Incluir caracteres especiales", "includeUppercase": "Incluir letras mayúsculas (A-Z)", - "lengthDesc": "Longitud de la contraseña", + "lengthDesc": "Longitud de la contraseña (>3 & <257)", "lengthPlaceholder": "p. ej. 12", "optionsTitle": "Opciones de contraseña", "resultTitle": "Contraseña generada", diff --git a/public/locales/es/time.json b/public/locales/es/time.json index c3ae82e9..4237ec34 100644 --- a/public/locales/es/time.json +++ b/public/locales/es/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Fecha → Unix", "description": "Convierte marcas de tiempo de Unix en fechas legibles y convierte fechas formateadas nuevamente en marcas de tiempo de Unix (en ambas direcciones).", "optionsTitle": "Modo de conversión", - "outputOptions": "Opciones de salida", "shortDescription": "Convierte marcas de tiempo de Unix y fechas en ambas direcciones.", "title": "Convertir Unix ↔ Fecha", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "Usar UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Analiza y explica expresiones cron en español. Entiende al instante qué hace cualquier programación cron, valida la sintaxis y procesa múltiples expresiones a la vez.", + "longDescription": "Crontab Guru es un analizador y validador de expresiones cron que traduce la compleja sintaxis cron en descripciones claras y legibles. Ya sea que estés programando copias de seguridad automáticas, tareas de mantenimiento del sistema o pipelines CI/CD, esta herramienta te ayuda a entender exactamente cuándo se ejecutarán tus tareas. Admite expresiones cron estándar de 5 campos, valida la sintaxis en tiempo real y procesa múltiples expresiones a la vez — una por línea. Disponible en inglés, francés, español, alemán, japonés, chino, portugués, neerlandés y ruso.", "shortDescription": "Analiza y explica expresiones cron en lenguaje claro", - "longDescription": "Crontab Guru es un analizador y validador de expresiones cron que traduce la compleja sintaxis cron en descripciones claras y legibles. Ya sea que estés programando copias de seguridad automáticas, tareas de mantenimiento del sistema o pipelines CI/CD, esta herramienta te ayuda a entender exactamente cuándo se ejecutarán tus tareas. Admite expresiones cron estándar de 5 campos, valida la sintaxis en tiempo real y procesa múltiples expresiones a la vez — una por línea. Disponible en inglés, francés, español, alemán, japonés, chino, portugués, neerlandés y ruso." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Calcula la diferencia horaria entre dos fechas. Obtén la duración exacta en días, horas, minutos y segundos.", diff --git a/public/locales/es/translation.json b/public/locales/es/translation.json index e27ddac5..840b21ea 100644 --- a/public/locales/es/translation.json +++ b/public/locales/es/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Recortar vídeo" }, "search": { - "placeholder": "Buscar todas las herramientas", - "noResult": "No se encontraron resultados, intenta ajustar tu búsqueda o los criterios de filtro" + "noResult": "No se encontraron resultados, intenta ajustar tu búsqueda o los criterios de filtro", + "placeholder": "Buscar todas las herramientas" }, "title": "Haga las cosas rápidamente con" }, @@ -229,9 +229,9 @@ "result": "Resultado" }, "toolMultipleInput": { + "deleteFile": "Eliminar archivo", "inputTitle": "Entrada {{type}}", - "noFilesSelected": "Ningún archivo seleccionado", - "deleteFile": "Eliminar archivo" + "noFilesSelected": "Ningún archivo seleccionado" }, "toolOptions": { "title": "Opciones de herramientas" diff --git a/public/locales/es/video.json b/public/locales/es/video.json index 1cbab702..3f5bb3ae 100644 --- a/public/locales/es/video.json +++ b/public/locales/es/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Multiplicador predeterminado: 2 significa 2 veces más rápido", "description": "Cambia la velocidad de reproducción de tus archivos de video. Acelera o ralentiza los videos manteniendo la sincronización del audio. Compatible con varios multiplicadores de velocidad y formatos de video comunes.", "inputTitle": "Vídeo de entrada", - "newVideoSpeed": "Nueva velocidad de video", "resultTitle": "Vídeo editado", - "settingSpeed": "Ajuste de velocidad", "shortDescription": "Cambiar la velocidad de reproducción del vídeo", "title": "Cambiar la velocidad del video", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Voltee archivos de video horizontal o verticalmente. Refleje videos para efectos especiales o corregir problemas de orientación.", - "flippingVideo": "Vídeo invertido", "horizontalLabel": "Horizontal (Espejo)", "inputTitle": "Vídeo de entrada", "orientation": "Orientación", @@ -73,7 +69,6 @@ "loop": { "description": "Crea un vídeo en bucle repitiendo el vídeo original varias veces.", "inputTitle": "Vídeo de entrada", - "loopingVideo": "Vídeo en bucle", "loops": "Bucles", "numberOfLoops": "Número de bucles", "resultTitle": "Vídeo en bucle", @@ -97,7 +92,6 @@ "description": "Gira archivos de vídeo 90, 180 o 270 grados. Corrige la orientación del vídeo o crea efectos especiales con un control de rotación preciso.", "inputTitle": "Vídeo de entrada", "resultTitle": "Vídeo rotado", - "rotatingVideo": "Vídeo giratorio", "rotation": "Rotación", "shortDescription": "Girar el vídeo en grados específicos", "title": "Girar vídeo" @@ -111,10 +105,5 @@ "startTime": "Hora de inicio", "timestamps": "Marcas de tiempo", "title": "Recortar vídeo" - }, - "videoToGif": { - "description": "Convierte archivos de vídeo a formato GIF animado. Extrae intervalos de tiempo específicos y crea imágenes animadas para compartir.", - "shortDescription": "Convertir vídeo a GIF animado", - "title": "Vídeo a GIF" } } diff --git a/public/locales/fr/audio.json b/public/locales/fr/audio.json index d75857f7..9de28341 100644 --- a/public/locales/fr/audio.json +++ b/public/locales/fr/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Réglage de la vitesse", "shortDescription": "Modifier la vitesse des fichiers audio", "speedDescription": "Multiplicateur par défaut : 2 signifie 2x plus rapide", - "title": "Changer la vitesse audio", - "toolInfo": { - "title": "Qu'est-ce que {{title}}?" - } + "title": "Changer la vitesse audio" }, "extractAudio": { "description": "Extraire la piste audio des fichiers vidéo.", @@ -31,7 +28,6 @@ "description": "Combinez plusieurs fichiers audio en un seul fichier audio en les concaténant en séquence.", "inputTitle": "Fichiers audio d'entrée", "longDescription": "Cet outil vous permet de fusionner plusieurs fichiers audio en un seul fichier en les concaténant dans l'ordre de leur mise en ligne. Idéal pour combiner des segments de podcast, des morceaux de musique ou tout autre fichier audio à assembler. Compatible avec différents formats audio, dont MP3, AAC et WAV.", - "mergingAudio": "Fusion audio", "outputFormat": "Format de sortie", "resultTitle": "Audio fusionné", "shortDescription": "Fusionnez plusieurs fichiers audio en un seul (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Couper le son", "toolInfo": { "title": "Qu'est-ce que {{title}}?" - }, - "trimmingAudio": "Découpage audio" + } } } diff --git a/public/locales/fr/string.json b/public/locales/fr/string.json index 5dfeb886..36877b40 100644 --- a/public/locales/fr/string.json +++ b/public/locales/fr/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Inclure des chiffres (0-9)", "includeSymbols": "Inclure des caractères spéciaux", "includeUppercase": "Inclure des lettres majuscules (A-Z)", - "lengthDesc": "Longueur du mot de passe", + "lengthDesc": "Longueur du mot de passe (>3 & <257)", "lengthPlaceholder": "par exemple 12", "optionsTitle": "Options de mot de passe", "resultTitle": "Mot de passe généré", diff --git a/public/locales/fr/time.json b/public/locales/fr/time.json index a571a08f..39b553ac 100644 --- a/public/locales/fr/time.json +++ b/public/locales/fr/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Date → Unix", "description": "Convertir les horodatages Unix en dates lisibles et reconvertir les dates formatées en horodatages Unix (dans les deux directions).", "optionsTitle": "Mode de conversion", - "outputOptions": "Options de sortie", "shortDescription": "Convertir les horodatages Unix et les dates dans les deux directions.", "title": "Convertir Unix ↔ Date", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "Utiliser l'UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Analysez et expliquez les expressions cron en français. Comprenez instantanément ce que fait un planning cron, validez la syntaxe et traitez plusieurs expressions à la fois.", + "longDescription": "Crontab Guru est un analyseur et validateur d'expressions cron qui traduit la syntaxe complexe des crons en descriptions claires et lisibles. Que vous planifiiez des sauvegardes automatiques, des tâches de maintenance système ou des pipelines CI/CD, cet outil vous aide à comprendre exactement quand vos tâches s'exécuteront. Prend en charge les expressions cron standard à 5 champs, valide la syntaxe en temps réel et traite plusieurs expressions à la fois — une par ligne. Disponible en anglais, français, espagnol, allemand, japonais, chinois, portugais, néerlandais et russe.", "shortDescription": "Analysez et expliquez les expressions cron en clair", - "longDescription": "Crontab Guru est un analyseur et validateur d'expressions cron qui traduit la syntaxe complexe des crons en descriptions claires et lisibles. Que vous planifiiez des sauvegardes automatiques, des tâches de maintenance système ou des pipelines CI/CD, cet outil vous aide à comprendre exactement quand vos tâches s'exécuteront. Prend en charge les expressions cron standard à 5 champs, valide la syntaxe en temps réel et traite plusieurs expressions à la fois — une par ligne. Disponible en anglais, français, espagnol, allemand, japonais, chinois, portugais, néerlandais et russe." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Calculez le décalage horaire entre deux dates. Obtenez la durée exacte en jours, heures, minutes et secondes.", diff --git a/public/locales/fr/translation.json b/public/locales/fr/translation.json index 75751358..9faf8f36 100644 --- a/public/locales/fr/translation.json +++ b/public/locales/fr/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Découper la vidéo" }, "search": { - "placeholder": "Rechercher tous les outils", - "noResult": "Aucun résultat trouvé, essayez d'ajuster votre recherche ou vos critères de filtre" + "noResult": "Aucun résultat trouvé, essayez d'ajuster votre recherche ou vos critères de filtre", + "placeholder": "Rechercher tous les outils" }, "title": "Faites avancer les choses rapidement avec" }, @@ -229,9 +229,9 @@ "result": "Résultat" }, "toolMultipleInput": { + "deleteFile": "Supprimer le fichier", "inputTitle": "Entrée {{type}}", - "noFilesSelected": "Aucun fichier sélectionné", - "deleteFile": "Supprimer le fichier" + "noFilesSelected": "Aucun fichier sélectionné" }, "toolOptions": { "title": "Options d'outils" diff --git a/public/locales/fr/video.json b/public/locales/fr/video.json index 64cfac04..eb957774 100644 --- a/public/locales/fr/video.json +++ b/public/locales/fr/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Multiplicateur par défaut : 2 signifie 2x plus rapide", "description": "Modifiez la vitesse de lecture des fichiers vidéo. Accélérez ou ralentissez les vidéos tout en conservant la synchronisation audio. Prise en charge de divers multiplicateurs de vitesse et formats vidéo courants.", "inputTitle": "Entrée vidéo", - "newVideoSpeed": "Nouvelle vitesse vidéo", "resultTitle": "Vidéo éditée", - "settingSpeed": "Réglage de la vitesse", "shortDescription": "Modifier la vitesse de lecture vidéo", "title": "Modifier la vitesse de la vidéo", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Retournez les fichiers vidéo horizontalement ou verticalement. Inversez les vidéos pour obtenir des effets spéciaux ou corriger les problèmes d'orientation.", - "flippingVideo": "Retournement vidéo", "horizontalLabel": "Horizontal (miroir)", "inputTitle": "Entrée vidéo", "orientation": "Orientation", @@ -73,7 +69,6 @@ "loop": { "description": "Créez une vidéo en boucle en répétant la vidéo originale plusieurs fois.", "inputTitle": "Entrée vidéo", - "loopingVideo": "Vidéo en boucle", "loops": "Boucles", "numberOfLoops": "Nombre de boucles", "resultTitle": "Vidéo en boucle", @@ -97,7 +92,6 @@ "description": "Faites pivoter vos fichiers vidéo de 90, 180 ou 270 degrés. Corrigez l'orientation de vos vidéos ou créez des effets spéciaux grâce à un contrôle précis de la rotation.", "inputTitle": "Entrée vidéo", "resultTitle": "Vidéo tournée", - "rotatingVideo": "Vidéo rotative", "rotation": "Rotation", "shortDescription": "Faire pivoter la vidéo selon les degrés spécifiés", "title": "Faire pivoter la vidéo" @@ -111,10 +105,5 @@ "startTime": "Heure de début", "timestamps": "Horodatages", "title": "Découper la vidéo" - }, - "videoToGif": { - "description": "Convertissez des fichiers vidéo au format GIF animé. Extrayez des plages horaires spécifiques et créez des images animées partageables.", - "shortDescription": "Convertir une vidéo en GIF animé", - "title": "Vidéo en GIF" } } diff --git a/public/locales/hi/audio.json b/public/locales/hi/audio.json index a62f95ad..4ee5082e 100644 --- a/public/locales/hi/audio.json +++ b/public/locales/hi/audio.json @@ -15,10 +15,7 @@ "speedDescription": "डिफ़ॉल्ट गुणक: 2 का अर्थ है 2x तेज़", "speedFactor": "गति कारक", "speedOptions": "गति विकल्प", - "title": "ऑडियो गति बदलें", - "toolInfo": { - "title": "क्या है {{title}}?" - } + "title": "ऑडियो गति बदलें" }, "extractAudio": { "audioFormat": "ऑडियो प्रारूप", @@ -53,7 +50,6 @@ "longDescription": "यह टूल आपको कई ऑडियो फ़ाइलों को अपलोड करने के क्रम में जोड़कर उन्हें एक ही फ़ाइल में मर्ज करने की सुविधा देता है। पॉडकास्ट सेगमेंट, म्यूज़िक ट्रैक या किसी भी ऑडियो फ़ाइल को एक साथ जोड़ने के लिए यह बिल्कुल सही है। MP3, AAC और WAV सहित विभिन्न ऑडियो फ़ॉर्मेट को सपोर्ट करता है।", "mergeMethod": "मर्ज विधि", "mergeOptions": "मर्ज विकल्प", - "mergingAudio": "ऑडियो मर्ज करना", "methodConcat": "क्रमबद्ध जोड़ना", "methodMix": "मिश्रण", "outputFormat": "आउटपुट प्रारूप", @@ -88,7 +84,6 @@ "toolInfo": { "title": "क्या है {{title}}?" }, - "trimOptions": "ट्रिम विकल्प", - "trimmingAudio": "ऑडियो ट्रिमिंग" + "trimOptions": "ट्रिम विकल्प" } } diff --git a/public/locales/hi/string.json b/public/locales/hi/string.json index 04822139..5e6b8c12 100644 --- a/public/locales/hi/string.json +++ b/public/locales/hi/string.json @@ -84,7 +84,7 @@ "includeNumbers": "संख्याएँ शामिल करें (0-9)", "includeSymbols": "विशेष वर्ण शामिल करें", "includeUppercase": "बड़े अक्षर (A-Z) शामिल करें", - "lengthDesc": "पासवर्ड की लंबाई", + "lengthDesc": "पासवर्ड की लंबाई (>3 & <257)", "lengthPlaceholder": "उदाहरणार्थ 12", "optionsTitle": "पासवर्ड विकल्प", "resultTitle": "जनरेट किया गया पासवर्ड", diff --git a/public/locales/hi/time.json b/public/locales/hi/time.json index 01605bf0..69a0644c 100644 --- a/public/locales/hi/time.json +++ b/public/locales/hi/time.json @@ -95,7 +95,6 @@ "date-to-unix": "दिनांक → यूनिक्स", "description": "यूनिक्स टाइमस्टैम्प को पठनीय दिनांकों में परिवर्तित करें और स्वरूपित दिनांकों को वापस यूनिक्स टाइमस्टैम्प में परिवर्तित करें (दोनों दिशाओं में)।", "optionsTitle": "रूपांतरण मोड", - "outputOptions": "आउटपुट विकल्प", "shortDescription": "यूनिक्स टाइमस्टैम्प और दिनांकों को दोनों दिशाओं में परिवर्तित करें।", "title": "यूनिक्स ↔ दिनांक रूपांतरित करें", "toolInfo": { @@ -109,10 +108,10 @@ "useUTC": "UTC का उपयोग करें" }, "crontabGuru": { - "title": "Crontab Guru", "description": "क्रॉन एक्सप्रेशन को हिंदी में पार्स और समझाएं। किसी भी क्रॉन शेड्यूल को तुरंत समझें, सिंटैक्स को वैलिडेट करें और एक साथ कई एक्सप्रेशन प्रोसेस करें।", + "longDescription": "Crontab Guru एक क्रॉन एक्सप्रेशन पार्सर और वैलिडेटर है जो जटिल क्रॉन सिंटैक्स को स्पष्ट, पठनीय विवरणों में अनुवाद करता है। चाहे आप स्वचालित बैकअप, सिस्टम रखरखाव कार्य, या CI/CD पाइपलाइन शेड्यूल कर रहे हों, यह टूल आपको यह समझने में मदद करता है कि आपके जॉब्स ठीक कब चलेंगे। मानक 5-फील्ड क्रॉन एक्सप्रेशन का समर्थन करता है, रियल टाइम में सिंटैक्स वैलिडेट करता है और एक साथ कई एक्सप्रेशन प्रोसेस करता है — एक प्रति पंक्ति।", "shortDescription": "क्रॉन एक्सप्रेशन को सरल भाषा में पार्स और समझाएं", - "longDescription": "Crontab Guru एक क्रॉन एक्सप्रेशन पार्सर और वैलिडेटर है जो जटिल क्रॉन सिंटैक्स को स्पष्ट, पठनीय विवरणों में अनुवाद करता है। चाहे आप स्वचालित बैकअप, सिस्टम रखरखाव कार्य, या CI/CD पाइपलाइन शेड्यूल कर रहे हों, यह टूल आपको यह समझने में मदद करता है कि आपके जॉब्स ठीक कब चलेंगे। मानक 5-फील्ड क्रॉन एक्सप्रेशन का समर्थन करता है, रियल टाइम में सिंटैक्स वैलिडेट करता है और एक साथ कई एक्सप्रेशन प्रोसेस करता है — एक प्रति पंक्ति।" + "title": "Crontab Guru" }, "timeBetweenDates": { "dateOptions": "तिथि विकल्प", diff --git a/public/locales/hi/translation.json b/public/locales/hi/translation.json index d83c0865..bfaa8872 100644 --- a/public/locales/hi/translation.json +++ b/public/locales/hi/translation.json @@ -95,8 +95,8 @@ "trimVideo": "वीडियो ट्रिम करें" }, "search": { - "placeholder": "सभी टूल खोजें", - "noResult": "कोई परिणाम नहीं मिला, अपनी खोज या फ़िल्टर मानदंड समायोजित करने का प्रयास करें" + "noResult": "कोई परिणाम नहीं मिला, अपनी खोज या फ़िल्टर मानदंड समायोजित करने का प्रयास करें", + "placeholder": "सभी टूल खोजें" }, "title": "के साथ जल्दी काम करें" }, @@ -229,9 +229,9 @@ "result": "परिणाम" }, "toolMultipleInput": { + "deleteFile": "फ़ाइल हटाएं", "inputTitle": "{{type}} इनपुट करें", - "noFilesSelected": "कोई फ़ाइल नहीं चुनी गई", - "deleteFile": "फ़ाइल हटाएं" + "noFilesSelected": "कोई फ़ाइल नहीं चुनी गई" }, "toolOptions": { "title": "टूल विकल्प" diff --git a/public/locales/hi/video.json b/public/locales/hi/video.json index bed972a6..33bb3727 100644 --- a/public/locales/hi/video.json +++ b/public/locales/hi/video.json @@ -1,17 +1,14 @@ { "changeSpeed": { - "defaultMultiplier": "डिफ़ॉल्ट गुणक: 2 का अर्थ है 2x तेज़", "description": "वीडियो फ़ाइलों की प्लेबैक गति बदलें।", "factorPlaceholder": "कारक (जैसे 0.5, 1.5, 2.0)", "formatAvi": "AVI", "formatMov": "MOV", "formatMp4": "MP4", "inputTitle": "इनपुट वीडियो", - "newVideoSpeed": "नई वीडियो स्पीड", "outputFormat": "आउटपुट प्रारूप", "preserveAudio": "ऑडियो संरक्षित करें", "resultTitle": "गति बदली गई वीडियो", - "settingSpeed": "गति सेट करना", "shortDescription": "वीडियो प्लेबैक गति बदलें", "speedFactor": "गति कारक", "speedOptions": "गति विकल्प", @@ -94,7 +91,6 @@ "directionVertical": "लंबवत", "flipDirection": "फ्लिप दिशा", "flipOptions": "फ्लिप विकल्प", - "flippingVideo": "फ़्लिपिंग वीडियो", "horizontalLabel": "क्षैतिज (दर्पण)", "inputTitle": "इनपुट वीडियो", "orientation": "अभिविन्यास", @@ -128,7 +124,6 @@ "loopCount": "लूप की संख्या", "loopInfinitely": "अनंत लूप", "loopOptions": "लूप विकल्प", - "loopingVideo": "पाशन वीडियो", "loops": "छोरों", "numberOfLoops": "लूपों की संख्या", "resultTitle": "लूप वीडियो", @@ -158,7 +153,6 @@ "inputTitle": "इनपुट वीडियो", "preserveAudio": "ऑडियो संरक्षित करें", "resultTitle": "घुमाया गया वीडियो", - "rotatingVideo": "घूमता हुआ वीडियो", "rotation": "ROTATION", "rotationAngle": "घुमाने का कोण", "rotationOptions": "घुमाने के विकल्प", @@ -178,24 +172,5 @@ "timestamps": "मुहर", "title": "वीडियो ट्रिम करें", "trimOptions": "ट्रिम विकल्प" - }, - "videoToGif": { - "conversionOptions": "रूपांतरण विकल्प", - "description": "वीडियो को GIF एनिमेटेड फ़ाइल में बदलें।", - "frameRate": "फ्रेम दर", - "frameRatePlaceholder": "FPS", - "height": "ऊंचाई", - "heightPlaceholder": "पिक्सेल", - "inputTitle": "इनपुट वीडियो", - "quality": "गुणवत्ता", - "qualityHigh": "उच्च", - "qualityLow": "कम", - "qualityMedium": "मध्यम", - "resize": "आकार बदलें", - "resultTitle": "GIF फ़ाइल", - "shortDescription": "वीडियो को एनिमेटेड GIF में बदलें", - "title": "वीडियो से GIF", - "width": "चौड़ाई", - "widthPlaceholder": "पिक्सेल" } } diff --git a/public/locales/ja/audio.json b/public/locales/ja/audio.json index 9126ac1a..a560c09d 100644 --- a/public/locales/ja/audio.json +++ b/public/locales/ja/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "速度設定", "shortDescription": "オーディオファイルの速度を変更する", "speedDescription": "デフォルトの乗数: 2は2倍速を意味します", - "title": "オーディオ速度を変更する", - "toolInfo": { - "title": "何ですか {{title}}?" - } + "title": "オーディオ速度を変更する" }, "extractAudio": { "description": "ビデオ ファイルからオーディオ トラックを抽出します。", @@ -31,7 +28,6 @@ "description": "複数のオーディオ ファイルを順番に連結して 1 つのオーディオ ファイルに結合します。", "inputTitle": "入力オーディオファイル", "longDescription": "このツールを使えば、複数のオーディオファイルをアップロード順に連結し、1つのファイルにまとめることができます。ポッドキャストのセグメント、音楽トラック、その他様々なオーディオファイルを結合するのに最適です。MP3、AAC、WAVなど、様々なオーディオ形式に対応しています。", - "mergingAudio": "オーディオの結合", "outputFormat": "出力形式", "resultTitle": "統合オーディオ", "shortDescription": "複数のオーディオ ファイルを 1 つに結合します (MP3、AAC、WAV)。", @@ -55,7 +51,6 @@ "title": "オーディオをトリムする", "toolInfo": { "title": "何ですか {{title}}?" - }, - "trimmingAudio": "オーディオのトリミング" + } } } diff --git a/public/locales/ja/string.json b/public/locales/ja/string.json index ca7d31a1..d4cfca2e 100644 --- a/public/locales/ja/string.json +++ b/public/locales/ja/string.json @@ -84,7 +84,7 @@ "includeNumbers": "数字を含める(0~9)", "includeSymbols": "特殊文字を含める", "includeUppercase": "大文字(A~Z)を含める", - "lengthDesc": "パスワードの長さ", + "lengthDesc": "パスワードの長さ (>3 & <257)", "lengthPlaceholder": "例:12", "optionsTitle": "パスワードオプション", "resultTitle": "生成されたパスワード", diff --git a/public/locales/ja/time.json b/public/locales/ja/time.json index fceccca2..47a3a84a 100644 --- a/public/locales/ja/time.json +++ b/public/locales/ja/time.json @@ -64,7 +64,6 @@ "date-to-unix": "日付 → Unix", "description": "Unix タイムスタンプを読み取り可能な日付に変換し、フォーマットされた日付を Unix タイムスタンプに変換します(両方向)。", "optionsTitle": "変換モード", - "outputOptions": "出力オプション", "shortDescription": "Unix タイムスタンプと日付を両方向に変換します。", "title": "Unix ↔ 日付を変換する", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "UTC を使用する" }, "crontabGuru": { - "title": "Crontab Guru", "description": "cron式を日本語で解析・説明します。任意のcronスケジュールの動作を即座に理解し、構文を検証し、複数の式を一度に処理できます。", + "longDescription": "Crontab Guruは、複雑なcron構文をわかりやすい説明に変換するcron式パーサー・バリデーターです。自動バックアップ、システムメンテナンスタスク、CI/CDパイプラインのスケジュール設定など、ジョブがいつ実行されるかを正確に把握できます。標準的な5フィールドのcron式をサポートし、構文をリアルタイムで検証し、複数の式を一度に処理します(1行に1つ)。英語、フランス語、スペイン語、ドイツ語、日本語、中国語、ポルトガル語、オランダ語、ロシア語に対応しています。", "shortDescription": "cron式をわかりやすく解析・説明する", - "longDescription": "Crontab Guruは、複雑なcron構文をわかりやすい説明に変換するcron式パーサー・バリデーターです。自動バックアップ、システムメンテナンスタスク、CI/CDパイプラインのスケジュール設定など、ジョブがいつ実行されるかを正確に把握できます。標準的な5フィールドのcron式をサポートし、構文をリアルタイムで検証し、複数の式を一度に処理します(1行に1つ)。英語、フランス語、スペイン語、ドイツ語、日本語、中国語、ポルトガル語、オランダ語、ロシア語に対応しています。" + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "2つの日付間の時差を計算します。正確な日数、時間、分、秒を取得します。", diff --git a/public/locales/ja/translation.json b/public/locales/ja/translation.json index 89ea2211..66e131d8 100644 --- a/public/locales/ja/translation.json +++ b/public/locales/ja/translation.json @@ -95,8 +95,8 @@ "trimVideo": "ビデオをトリミングする" }, "search": { - "placeholder": "すべてのツールを検索", - "noResult": "結果が見つかりません。検索条件またはフィルター条件を調整してみてください" + "noResult": "結果が見つかりません。検索条件またはフィルター条件を調整してみてください", + "placeholder": "すべてのツールを検索" }, "title": "物事を素早く終わらせる" }, @@ -229,9 +229,9 @@ "result": "結果" }, "toolMultipleInput": { + "deleteFile": "ファイルを削除", "inputTitle": "{{type}}を入力", - "noFilesSelected": "ファイルが選択されていません", - "deleteFile": "ファイルを削除" + "noFilesSelected": "ファイルが選択されていません" }, "toolOptions": { "title": "ツールオプション" diff --git a/public/locales/ja/video.json b/public/locales/ja/video.json index 32095a65..5bbdb37b 100644 --- a/public/locales/ja/video.json +++ b/public/locales/ja/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "デフォルトの乗数: 2は2倍速を意味します", "description": "動画ファイルの再生速度を変更できます。音声の同期を維持しながら、動画の再生速度を上げたり下げたりできます。様々な速度調整機能と一般的な動画形式に対応しています。", "inputTitle": "入力ビデオ", - "newVideoSpeed": "新しいビデオ速度", "resultTitle": "編集されたビデオ", - "settingSpeed": "速度設定", "shortDescription": "ビデオの再生速度を変更する", "title": "ビデオ速度の変更", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "ビデオファイルを水平または垂直に反転します。特殊効果や向きの問題を修正するためにビデオをミラーリングします。", - "flippingVideo": "反転ビデオ", "horizontalLabel": "水平(ミラー)", "inputTitle": "入力ビデオ", "orientation": "オリエンテーション", @@ -73,7 +69,6 @@ "loop": { "description": "元のビデオを複数回繰り返してループビデオを作成します。", "inputTitle": "入力ビデオ", - "loopingVideo": "ループビデオ", "loops": "ループ", "numberOfLoops": "ループ数", "resultTitle": "ループ動画", @@ -97,7 +92,6 @@ "description": "ビデオファイルを90度、180度、または270度回転できます。正確な回転制御により、ビデオの向きを修正したり、特殊効果を作成したりできます。", "inputTitle": "入力ビデオ", "resultTitle": "回転したビデオ", - "rotatingVideo": "回転するビデオ", "rotation": "回転", "shortDescription": "指定した角度でビデオを回転する", "title": "ビデオを回転する" @@ -111,10 +105,5 @@ "startTime": "開始時間", "timestamps": "タイムスタンプ", "title": "ビデオをトリムする" - }, - "videoToGif": { - "description": "ビデオファイルをアニメーションGIF形式に変換します。特定の時間範囲を抽出し、共有可能なアニメーション画像を作成します。", - "shortDescription": "ビデオをアニメーションGIFに変換する", - "title": "ビデオをGIFに変換" } } diff --git a/public/locales/nl/audio.json b/public/locales/nl/audio.json index 24a043bc..e00070b0 100644 --- a/public/locales/nl/audio.json +++ b/public/locales/nl/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Snelheid instellen", "shortDescription": "De snelheid van audiobestanden wijzigen", "speedDescription": "Standaardvermenigvuldiger: 2 betekent 2x sneller", - "title": "Wijzig audiosnelheid", - "toolInfo": { - "title": "Wat is {{title}}?" - } + "title": "Wijzig audiosnelheid" }, "extractAudio": { "description": "Haal een audiotrack uit videobestanden.", @@ -31,7 +28,6 @@ "description": "Combineer meerdere audiobestanden tot één audiobestand door ze in volgorde te plaatsen.", "inputTitle": "Invoer audiobestanden", "longDescription": "Met deze tool kun je meerdere audiobestanden samenvoegen tot één bestand door ze te combineren in de volgorde waarin je ze uploadt. Perfect voor het combineren van podcastfragmenten, muzieknummers of andere audiobestanden die moeten worden samengevoegd. Ondersteunt diverse audioformaten, waaronder MP3, AAC en WAV.", - "mergingAudio": "Audio samenvoegen", "outputFormat": "Uitvoerformaat", "resultTitle": "Samengevoegde audio", "shortDescription": "Voeg meerdere audiobestanden samen tot één bestand (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Audio bijsnijden", "toolInfo": { "title": "Wat is {{title}}?" - }, - "trimmingAudio": "Audio bijsnijden" + } } } diff --git a/public/locales/nl/string.json b/public/locales/nl/string.json index 53dd230d..0e582785 100644 --- a/public/locales/nl/string.json +++ b/public/locales/nl/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Inclusief cijfers (0-9)", "includeSymbols": "Speciale tekens toevoegen", "includeUppercase": "Inclusief hoofdletters (A-Z)", - "lengthDesc": "Lengte van het wachtwoord", + "lengthDesc": "Lengte van het wachtwoord (>3 & <257)", "lengthPlaceholder": "bijv. 12", "optionsTitle": "Wachtwoordopties", "resultTitle": "gegenereerd wachtwoord", diff --git a/public/locales/nl/time.json b/public/locales/nl/time.json index 66b4c579..13c2680f 100644 --- a/public/locales/nl/time.json +++ b/public/locales/nl/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Datum → Unix", "description": "Converteer Unix-tijdstempels naar leesbare datums en converteer geformatteerde datums terug naar Unix-tijdstempels (in beide richtingen).", "optionsTitle": "Conversie-modus", - "outputOptions": "Uitvoeropties", "shortDescription": "Converteer Unix-tijdstempels en datums in beide richtingen.", "title": "Unix ↔ Datum converteren", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "UTC gebruiken" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Parseer en verklaar cron-expressies in het Nederlands. Begrijp direct wat een cron-schema doet, valideer de syntaxis en verwerk meerdere expressies tegelijk.", + "longDescription": "Crontab Guru is een cron-expressie-parser en -validator die complexe cron-syntaxis vertaalt naar duidelijke, leesbare beschrijvingen. Of u nu automatische back-ups, systeemonderhoudstaken of CI/CD-pipelines plant, deze tool helpt u precies te begrijpen wanneer uw taken worden uitgevoerd. Ondersteunt standaard cron-expressies met 5 velden, valideert de syntaxis in realtime en verwerkt meerdere expressies tegelijk — één per regel. Beschikbaar in het Engels, Frans, Spaans, Duits, Japans, Chinees, Portugees, Nederlands en Russisch.", "shortDescription": "Cron-expressies parseren en in begrijpelijke taal uitleggen", - "longDescription": "Crontab Guru is een cron-expressie-parser en -validator die complexe cron-syntaxis vertaalt naar duidelijke, leesbare beschrijvingen. Of u nu automatische back-ups, systeemonderhoudstaken of CI/CD-pipelines plant, deze tool helpt u precies te begrijpen wanneer uw taken worden uitgevoerd. Ondersteunt standaard cron-expressies met 5 velden, valideert de syntaxis in realtime en verwerkt meerdere expressies tegelijk — één per regel. Beschikbaar in het Engels, Frans, Spaans, Duits, Japans, Chinees, Portugees, Nederlands en Russisch." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Bereken het tijdsverschil tussen twee datums. Bereken de exacte duur in dagen, uren, minuten en seconden.", diff --git a/public/locales/nl/translation.json b/public/locales/nl/translation.json index 12e11dc5..ce21dd34 100644 --- a/public/locales/nl/translation.json +++ b/public/locales/nl/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Video bijsnijden" }, "search": { - "placeholder": "Alle tools doorzoeken", - "noResult": "Geen resultaten gevonden, probeer uw zoekopdracht of filtercriteria aan te passen" + "noResult": "Geen resultaten gevonden, probeer uw zoekopdracht of filtercriteria aan te passen", + "placeholder": "Alle tools doorzoeken" }, "title": "Krijg dingen snel gedaan met" }, @@ -229,9 +229,9 @@ "result": "Resultaat" }, "toolMultipleInput": { + "deleteFile": "Bestand verwijderen", "inputTitle": "Invoer {{type}}", - "noFilesSelected": "Geen bestanden geselecteerd", - "deleteFile": "Bestand verwijderen" + "noFilesSelected": "Geen bestanden geselecteerd" }, "toolOptions": { "title": "Gereedschapsopties" diff --git a/public/locales/nl/video.json b/public/locales/nl/video.json index 2408d847..152cedae 100644 --- a/public/locales/nl/video.json +++ b/public/locales/nl/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Standaardvermenigvuldiger: 2 betekent 2x sneller", "description": "Wijzig de afspeelsnelheid van videobestanden. Versnel of vertraag video's met behoud van audiosynchronisatie. Ondersteunt diverse snelheidsvermenigvuldigers en gangbare videoformaten.", "inputTitle": "Invoervideo", - "newVideoSpeed": "Nieuwe videosnelheid", "resultTitle": "Bewerkte video", - "settingSpeed": "Snelheid instellen", "shortDescription": "Wijzig de afspeelsnelheid van video", "title": "Videosnelheid wijzigen", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Draai videobestanden horizontaal of verticaal. Spiegel video's voor speciale effecten of om problemen met de oriëntatie te corrigeren.", - "flippingVideo": "Flipping Video", "horizontalLabel": "Horizontaal (Spiegel)", "inputTitle": "Invoervideo", "orientation": "Oriëntatie", @@ -73,7 +69,6 @@ "loop": { "description": "Maak een herhalende video door de originele video meerdere keren te herhalen.", "inputTitle": "Invoervideo", - "loopingVideo": "Video herhalen", "loops": "Lussen", "numberOfLoops": "Aantal lussen", "resultTitle": "Geloopte video", @@ -97,7 +92,6 @@ "description": "Roteer videobestanden 90, 180 of 270 graden. Corrigeer de video-oriëntatie of creëer speciale effecten met nauwkeurige rotatiecontrole.", "inputTitle": "Invoervideo", "resultTitle": "Gedraaide video", - "rotatingVideo": "Roterende video", "rotation": "Rotatie", "shortDescription": "Video met opgegeven graden roteren", "title": "Video roteren" @@ -111,10 +105,5 @@ "startTime": "Starttijd", "timestamps": "Tijdstempels", "title": "Video bijsnijden" - }, - "videoToGif": { - "description": "Converteer videobestanden naar geanimeerde GIF-indeling. Extraheer specifieke tijdsperioden en maak deelbare geanimeerde afbeeldingen.", - "shortDescription": "Converteer video naar geanimeerde GIF", - "title": "Video naar GIF" } } diff --git a/public/locales/pt/audio.json b/public/locales/pt/audio.json index cd63907f..457a88f1 100644 --- a/public/locales/pt/audio.json +++ b/public/locales/pt/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Definindo a velocidade", "shortDescription": "Alterar a velocidade dos arquivos de áudio", "speedDescription": "Multiplicador padrão: 2 significa 2x mais rápido", - "title": "Alterar velocidade do áudio", - "toolInfo": { - "title": "O que é {{title}}?" - } + "title": "Alterar velocidade do áudio" }, "extractAudio": { "description": "Extraia faixas de áudio de arquivos de vídeo.", @@ -31,7 +28,6 @@ "description": "Combine vários arquivos de áudio em um único arquivo de áudio concatenando-os em sequência.", "inputTitle": "Arquivos de áudio de entrada", "longDescription": "Esta ferramenta permite mesclar vários arquivos de áudio em um único arquivo, concatenando-os na ordem em que foram enviados. Perfeito para combinar segmentos de podcast, faixas de música ou qualquer arquivo de áudio que precise ser unido. Suporta vários formatos de áudio, incluindo MP3, AAC e WAV.", - "mergingAudio": "Mesclando áudio", "outputFormat": "Formato de saída", "resultTitle": "Áudio mesclado", "shortDescription": "Mescle vários arquivos de áudio em um (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Aparar áudio", "toolInfo": { "title": "O que é {{title}}?" - }, - "trimmingAudio": "Cortando áudio" + } } } diff --git a/public/locales/pt/string.json b/public/locales/pt/string.json index 8d10bae3..e398a3a3 100644 --- a/public/locales/pt/string.json +++ b/public/locales/pt/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Incluir números (0-9)", "includeSymbols": "Incluir caracteres especiais", "includeUppercase": "Incluir letras maiúsculas (A-Z)", - "lengthDesc": "Comprimento da senha", + "lengthDesc": "Comprimento da senha (>3 & <257)", "lengthPlaceholder": "por exemplo 12", "optionsTitle": "Opções de senha", "resultTitle": "Senha gerada", diff --git a/public/locales/pt/time.json b/public/locales/pt/time.json index f34f9d3c..54e4a3e5 100644 --- a/public/locales/pt/time.json +++ b/public/locales/pt/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Data → Unix", "description": "Converta registros de data e hora Unix em datas legíveis e converta datas formatadas de volta para registros de data e hora Unix (em ambas as direções).", "optionsTitle": "Modo de conversão", - "outputOptions": "Opções de saída", "shortDescription": "Converta registros de data e hora Unix e datas em ambas as direções.", "title": "Converter Unix ↔ Data", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "Usar UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Analise e explique expressões cron em português. Entenda instantaneamente o que qualquer agendamento cron faz, valide a sintaxe e processe múltiplas expressões de uma vez.", + "longDescription": "O Crontab Guru é um analisador e validador de expressões cron que traduz a sintaxe complexa do cron em descrições claras e legíveis. Seja para agendar backups automáticos, tarefas de manutenção do sistema ou pipelines de CI/CD, esta ferramenta ajuda-o a perceber exatamente quando os seus trabalhos serão executados. Suporta expressões cron padrão de 5 campos, valida a sintaxe em tempo real e processa múltiplas expressões de uma vez — uma por linha. Disponível em inglês, francês, espanhol, alemão, japonês, chinês, português, neerlandês e russo.", "shortDescription": "Analise e explique expressões cron em linguagem simples", - "longDescription": "O Crontab Guru é um analisador e validador de expressões cron que traduz a sintaxe complexa do cron em descrições claras e legíveis. Seja para agendar backups automáticos, tarefas de manutenção do sistema ou pipelines de CI/CD, esta ferramenta ajuda-o a perceber exatamente quando os seus trabalhos serão executados. Suporta expressões cron padrão de 5 campos, valida a sintaxe em tempo real e processa múltiplas expressões de uma vez — uma por linha. Disponível em inglês, francês, espanhol, alemão, japonês, chinês, português, neerlandês e russo." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Calcule a diferença de tempo entre duas datas. Obtenha a duração exata em dias, horas, minutos e segundos.", diff --git a/public/locales/pt/translation.json b/public/locales/pt/translation.json index 74cb3249..f7905931 100644 --- a/public/locales/pt/translation.json +++ b/public/locales/pt/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Cortar vídeo" }, "search": { - "placeholder": "Pesquisar todas as ferramentas", - "noResult": "Nenhum resultado encontrado, tente ajustar a sua pesquisa ou os critérios de filtro" + "noResult": "Nenhum resultado encontrado, tente ajustar a sua pesquisa ou os critérios de filtro", + "placeholder": "Pesquisar todas as ferramentas" }, "title": "Faça as coisas rapidamente com" }, @@ -229,9 +229,9 @@ "result": "Resultado" }, "toolMultipleInput": { + "deleteFile": "Eliminar ficheiro", "inputTitle": "Entrada {{type}}", - "noFilesSelected": "Nenhum ficheiro selecionado", - "deleteFile": "Eliminar ficheiro" + "noFilesSelected": "Nenhum ficheiro selecionado" }, "toolOptions": { "title": "Opções de ferramentas" diff --git a/public/locales/pt/video.json b/public/locales/pt/video.json index 35dbe6ed..34e30903 100644 --- a/public/locales/pt/video.json +++ b/public/locales/pt/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Multiplicador padrão: 2 significa 2x mais rápido", "description": "Altere a velocidade de reprodução de arquivos de vídeo. Acelere ou desacelere vídeos, mantendo a sincronização do áudio. Suporta vários multiplicadores de velocidade e formatos de vídeo comuns.", "inputTitle": "Entrada de vídeo", - "newVideoSpeed": "Nova velocidade de vídeo", "resultTitle": "Vídeo editado", - "settingSpeed": "Definindo a velocidade", "shortDescription": "Alterar a velocidade de reprodução do vídeo", "title": "Alterar velocidade do vídeo", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Inverta arquivos de vídeo horizontal ou verticalmente. Espelhe vídeos para obter efeitos especiais ou corrigir problemas de orientação.", - "flippingVideo": "Invertendo o vídeo", "horizontalLabel": "Horizontal (Espelho)", "inputTitle": "Entrada de vídeo", "orientation": "Orientação", @@ -73,7 +69,6 @@ "loop": { "description": "Crie um vídeo em loop repetindo o vídeo original várias vezes.", "inputTitle": "Entrada de vídeo", - "loopingVideo": "Vídeo em loop", "loops": "Laços", "numberOfLoops": "Número de Loops", "resultTitle": "Vídeo em loop", @@ -97,7 +92,6 @@ "description": "Gire arquivos de vídeo em 90, 180 ou 270 graus. Corrija a orientação do vídeo ou crie efeitos especiais com controle de rotação preciso.", "inputTitle": "Entrada de vídeo", "resultTitle": "Vídeo girado", - "rotatingVideo": "Vídeo rotativo", "rotation": "Rotação", "shortDescription": "Girar o vídeo em graus especificados", "title": "Girar vídeo" @@ -111,10 +105,5 @@ "startTime": "Hora de início", "timestamps": "Carimbos de data e hora", "title": "Cortar vídeo" - }, - "videoToGif": { - "description": "Converta arquivos de vídeo para o formato GIF animado. Extraia intervalos de tempo específicos e crie imagens animadas compartilháveis.", - "shortDescription": "Converter vídeo em GIF animado", - "title": "Vídeo para GIF" } } diff --git a/public/locales/ru/audio.json b/public/locales/ru/audio.json index 5e0706b0..bfc6aa0b 100644 --- a/public/locales/ru/audio.json +++ b/public/locales/ru/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Скорость установки", "shortDescription": "Изменить скорость аудиофайлов", "speedDescription": "Множитель по умолчанию: 2 означает в 2 раза быстрее", - "title": "Изменить скорость звука", - "toolInfo": { - "title": "Что такое {{title}}?" - } + "title": "Изменить скорость звука" }, "extractAudio": { "description": "Извлечь звуковую дорожку из видеофайлов.", @@ -31,7 +28,6 @@ "description": "Объедините несколько аудиофайлов в один, объединив их последовательно.", "inputTitle": "Входные аудиофайлы", "longDescription": "Этот инструмент позволяет объединить несколько аудиофайлов в один, объединяя их в порядке загрузки. Идеально подходит для объединения фрагментов подкастов, музыкальных треков и любых других аудиофайлов, которые необходимо объединить. Поддерживает различные аудиоформаты, включая MP3, AAC и WAV.", - "mergingAudio": "Объединение аудио", "outputFormat": "Формат вывода", "resultTitle": "Объединенный аудио", "shortDescription": "Объединить несколько аудиофайлов в один (MP3, AAC, WAV).", @@ -55,7 +51,6 @@ "title": "Обрезать аудио", "toolInfo": { "title": "Что такое {{title}}?" - }, - "trimmingAudio": "Обрезка аудио" + } } } diff --git a/public/locales/ru/image.json b/public/locales/ru/image.json index 8290de1b..62fe9823 100644 --- a/public/locales/ru/image.json +++ b/public/locales/ru/image.json @@ -98,43 +98,43 @@ "title": "Повернуть изображение" }, "split": { - "title": "Разбить изображение по страницам", - "shortDescription": "Разбивает большое изображение на несколько страниц (PDF).", "description": "Разбивает карту или большое изображение на страницы выбранного формата с учётом полей. Укажите количество пикселей на заданное число клеток и их количество для корректного масштабирования.", "inputTitle": "Входное изображение", - "resultTitle": "PDF с разрезанными страницами", "loadingText": "Загрузка... Это может занять некоторое время.", "pageParameters": { - "title": "Параметры страницы", - "selectPageFormat": "Выберите формат страницы", "padding": { - "label": "Отступ", - "description": "Отступ вокруг карты на каждой странице (в выбранных единицах)" - } + "description": "Отступ вокруг карты на каждой странице (в выбранных единицах)", + "label": "Отступ" + }, + "selectPageFormat": "Выберите формат страницы", + "title": "Параметры страницы" }, + "resultTitle": "PDF с разрезанными страницами", "scaleParameters": { - "title": "Параметры масштаба", "pxPerSquareQuantity": { - "label": "Пикселей на количество клеток", - "description": "Сколько пикселей соответствует указанному количеству клеток на исходном изображении (по горизонтали или вертикали)" + "description": "Сколько пикселей соответствует указанному количеству клеток на исходном изображении (по горизонтали или вертикали)", + "label": "Пикселей на количество клеток" }, "squareQuantity": { - "label": "Количество клеток", - "description": "Число игровых клеток по горизонтали или вертикали, используемое для масштабирования" + "description": "Число игровых клеток по горизонтали или вертикали, используемое для масштабирования", + "label": "Количество клеток" }, + "title": "Параметры масштаба", "unitsPerOneSquare": { - "label": "Размер клетки", - "description": "Физический размер одной клетки в выбранных единицах" + "description": "Физический размер одной клетки в выбранных единицах", + "label": "Размер клетки" } }, + "shortDescription": "Разбивает большое изображение на несколько страниц (PDF).", + "title": "Разбить изображение по страницам", "units": { - "title": "Единицы измерения", - "select": "Выберите единицы измерения", "options": { - "pt": "Пункты (pt)", + "in": "Дюймы (in)", "mm": "Миллиметры (мм)", - "in": "Дюймы (in)" - } + "pt": "Пункты (pt)" + }, + "select": "Выберите единицы измерения", + "title": "Единицы измерения" } } } diff --git a/public/locales/ru/string.json b/public/locales/ru/string.json index 714ae84e..1d921246 100644 --- a/public/locales/ru/string.json +++ b/public/locales/ru/string.json @@ -84,7 +84,7 @@ "includeNumbers": "Включить цифры (0-9)", "includeSymbols": "Включить специальные символы", "includeUppercase": "Включайте заглавные буквы (A–Z)", - "lengthDesc": "Длина пароля", + "lengthDesc": "Длина пароля (>3 & <257)", "lengthPlaceholder": "например, 12", "optionsTitle": "Параметры пароля", "resultTitle": "Сгенерированный пароль", diff --git a/public/locales/ru/time.json b/public/locales/ru/time.json index 2f6db7c6..5459bff8 100644 --- a/public/locales/ru/time.json +++ b/public/locales/ru/time.json @@ -64,7 +64,6 @@ "date-to-unix": "Дата → Unix", "description": "Преобразуйте временные метки Unix в читаемые даты и обратно преобразуйте отформатированные даты в временные метки Unix (в обе стороны).", "optionsTitle": "Режим преобразования", - "outputOptions": "Параметры вывода", "shortDescription": "Преобразуйте временные метки Unix и даты в обе стороны.", "title": "Преобразовать Unix ↔ Дату", "toolInfo": { @@ -78,10 +77,10 @@ "useUTC": "Использовать UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "Разбирайте и объясняйте cron-выражения на русском языке. Мгновенно понимайте, что делает любое cron-расписание, проверяйте синтаксис и обрабатывайте несколько выражений одновременно.", + "longDescription": "Crontab Guru — это парсер и валидатор cron-выражений, который переводит сложный синтаксис cron в понятные человеку описания. Независимо от того, планируете ли вы автоматическое резервное копирование, задачи обслуживания системы или CI/CD-пайплайны, этот инструмент поможет вам точно понять, когда будут выполняться ваши задания. Поддерживает стандартные 5-польные cron-выражения, проверяет синтаксис в реальном времени и обрабатывает несколько выражений одновременно — по одному на строку. Доступно на английском, французском, испанском, немецком, японском, китайском, португальском, нидерландском и русском языках.", "shortDescription": "Разбор и объяснение cron-выражений простым языком", - "longDescription": "Crontab Guru — это парсер и валидатор cron-выражений, который переводит сложный синтаксис cron в понятные человеку описания. Независимо от того, планируете ли вы автоматическое резервное копирование, задачи обслуживания системы или CI/CD-пайплайны, этот инструмент поможет вам точно понять, когда будут выполняться ваши задания. Поддерживает стандартные 5-польные cron-выражения, проверяет синтаксис в реальном времени и обрабатывает несколько выражений одновременно — по одному на строку. Доступно на английском, французском, испанском, немецком, японском, китайском, португальском, нидерландском и русском языках." + "title": "Crontab Guru" }, "timeBetweenDates": { "description": "Рассчитайте разницу во времени между двумя датами. Получите точную продолжительность в днях, часах, минутах и секундах.", diff --git a/public/locales/ru/translation.json b/public/locales/ru/translation.json index 7b4cf97b..58dac6dd 100644 --- a/public/locales/ru/translation.json +++ b/public/locales/ru/translation.json @@ -95,8 +95,8 @@ "trimVideo": "Обрезать видео" }, "search": { - "placeholder": "Поиск по всем инструментам", - "noResult": "Результаты не найдены, попробуйте изменить параметры поиска или фильтрации" + "noResult": "Результаты не найдены, попробуйте изменить параметры поиска или фильтрации", + "placeholder": "Поиск по всем инструментам" }, "title": "Выполняйте задачи быстро с помощью" }, @@ -229,9 +229,9 @@ "result": "Результат" }, "toolMultipleInput": { + "deleteFile": "Удалить файл", "inputTitle": "Ввод {{type}}", - "noFilesSelected": "Файлы не выбраны", - "deleteFile": "Удалить файл" + "noFilesSelected": "Файлы не выбраны" }, "toolOptions": { "title": "Параметры инструмента" diff --git a/public/locales/ru/video.json b/public/locales/ru/video.json index c93eacbd..9de0c629 100644 --- a/public/locales/ru/video.json +++ b/public/locales/ru/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "Множитель по умолчанию: 2 означает в 2 раза быстрее", "description": "Изменяйте скорость воспроизведения видеофайлов. Ускоряйте или замедляйте видео, сохраняя синхронизацию со звуком. Поддерживает различные коэффициенты ускорения и распространённые видеоформаты.", "inputTitle": "Входное видео", - "newVideoSpeed": "Новая скорость видео", "resultTitle": "Отредактированное видео", - "settingSpeed": "Скорость установки", "shortDescription": "Изменить скорость воспроизведения видео", "title": "Изменить скорость видео", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "Переворачивайте видеофайлы по горизонтали или вертикали. Зеркально отображайте видео для создания спецэффектов или исправления проблем с ориентацией.", - "flippingVideo": "Перелистывание видео", "horizontalLabel": "Горизонтальный (Зеркальный)", "inputTitle": "Входное видео", "orientation": "Ориентация", @@ -73,7 +69,6 @@ "loop": { "description": "Создайте зацикленное видео, повторив исходное видео несколько раз.", "inputTitle": "Входное видео", - "loopingVideo": "Зацикливание видео", "loops": "Петли", "numberOfLoops": "Количество петель", "resultTitle": "Зацикленное видео", @@ -97,7 +92,6 @@ "description": "Поворачивайте видеофайлы на 90, 180 или 270 градусов. Корректируйте ориентацию видео или создавайте спецэффекты с помощью точного управления поворотом.", "inputTitle": "Входное видео", "resultTitle": "Повернутое видео", - "rotatingVideo": "Вращение видео", "rotation": "Вращение", "shortDescription": "Повернуть видео на указанный угол", "title": "Повернуть видео" @@ -111,10 +105,5 @@ "startTime": "Время начала", "timestamps": "Временные метки", "title": "Обрезать видео" - }, - "videoToGif": { - "description": "Конвертируйте видеофайлы в анимированный GIF-формат. Извлекайте определённые временные диапазоны и создавайте анимированные изображения для публикации.", - "shortDescription": "Конвертировать видео в анимированный GIF", - "title": "Видео в GIF" } } diff --git a/public/locales/zh/audio.json b/public/locales/zh/audio.json index dabd03b4..0f85e6ac 100644 --- a/public/locales/zh/audio.json +++ b/public/locales/zh/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "设定速度", "shortDescription": "更改音频文件的速度", "speedDescription": "默认乘数:2 表示速度快 2 倍", - "title": "更改音频速度", - "toolInfo": { - "title": "什么是 {{title}}?" - } + "title": "更改音频速度" }, "extractAudio": { "description": "从视频文件中提取音轨。", @@ -31,7 +28,6 @@ "description": "按顺序连接多个音频文件,将其合并为一个音频文件。", "inputTitle": "输入音频文件", "longDescription": "此工具允许您将多个音频文件按照上传顺序串联成一个文件。非常适合合并播客片段、音乐曲目或任何需要合并的音频文件。支持多种音频格式,包括 MP3、AAC 和 WAV。", - "mergingAudio": "合并音频", "outputFormat": "输出格式", "resultTitle": "合并音频", "shortDescription": "将多个音频文件合并为一个(MP3、AAC、WAV)。", @@ -55,7 +51,6 @@ "title": "修剪音频", "toolInfo": { "title": "什么是 {{title}}?" - }, - "trimmingAudio": "修剪音频" + } } } diff --git a/public/locales/zh/string.json b/public/locales/zh/string.json index 89593c6d..856bd9f7 100644 --- a/public/locales/zh/string.json +++ b/public/locales/zh/string.json @@ -84,7 +84,7 @@ "includeNumbers": "包含数字 (0-9)", "includeSymbols": "包含特殊字符", "includeUppercase": "包含大写字母(A-Z)", - "lengthDesc": "密码长度", + "lengthDesc": "密码长度 (>3 & <257)", "lengthPlaceholder": "例如 12", "optionsTitle": "密码选项", "resultTitle": "生成的密码", diff --git a/public/locales/zh/time.json b/public/locales/zh/time.json index c61a4348..79c46a0d 100644 --- a/public/locales/zh/time.json +++ b/public/locales/zh/time.json @@ -70,7 +70,6 @@ "date-to-unix": "日期 → Unix", "description": "将 Unix 时间戳转换为可读日期,并将格式化日期转换回 Unix 时间戳(双向转换)。", "optionsTitle": "转换模式", - "outputOptions": "输出选项", "shortDescription": "双向转换 Unix 时间戳和日期。", "title": "转换 Unix ↔ 日期", "toolInfo": { @@ -84,10 +83,10 @@ "useUTC": "使用 UTC" }, "crontabGuru": { - "title": "Crontab Guru", "description": "用中文解析和解释 cron 表达式。即时了解任何 cron 计划的作用,验证语法,并一次处理多个表达式。", + "longDescription": "Crontab Guru 是一个 cron 表达式解析器和验证器,可将复杂的 cron 语法转换为清晰易读的描述。无论您是在安排自动备份、系统维护任务还是 CI/CD 流水线,此工具都能帮助您准确了解您的任务何时运行。支持标准的 5 字段 cron 表达式,实时验证语法,并一次处理多个表达式——每行一个。支持英语、法语、西班牙语、德语、日语、中文、葡萄牙语、荷兰语和俄语。", "shortDescription": "用简单语言解析和解释 cron 表达式", - "longDescription": "Crontab Guru 是一个 cron 表达式解析器和验证器,可将复杂的 cron 语法转换为清晰易读的描述。无论您是在安排自动备份、系统维护任务还是 CI/CD 流水线,此工具都能帮助您准确了解您的任务何时运行。支持标准的 5 字段 cron 表达式,实时验证语法,并一次处理多个表达式——每行一个。支持英语、法语、西班牙语、德语、日语、中文、葡萄牙语、荷兰语和俄语。" + "title": "Crontab Guru" }, "discordTimestamp": { "description": "将日期和时间转换为 Discord 的特殊时间戳格式,自动适应每位用户的本地时区和语言", diff --git a/public/locales/zh/translation.json b/public/locales/zh/translation.json index 8f89155b..7963b7b8 100644 --- a/public/locales/zh/translation.json +++ b/public/locales/zh/translation.json @@ -99,8 +99,8 @@ "trimVideo": "修剪视频" }, "search": { - "placeholder": "搜索所有工具", - "noResult": "未找到结果 请尝试调整搜索或筛选条件" + "noResult": "未找到结果 请尝试调整搜索或筛选条件", + "placeholder": "搜索所有工具" }, "title": "快速完成工作" }, @@ -226,10 +226,6 @@ "toolLayout": { "allToolsTitle": "全部 {{type}}" }, - "toolsByCategory": { - "noResultsTitle": "未找到工具", - "noResultsDescription": "请尝试调整搜索条件或筛选条件" - }, "toolMultiFileResult": { "copied": "文件已复制", "copyFailed": "复制失败: {{error}}", @@ -237,9 +233,9 @@ "result": "结果" }, "toolMultipleInput": { + "deleteFile": "删除文件", "inputTitle": "输入 {{type}}", - "noFilesSelected": "未选择任何文件", - "deleteFile": "删除文件" + "noFilesSelected": "未选择任何文件" }, "toolOptions": { "title": "工具选项" @@ -256,6 +252,10 @@ "loading": "正在加载...这可能需要一点时间。", "result": "结果" }, + "toolsByCategory": { + "noResultsDescription": "请尝试调整搜索条件或筛选条件", + "noResultsTitle": "未找到工具" + }, "userTypes": { "developers": "开发人员", "generalUsers": "普通用户" diff --git a/public/locales/zh/video.json b/public/locales/zh/video.json index 615af41e..cbf6b846 100644 --- a/public/locales/zh/video.json +++ b/public/locales/zh/video.json @@ -1,11 +1,8 @@ { "changeSpeed": { - "defaultMultiplier": "默认乘数:2 表示速度快 2 倍", "description": "更改视频文件的播放速度。在保持音频同步的同时,加快或减慢视频速度。支持各种倍速器和常见视频格式。", "inputTitle": "输入视频", - "newVideoSpeed": "新视频速度", "resultTitle": "编辑视频", - "settingSpeed": "设定速度", "shortDescription": "更改视频播放速度", "title": "更改视频速度", "toolInfo": { @@ -54,7 +51,6 @@ }, "flip": { "description": "水平或垂直翻转视频文件。镜像视频以获得特殊效果或纠正方向问题。", - "flippingVideo": "翻转视频", "horizontalLabel": "水平(镜像)", "inputTitle": "输入视频", "orientation": "方向", @@ -73,7 +69,6 @@ "loop": { "description": "通过多次重复播放原始视频来创建循环视频。", "inputTitle": "输入视频", - "loopingVideo": "循环视频", "loops": "循环", "numberOfLoops": "循环次数", "resultTitle": "循环视频", @@ -97,7 +92,6 @@ "description": "将视频文件旋转 90 度、180 度或 270 度。通过精确的旋转控制来校正视频方向或创建特殊效果。", "inputTitle": "输入视频", "resultTitle": "旋转视频", - "rotatingVideo": "旋转视频", "rotation": "旋转", "shortDescription": "按指定角度旋转视频", "title": "旋转视频" @@ -111,10 +105,5 @@ "startTime": "开始时间", "timestamps": "时间戳", "title": "修剪视频" - }, - "videoToGif": { - "description": "将视频文件转换为 GIF 动画格式。提取特定时间范围并创建可共享的动画图像。", - "shortDescription": "将视频转换为动画 GIF", - "title": "视频转GIF" } } diff --git a/src/@types/env.d.ts b/src/@types/env.d.ts new file mode 100644 index 00000000..11311eb7 --- /dev/null +++ b/src/@types/env.d.ts @@ -0,0 +1,2 @@ +declare const __APP_VERSION__: string; +declare const __COMMIT_HASH__: string; diff --git a/src/components/Navbar/index.tsx b/src/components/Navbar/index.tsx index dbacb3aa..45d02f49 100644 --- a/src/components/Navbar/index.tsx +++ b/src/components/Navbar/index.tsx @@ -16,7 +16,8 @@ import { Stack, Select, MenuItem, - FormControl + FormControl, + Typography } from '@mui/material'; import useMediaQuery from '@mui/material/useMediaQuery'; import { useTheme } from '@mui/material/styles'; @@ -178,12 +179,34 @@ const Navbar: React.FC = ({ mx: { md: '50px', lg: '150px' } }} > - - - + + + + + + v{__APP_VERSION__} ( + + {__COMMIT_HASH__} + + ) + + {isMobile ? ( <> ({ - height: '100%', + flex: 1, + minHeight: 0, display: 'flex', flexDirection: 'column', backgroundColor: 'background.paper', @@ -92,6 +93,9 @@ export default function ToolCodeInput({ }, '.decorationsOverviewRuler': { display: 'none !important' + }, + '.codicon': { + fontFamily: 'codicon !important' } })} > @@ -102,6 +106,9 @@ export default function ToolCodeInput({ value={value} onChange={(value) => onChange(value ?? '')} options={{ + automaticLayout: true, + folding: true, + showFoldingControls: 'always', scrollbar: { vertical: 'visible', horizontal: 'visible', diff --git a/src/components/result/ToolCodeResult.tsx b/src/components/result/ToolCodeResult.tsx new file mode 100644 index 00000000..87c04847 --- /dev/null +++ b/src/components/result/ToolCodeResult.tsx @@ -0,0 +1,147 @@ +import { Box, CircularProgress, Typography, useTheme } from '@mui/material'; +import React, { useContext } from 'react'; +import { CustomSnackBarContext } from '../../contexts/CustomSnackBarContext'; +import InputHeader from '../InputHeader'; +import ResultFooter from './ResultFooter'; +import { useTranslation } from 'react-i18next'; +import Editor from '@monaco-editor/react'; +import mime from 'mime'; +import { + globalInputHeight, + codeInputHeightOffset +} from '../../config/uiConfig'; + +export default function ToolCodeResult({ + title = 'Result', + value, + language, + extension = language, + loading +}: { + title?: string; + value: string; + language: string; + extension?: string; + loading?: boolean; +}) { + const { t } = useTranslation(); + const { showSnackBar } = useContext(CustomSnackBarContext); + const theme = useTheme(); + + const handleCopy = () => { + navigator.clipboard + .writeText(value) + .then(() => showSnackBar(t('toolTextResult.copied'), 'success')) + .catch((err) => { + showSnackBar(t('toolTextResult.copyFailed', { error: err }), 'error'); + }); + }; + + const handleDownload = () => { + const filename = `output-omni-tools.${extension}`; + + const mimeType = mime.getType(extension) || 'text/plain'; + + const blob = new Blob([value], { + type: mimeType + }); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + window.URL.revokeObjectURL(url); + }; + + return ( + + + + {loading ? ( + + + + {t('toolTextResult.loading')} + + + ) : ( + ({ + flex: 1, + minHeight: 0, + display: 'flex', + flexDirection: 'column', + backgroundColor: 'background.paper', + '.monaco-editor': { + height: '100% !important', + outline: 'none !important', + '.overflow-guard': { + height: '100% !important', + border: + theme.palette.mode === 'light' + ? '1px solid rgba(0, 0, 0, 0.23)' + : '1px solid rgba(255, 255, 255, 0.23)', + borderRadius: 1, + transition: theme.transitions.create( + ['border-color', 'background-color'], + { + duration: theme.transitions.duration.shorter + } + ) + }, + '&:hover .overflow-guard': { + borderColor: theme.palette.text.primary + } + }, + '.decorationsOverviewRuler': { + display: 'none !important' + }, + '.codicon': { + fontFamily: 'codicon !important' + } + })} + > + + + )} + + + + ); +} diff --git a/src/lib/ffmpeg.ts b/src/lib/ffmpeg.ts new file mode 100644 index 00000000..5957e708 --- /dev/null +++ b/src/lib/ffmpeg.ts @@ -0,0 +1,97 @@ +import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { toBlobURL } from '@ffmpeg/util'; + +const CORE_VERSION = '0.12.6'; +const BASE_URL = `https://unpkg.com/@ffmpeg/core@${CORE_VERSION}/dist/esm`; + +let ffmpegInstance: FFmpeg | null = null; +let loadingPromise: Promise | null = null; + +type FFmpegTaskContext = { + ffmpeg: FFmpeg; + tempFile: (extension: string) => string; +}; + +async function getFFmpeg(): Promise { + if (ffmpegInstance?.loaded) { + return ffmpegInstance; + } + + if (!loadingPromise) { + loadingPromise = (async () => { + const ffmpeg = new FFmpeg(); + + await ffmpeg.load({ + coreURL: await toBlobURL( + `${BASE_URL}/ffmpeg-core.js`, + 'text/javascript' + ), + wasmURL: await toBlobURL( + `${BASE_URL}/ffmpeg-core.wasm`, + 'application/wasm' + ) + }); + + ffmpegInstance = ffmpeg; + + return ffmpeg; + })(); + } + + try { + return await loadingPromise; + } finally { + loadingPromise = null; + } +} + +/** + * Destroy the current FFmpeg instance. + * + * Normally not needed because the instance is reused. + * Use only after worker crashes or when explicitly freeing memory. + */ +export function resetFFmpeg(): void { + ffmpegInstance?.terminate(); + + ffmpegInstance = null; + loadingPromise = null; +} + +// FFmpeg worker is not safe for concurrent operations. +let taskQueue: Promise = Promise.resolve(); + +export async function runFFmpegTask( + task: (context: FFmpegTaskContext) => Promise +): Promise { + const ffmpeg = await getFFmpeg(); + + const run = taskQueue + .catch(() => {}) + .then(async () => { + const tempFiles = new Set(); + + const tempFile = (extension: string) => { + const filename = `${crypto.randomUUID()}${extension}`; + + tempFiles.add(filename); + + return filename; + }; + + try { + return await task({ + ffmpeg, + tempFile + }); + } finally { + await Promise.all( + [...tempFiles].map((file) => ffmpeg.deleteFile(file).catch(() => {})) + ); + } + }); + + taskQueue = run.catch(() => {}); + + return run; +} diff --git a/src/pages/tools/audio/change-speed/change-speed.service.test.ts b/src/pages/tools/audio/change-speed/change-speed.service.test.ts deleted file mode 100644 index 0ebd4637..00000000 --- a/src/pages/tools/audio/change-speed/change-speed.service.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { changeAudioSpeed } from './service'; -import { InitialValuesType } from './types'; - -describe('changeAudioSpeed', () => { - it('should return a new File with the correct name and type', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.mp3', { - type: 'audio/mp3' - }); - const options: InitialValuesType = { - newSpeed: 2, - outputFormat: 'mp3' - }; - const result = await changeAudioSpeed(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result?.name).toBe('test-2x.mp3'); - expect(result?.type).toBe('audio/mp3'); - }); - - it('should return null if input is null', async () => { - const options: InitialValuesType = { - newSpeed: 2, - outputFormat: 'mp3' - }; - const result = await changeAudioSpeed(null, options); - expect(result).toBeNull(); - }); -}); diff --git a/src/pages/tools/audio/change-speed/index.tsx b/src/pages/tools/audio/change-speed/index.tsx index bb556b38..27cb10c8 100644 --- a/src/pages/tools/audio/change-speed/index.tsx +++ b/src/pages/tools/audio/change-speed/index.tsx @@ -7,12 +7,11 @@ import { InitialValuesType } from './types'; import ToolAudioInput from '@components/input/ToolAudioInput'; import ToolFileResult from '@components/result/ToolFileResult'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import RadioWithTextField from '@components/options/RadioWithTextField'; import { changeAudioSpeed } from './service'; import { useTranslation } from 'react-i18next'; const initialValues: InitialValuesType = { - newSpeed: 2, + speed: 2, outputFormat: 'mp3' }; @@ -22,10 +21,7 @@ const formatOptions = [ { label: 'WAV', value: 'wav' } ]; -export default function ChangeSpeed({ - title, - longDescription -}: ToolComponentProps) { +export default function ChangeSpeed({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -35,10 +31,12 @@ export default function ChangeSpeed({ optionsValues: InitialValuesType, input: File | null ) => { + if (!input) return; + setLoading(true); try { - const newFile = await changeAudioSpeed(input, optionsValues); - setResult(newFile); + const resultFile = await changeAudioSpeed(input, optionsValues); + setResult(resultFile); } catch (err) { setResult(null); } finally { @@ -55,9 +53,10 @@ export default function ChangeSpeed({ component: ( updateField('newSpeed', Number(val))} + value={values.speed.toString()} + onOwnChange={(val) => updateField('speed', Number(val))} description={t('changeSpeed.speedDescription')} + inputProps={{ min: 0 }} type="number" /> @@ -102,28 +101,17 @@ export default function ChangeSpeed({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} compute={compute} - toolInfo={{ - title: t('changeSpeed.toolInfo.title', { title }), - description: longDescription - }} /> ); } diff --git a/src/pages/tools/audio/change-speed/service.ts b/src/pages/tools/audio/change-speed/service.ts index c6638571..2a14f71c 100644 --- a/src/pages/tools/audio/change-speed/service.ts +++ b/src/pages/tools/audio/change-speed/service.ts @@ -1,6 +1,7 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; function computeAudioFilter(speed: number): string { if (speed <= 2 && speed >= 0.5) { @@ -21,27 +22,19 @@ function computeAudioFilter(speed: number): string { } export async function changeAudioSpeed( - input: File | null, + input: File, options: InitialValuesType -): Promise { - if (!input) return null; - const { newSpeed, outputFormat } = options; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; - try { - ffmpeg = new FFmpeg(); - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - const fileName = input.name; - const outputName = `output.${outputFormat}`; +): Promise { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { speed, outputFormat } = options; + + const fileName = tempFile(`.${getFileExtension(input.name)}`); + const outputName = tempFile(`.${outputFormat}`); + await ffmpeg.writeFile(fileName, await fetchFile(input)); - const audioFilter = computeAudioFilter(newSpeed); + const audioFilter = computeAudioFilter(speed); const args = ['-i', fileName, '-filter:a', audioFilter]; + if (outputFormat === 'mp3') { args.push('-b:a', '192k', '-f', 'mp3', outputName); } else if (outputFormat === 'aac') { @@ -61,20 +54,19 @@ export async function changeAudioSpeed( } await ffmpeg.exec(args); const data = await ffmpeg.readFile(outputName); + let mimeType = 'audio/mp3'; if (outputFormat === 'aac') mimeType = 'audio/aac'; if (outputFormat === 'wav') mimeType = 'audio/wav'; - const blob = new Blob([data as any], { type: mimeType }); - const newFile = new File( + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: mimeType + }); + + return new File( [blob], - fileName.replace(/\.[^/.]+$/, `-${newSpeed}x.${outputFormat}`), + fileName.replace(/\.[^/.]+$/, `-${speed}x.${outputFormat}`), { type: mimeType } ); - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - return newFile; - } catch (err) { - console.error(`Failed to process audio: ${err}`); - return null; - } + }); } diff --git a/src/pages/tools/audio/change-speed/types.ts b/src/pages/tools/audio/change-speed/types.ts index 587fc4fb..150e8de0 100644 --- a/src/pages/tools/audio/change-speed/types.ts +++ b/src/pages/tools/audio/change-speed/types.ts @@ -1,4 +1,4 @@ export type InitialValuesType = { - newSpeed: number; + speed: number; outputFormat: 'mp3' | 'aac' | 'wav'; }; diff --git a/src/pages/tools/audio/extract-audio/index.tsx b/src/pages/tools/audio/extract-audio/index.tsx index e54e2901..5da78ab4 100644 --- a/src/pages/tools/audio/extract-audio/index.tsx +++ b/src/pages/tools/audio/extract-audio/index.tsx @@ -9,15 +9,13 @@ import { GetGroupsType } from '@components/options/ToolOptions'; import ToolFileResult from '@components/result/ToolFileResult'; import SelectWithDesc from '@components/options/SelectWithDesc'; import { useTranslation } from 'react-i18next'; +import { getFileExtension } from '@utils/file'; const initialValues: InitialValuesType = { outputFormat: 'aac' }; -export default function ExtractAudio({ - title, - longDescription -}: ToolComponentProps) { +export default function ExtractAudio({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [file, setFile] = useState(null); const [audioFile, setAudioFile] = useState(null); @@ -35,7 +33,7 @@ export default function ExtractAudio({ { - updateField('outputFormat', value.toString()); + updateField('outputFormat', value); }} options={[ { label: 'AAC', value: 'aac' }, @@ -75,25 +73,19 @@ export default function ExtractAudio({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} compute={compute} toolInfo={{ title: t('extractAudio.toolInfo.title', { title }), - description: longDescription + description: t('extractAudio.toolInfo.description') }} setInput={setFile} /> diff --git a/src/pages/tools/audio/extract-audio/service.ts b/src/pages/tools/audio/extract-audio/service.ts index 644c70a9..f1c054d4 100644 --- a/src/pages/tools/audio/extract-audio/service.ts +++ b/src/pages/tools/audio/extract-audio/service.ts @@ -1,70 +1,62 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function extractAudioFromVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { outputFormat } = options; + + const inputName = tempFile('.mp4'); + const outputName = tempFile(`.${outputFormat}`); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args: string[] = ['-i', inputName, '-vn']; + + if (outputFormat === 'mp3') { + args.push( + '-ar', + '44100', + '-ac', + '2', + '-b:a', + '192k', + '-f', + 'mp3', + outputName + ); + } else if (outputFormat === 'wav') { + args.push( + '-acodec', + 'pcm_s16le', + '-ar', + '44100', + '-ac', + '2', + '-f', + 'wav', + outputName + ); + } else { + // Default to AAC or copy + args.push('-acodec', 'copy', outputName); + } + + await ffmpeg.exec(args); + + const extractedAudio = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(extractedAudio as Uint8Array)], { + type: `audio/${outputFormat}` }); - } - const inputName = 'input.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const configuredOutputAudioFormat = options.outputFormat; - const outputName = `output.${configuredOutputAudioFormat}`; - const args: string[] = ['-i', inputName, '-vn']; - - if (configuredOutputAudioFormat === 'mp3') { - args.push( - '-ar', - '44100', - '-ac', - '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_audio.${outputFormat}`, + { type: `audio/${outputFormat}` } ); - } else if (configuredOutputAudioFormat === 'wav') { - args.push( - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - '-f', - 'wav', - outputName - ); - } else { - // Default to AAC or copy - args.push('-acodec', 'copy', outputName); - } - - await ffmpeg.exec(args); - - const extractedAudio = await ffmpeg.readFile(outputName); - - return new File( - [ - new Blob([extractedAudio as any], { - type: `audio/${configuredOutputAudioFormat}` - }) - ], - `${input.name.replace( - /\.[^/.]+$/, - '' - )}_audio.${configuredOutputAudioFormat}`, - { type: `audio/${configuredOutputAudioFormat}` } - ); + }); } diff --git a/src/pages/tools/audio/extract-audio/types.ts b/src/pages/tools/audio/extract-audio/types.ts index d6d4f360..4077a45a 100644 --- a/src/pages/tools/audio/extract-audio/types.ts +++ b/src/pages/tools/audio/extract-audio/types.ts @@ -1,3 +1,5 @@ +type AudioFormat = 'aac' | 'mp3' | 'wav'; + export type InitialValuesType = { - outputFormat: string; + outputFormat: AudioFormat; }; diff --git a/src/pages/tools/audio/merge-audio/index.tsx b/src/pages/tools/audio/merge-audio/index.tsx index 02ab2b87..a201416a 100644 --- a/src/pages/tools/audio/merge-audio/index.tsx +++ b/src/pages/tools/audio/merge-audio/index.tsx @@ -34,7 +34,7 @@ export default function MergeAudio({ optionsValues: InitialValuesType, input: MultiAudioInput[] ) => { - if (input.length === 0) return; + if (input.length < 2) return; setLoading(true); try { const files = input.map((item) => item.file); @@ -94,19 +94,12 @@ export default function MergeAudio({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts b/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts deleted file mode 100644 index 6bdaaabb..00000000 --- a/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { mergeAudioFiles } from './service'; - -describe('mergeAudioFiles', () => { - it('should merge multiple audio files', async () => { - // Create mock audio files - const mockAudioData1 = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockAudioData2 = new Uint8Array([6, 7, 8, 9, 10, 11]); - - const mockFile1 = new File([mockAudioData1], 'test1.mp3', { - type: 'audio/mp3' - }); - const mockFile2 = new File([mockAudioData2], 'test2.mp3', { - type: 'audio/mp3' - }); - - const options = { - outputFormat: 'mp3' as const - }; - - const result = await mergeAudioFiles([mockFile1, mockFile2], options); - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('merged_audio.mp3'); - expect(result.type).toBe('audio/mp3'); - }); - - it('should handle different output formats', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.wav', { - type: 'audio/wav' - }); - - const options = { - outputFormat: 'aac' as const - }; - - const result = await mergeAudioFiles([mockFile], options); - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('merged_audio.aac'); - expect(result.type).toBe('audio/aac'); - }); - - it('should throw error when no input files provided', async () => { - const options = { - outputFormat: 'mp3' as const - }; - - try { - await mergeAudioFiles([], options); - expect.fail('Should have thrown an error'); - } catch (error) { - expect(error).toBeInstanceOf(Error); - expect((error as Error).message).toBe('No input files provided'); - } - }); -}); diff --git a/src/pages/tools/audio/merge-audio/service.ts b/src/pages/tools/audio/merge-audio/service.ts index 679ac6aa..e4ee8d8c 100644 --- a/src/pages/tools/audio/merge-audio/service.ts +++ b/src/pages/tools/audio/merge-audio/service.ts @@ -1,115 +1,93 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function mergeAudioFiles( inputs: File[], options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { outputFormat } = options; - if (inputs.length === 0) { - throw new Error('No input files provided'); - } + const tempWavNames: string[] = []; + const fileListName = tempFile('.txt'); + const concatWavName = tempFile('.wav'); + const outputName = tempFile(`.${outputFormat}`); - const { outputFormat } = options; - const outputName = `output.${outputFormat}`; + for (let i = 0; i < inputs.length; i++) { + const inputName = tempFile( + `.${inputs[i].name.split('.').pop() ?? 'tmp'}` + ); + const tempWavName = tempFile('.wav'); - // 1. Convert all inputs to WAV - const tempWavNames: string[] = []; - for (let i = 0; i < inputs.length; i++) { - const inputName = `input${i}`; - const tempWavName = `temp${i}.wav`; - await ffmpeg.writeFile(inputName, await fetchFile(inputs[i])); - await ffmpeg.exec([ - '-i', - inputName, - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - tempWavName - ]); - tempWavNames.push(tempWavName); - await ffmpeg.deleteFile(inputName); - } + await ffmpeg.writeFile(inputName, await fetchFile(inputs[i])); - // 2. Create file list for concat - const fileListName = 'filelist.txt'; - const fileListContent = tempWavNames - .map((name) => `file '${name}'`) - .join('\n'); - await ffmpeg.writeFile(fileListName, fileListContent); - - // 3. Concatenate WAV files - const concatWav = 'concat.wav'; - await ffmpeg.exec([ - '-f', - 'concat', - '-safe', - '0', - '-i', - fileListName, - '-c', - 'copy', - concatWav - ]); - - // 4. Convert concatenated WAV to requested output format - let finalOutput = concatWav; - if (outputFormat !== 'wav') { - const args = ['-i', concatWav]; - if (outputFormat === 'mp3') { - args.push( + await ffmpeg.exec([ + '-i', + inputName, + '-acodec', + 'pcm_s16le', '-ar', '44100', '-ac', '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName - ); - } else if (outputFormat === 'aac') { - args.push('-c:a', 'aac', '-b:a', '192k', '-f', 'adts', outputName); + tempWavName + ]); + + tempWavNames.push(tempWavName); } - await ffmpeg.exec(args); - finalOutput = outputName; - } - const mergedAudio = await ffmpeg.readFile(finalOutput); + // Build concat file list + const fileListContent = tempWavNames + .map((name) => `file '${name}'`) + .join('\n'); - let mimeType = 'audio/wav'; - if (outputFormat === 'mp3') mimeType = 'audio/mp3'; - if (outputFormat === 'aac') mimeType = 'audio/aac'; + await ffmpeg.writeFile(fileListName, fileListContent); - // Clean up files - for (const tempWavName of tempWavNames) { - await ffmpeg.deleteFile(tempWavName); - } - await ffmpeg.deleteFile(fileListName); - await ffmpeg.deleteFile(concatWav); - if (outputFormat !== 'wav') { - await ffmpeg.deleteFile(outputName); - } + // Concatenate WAV files + await ffmpeg.exec([ + '-f', + 'concat', + '-safe', + '0', + '-i', + fileListName, + '-c', + 'copy', + concatWavName + ]); - return new File( - [ - new Blob([mergedAudio as any], { - type: mimeType - }) - ], - `merged_audio.${outputFormat}`, - { type: mimeType } - ); + let finalOutput = concatWavName; + + if (outputFormat !== 'wav') { + const args = ['-i', concatWavName]; + + switch (outputFormat) { + case 'mp3': + args.push('-b:a', '192k', '-f', 'mp3', outputName); + break; + + case 'aac': + args.push('-c:a', 'aac', '-b:a', '192k', '-f', 'adts', outputName); + break; + } + + await ffmpeg.exec(args); + finalOutput = outputName; + } + + const data = await ffmpeg.readFile(finalOutput); + + return new File( + [ + new Blob([new Uint8Array(data as Uint8Array)], { + type: `audio/${outputFormat}` + }) + ], + `merged_audio.${outputFormat}`, + { + type: `audio/${outputFormat}` + } + ); + }); } diff --git a/src/pages/tools/audio/trim/index.tsx b/src/pages/tools/audio/trim/index.tsx index 1a3efe73..622d21ea 100644 --- a/src/pages/tools/audio/trim/index.tsx +++ b/src/pages/tools/audio/trim/index.tsx @@ -9,6 +9,7 @@ import ToolAudioInput from '@components/input/ToolAudioInput'; import ToolFileResult from '@components/result/ToolFileResult'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { trimAudio } from './service'; +import { getFileExtension } from '@utils/file'; const initialValues: InitialValuesType = { startTime: '00:00:00', @@ -22,7 +23,7 @@ const formatOptions = [ { label: 'WAV', value: 'wav' } ]; -export default function Trim({ title, longDescription }: ToolComponentProps) { +export default function Trim({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -110,19 +111,12 @@ export default function Trim({ title, longDescription }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} @@ -130,7 +124,7 @@ export default function Trim({ title, longDescription }: ToolComponentProps) { compute={compute} toolInfo={{ title: t('trim.toolInfo.title', { title }), - description: longDescription + description: t('trim.toolInfo.longDescription') }} /> ); diff --git a/src/pages/tools/audio/trim/service.ts b/src/pages/tools/audio/trim/service.ts index 26b0a66f..de9004cc 100644 --- a/src/pages/tools/audio/trim/service.ts +++ b/src/pages/tools/audio/trim/service.ts @@ -1,108 +1,97 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function trimAudio( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { startTime, endTime, outputFormat } = options; + const inputName = tempFile(getFileExtension(input.name)); + const outputName = tempFile(`.${outputFormat}`); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + let args: string[] = [ + '-i', + inputName, + '-ss', + startTime, // Start time + '-to', + endTime, // End time + '-c', + 'copy' + ]; + + // Add format-specific arguments + if (outputFormat === 'mp3') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-ar', + '44100', + '-ac', + '2', + '-b:a', + '192k', + '-f', + 'mp3', + outputName + ]; + } else if (outputFormat === 'aac') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-c:a', + 'aac', + '-b:a', + '192k', + '-f', + 'adts', + outputName + ]; + } else if (outputFormat === 'wav') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-acodec', + 'pcm_s16le', + '-ar', + '44100', + '-ac', + '2', + '-f', + 'wav', + outputName + ]; + } + + await ffmpeg.exec(args); + + const trimmedAudio = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(trimmedAudio as Uint8Array)], { + type: `audio/${outputFormat}` }); - } - const inputName = 'input.mp3'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const { startTime, endTime, outputFormat } = options; - const outputName = `output.${outputFormat}`; - - // Build FFmpeg arguments for trimming - let args: string[] = [ - '-i', - inputName, - '-ss', - startTime, // Start time - '-to', - endTime, // End time - '-c', - 'copy' // Copy without re-encoding for speed - ]; - - // Add format-specific arguments - if (outputFormat === 'mp3') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-ar', - '44100', - '-ac', - '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName - ]; - } else if (outputFormat === 'aac') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-c:a', - 'aac', - '-b:a', - '192k', - '-f', - 'adts', - outputName - ]; - } else if (outputFormat === 'wav') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - '-f', - 'wav', - outputName - ]; - } - - await ffmpeg.exec(args); - - const trimmedAudio = await ffmpeg.readFile(outputName); - - let mimeType = 'audio/mp3'; - if (outputFormat === 'aac') mimeType = 'audio/aac'; - if (outputFormat === 'wav') mimeType = 'audio/wav'; - - return new File( - [ - new Blob([trimmedAudio as any], { - type: mimeType - }) - ], - `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.${outputFormat}`, - { type: mimeType } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.${outputFormat}`, + { type: `audio/${outputFormat}` } + ); + }); } diff --git a/src/pages/tools/audio/trim/trim.service.test.ts b/src/pages/tools/audio/trim/trim.service.test.ts deleted file mode 100644 index 5d9faa5c..00000000 --- a/src/pages/tools/audio/trim/trim.service.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { trimAudio } from './service'; - -describe('trimAudio', () => { - it('should trim audio file with valid time parameters', async () => { - // Create a mock audio file - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.mp3', { - type: 'audio/mp3' - }); - - const options = { - startTime: '00:00:10', - endTime: '00:00:20', - outputFormat: 'mp3' as const - }; - - const result = await trimAudio(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result.name).toContain('_trimmed.mp3'); - expect(result.type).toBe('audio/mp3'); - }); - - it('should handle different output formats', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.wav', { - type: 'audio/wav' - }); - - const options = { - startTime: '00:00:00', - endTime: '00:00:30', - outputFormat: 'wav' as const - }; - - const result = await trimAudio(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result.name).toContain('_trimmed.wav'); - expect(result.type).toBe('audio/wav'); - }); -}); diff --git a/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts b/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts deleted file mode 100644 index 9c232995..00000000 --- a/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { expect, describe, it, vi, beforeEach } from 'vitest'; -import { convertAudio } from './service'; -import { InitialValuesType } from './types'; - -// Mock FFmpeg since it doesn't support Node.js in tests -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([10, 20, 30, 40, 50])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([10, 20, 30, 40, 50])) -})); - -describe('convertAudio', () => { - let mockInputFile: File; - - beforeEach(() => { - const mockAudioData = new Uint8Array([1, 2, 3, 4, 5]); - mockInputFile = new File([mockAudioData], 'input.aac', { - type: 'audio/aac' - }); - }); - - it('should convert to MP3 format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'mp3' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.mp3'); - expect(result.type).toBe('audio/mpeg'); - }); - - it('should convert to AAC format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'aac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.aac'); - expect(result.type).toBe('audio/aac'); - }); - - it('should convert to WAV format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'wav' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.wav'); - expect(result.type).toBe('audio/wav'); - }); - - it('should convert to FLAC format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'flac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.flac'); - expect(result.type).toBe('audio/flac'); - }); - - it('should convert to OGG format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'ogg' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.ogg'); - expect(result.type).toBe('audio/ogg'); - }); - - it('should return original file if input format matches output format', async () => { - const options: InitialValuesType = { outputFormat: 'aac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBe(mockInputFile); // Same instance - expect(result.name).toBe('input.aac'); - }); - - it('should handle files without extensions', async () => { - const fileNoExt = new File([new Uint8Array([1, 2, 3])], 'audiofile', { - type: 'audio/aac' - }); - const options: InitialValuesType = { outputFormat: 'mp3' }; - const result = await convertAudio(fileNoExt, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('audiofile.mp3'); - expect(result.type).toBe('audio/mpeg'); - }); -}); diff --git a/src/pages/tools/converters/audio-converter/service.ts b/src/pages/tools/converters/audio-converter/service.ts index dc243e35..33f742e0 100644 --- a/src/pages/tools/converters/audio-converter/service.ts +++ b/src/pages/tools/converters/audio-converter/service.ts @@ -1,82 +1,50 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { InitialValuesType, AUDIO_FORMATS } from './types'; import { getFileExtension } from 'utils/file'; /** - * optimzed call for FFmpeg instance creation, - * avoiding to download required FFmpeg binaries on every reload - */ -const ffmpeg = new FFmpeg(); -let isLoaded = false; - -async function loadFFmpeg() { - if (!isLoaded) { - await ffmpeg.load(); - isLoaded = true; - } -} - -/** - * Converts input audio file to selected output format ('mp3', 'aac', or 'wav'). - * Supports any input audio file type accepted by FFmpeg. + * Converts input audio file to selected output format. * * @param input - Source audio File - * @param outputFormat - 'mp3' | 'aac' | 'wav' + * @param options - Conversion options * @returns Converted audio File */ export async function convertAudio( input: File, options: InitialValuesType ): Promise { - await loadFFmpeg(); - - // Use the original input extension for input filename const inputExt = getFileExtension(input.name); - if (inputExt === options.outputFormat) return input; + if (inputExt === options.outputFormat) { + return input; + } - const inputFileName = inputExt ? `input.${inputExt}` : 'input'; - const outputFileName = `output.${options.outputFormat}`; + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputFileName = tempFile(inputExt ? `.${inputExt}` : ''); - // Write the input file to FFmpeg FS - await ffmpeg.writeFile(inputFileName, await fetchFile(input)); + const outputFileName = tempFile(`.${options.outputFormat}`); - // Build the FFmpeg args depending on the output format - // You can customize the codec and bitrate options per format here + await ffmpeg.writeFile(inputFileName, await fetchFile(input)); - const format = AUDIO_FORMATS[options.outputFormat]; - const { codec, bitrate, mimeType } = format; + const { codec, bitrate, mimeType } = AUDIO_FORMATS[options.outputFormat]; - const args = bitrate - ? ['-i', inputFileName, '-c:a', codec, '-b:a', bitrate, outputFileName] - : ['-i', inputFileName, '-c:a', codec, outputFileName]; + const args = bitrate + ? ['-i', inputFileName, '-c:a', codec, '-b:a', bitrate, outputFileName] + : ['-i', inputFileName, '-c:a', codec, outputFileName]; - // Execute ffmpeg with arguments - try { await ffmpeg.exec(args); - // Read the output file from FFmpeg FS const data = await ffmpeg.readFile(outputFileName); - // Create a new File with the original name but new extension - const baseName = input.name.replace(/\.[^.]+$/, ''); - const convertedFileName = `${baseName}.${options.outputFormat}`; + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: mimeType + }); - return new File( - [new Blob([data as any], { type: mimeType })], - convertedFileName, - { - type: mimeType - } - ); - } finally { - // Clean up FFmpeg virtual filesystem - try { - await ffmpeg.deleteFile(inputFileName); - await ffmpeg.deleteFile(outputFileName); - } catch (e) { - // Ignore cleanup errors - } - } + const baseName = input.name.replace(/\.[^.]+$/, ''); + + return new File([blob], `${baseName}.${options.outputFormat}`, { + type: mimeType + }); + }); } diff --git a/src/pages/tools/converters/index.ts b/src/pages/tools/converters/index.ts index ffc9a721..a98b5b52 100644 --- a/src/pages/tools/converters/index.ts +++ b/src/pages/tools/converters/index.ts @@ -1,9 +1,11 @@ import { tool as convertersAudioConverter } from './audio-converter/meta'; import { tool as convertersWebpConverter } from './convert-to-webp/meta'; import { tool as convertersJpgConverter } from './convert-to-jpg/meta'; +import { tool as convertersGifConverter } from './video-to-gif/meta'; export const convertersTools = [ convertersAudioConverter, convertersWebpConverter, - convertersJpgConverter + convertersJpgConverter, + convertersGifConverter ]; diff --git a/src/pages/tools/converters/video-to-gif/index.tsx b/src/pages/tools/converters/video-to-gif/index.tsx new file mode 100644 index 00000000..9ed7fccf --- /dev/null +++ b/src/pages/tools/converters/video-to-gif/index.tsx @@ -0,0 +1,121 @@ +import { Box } from '@mui/material'; +import React, { useState, useCallback } from 'react'; +import ToolContent from '@components/ToolContent'; +import { ToolComponentProps } from '@tools/defineTool'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; +import { updateNumberField } from '@utils/string'; +import { InitialValuesType, GIF_PRESETS, Quality } from './types'; +import ToolVideoInput from '@components/input/ToolVideoInput'; +import ToolFileResult from '@components/result/ToolFileResult'; +import SimpleRadio from '@components/options/SimpleRadio'; +import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; +import { videoToGif } from './service'; + +const initialValues: InitialValuesType = { + quality: 'mid', + start: 0, + end: 100 +}; + +export default function VideoToGif({ title }: ToolComponentProps) { + const { t } = useTranslation('converters'); + const [input, setInput] = useState(null); + const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); + + const compute = async (values: InitialValuesType, input: File | null) => { + if (!input) return; + setLoading(true); + + try { + const resultFile = await videoToGif(input, values); + setResult(resultFile); + } catch (error) { + console.error('Error converting video to gif:', error); + } finally { + setLoading(false); + } + }; + + const debouncedCompute = useCallback(debounce(compute, 1000), []); + + const getGroups: GetGroupsType | null = ({ + values, + updateField + }) => [ + { + title: t('videoToGif.options.quality'), + component: ( + + {(Object.keys(GIF_PRESETS) as Quality[]).map((quality) => ( + updateField('quality', quality)} + /> + ))} + + ) + }, + { + title: t('videoToGif.options.timestamps'), + component: ( + + + updateNumberField(value, 'start', updateField) + } + value={values.start} + label={t('videoToGif.options.startTime')} + sx={{ mb: 2, backgroundColor: 'background.paper' }} + /> + + updateNumberField(value, 'end', updateField) + } + value={values.end} + label={t('videoToGif.options.endTime')} + /> + + ) + } + ]; + + return ( + { + return ( + { + setFieldValue('start', start); + setFieldValue('end', end); + }} + trimStart={start} + trimEnd={end} + /> + ); + }} + resultComponent={ + + } + initialValues={initialValues} + getGroups={getGroups} + setInput={setInput} + compute={debouncedCompute} + /> + ); +} diff --git a/src/pages/tools/video/video-to-gif/meta.ts b/src/pages/tools/converters/video-to-gif/meta.ts similarity index 58% rename from src/pages/tools/video/video-to-gif/meta.ts rename to src/pages/tools/converters/video-to-gif/meta.ts index b3236866..2e3aaf27 100644 --- a/src/pages/tools/video/video-to-gif/meta.ts +++ b/src/pages/tools/converters/video-to-gif/meta.ts @@ -1,15 +1,15 @@ import { defineTool } from '@tools/defineTool'; import { lazy } from 'react'; -export const tool = defineTool('video', { +export const tool = defineTool('converters', { path: 'video-to-gif', icon: 'material-symbols:gif', keywords: ['video', 'gif', 'convert', 'animated', 'image'], component: lazy(() => import('./index')), i18n: { - name: 'video:videoToGif.title', - description: 'video:videoToGif.description', - shortDescription: 'video:videoToGif.shortDescription', + name: 'converters:videoToGif.title', + description: 'converters:videoToGif.description', + shortDescription: 'converters:videoToGif.shortDescription', userTypes: ['generalUsers'] } }); diff --git a/src/pages/tools/converters/video-to-gif/service.ts b/src/pages/tools/converters/video-to-gif/service.ts new file mode 100644 index 00000000..6af26f02 --- /dev/null +++ b/src/pages/tools/converters/video-to-gif/service.ts @@ -0,0 +1,55 @@ +import { runFFmpegTask } from 'lib/ffmpeg'; +import { fetchFile } from '@ffmpeg/util'; +import { GIF_PRESETS, InitialValuesType } from './types'; + +export const videoToGif = async ( + input: File, + options: InitialValuesType +): Promise => { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const fileName = tempFile('.mp4'); + const outputName = tempFile('.gif'); + const paletteName = tempFile('.png'); + + const { start, end, quality } = options; + + const { fps, scale } = GIF_PRESETS[quality]; + + await ffmpeg.writeFile(fileName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + fileName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-vf', + `fps=${fps},scale=${scale},palettegen`, + paletteName + ]); + + await ffmpeg.exec([ + '-i', + fileName, + '-i', + paletteName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-filter_complex', + `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'image/gif' + }); + return new File([blob], `${input.name.replace(/\.[^/.]+$/, '')}.gif`, { + type: 'image/gif' + }); + }); +}; diff --git a/src/pages/tools/converters/video-to-gif/types.ts b/src/pages/tools/converters/video-to-gif/types.ts new file mode 100644 index 00000000..317d0585 --- /dev/null +++ b/src/pages/tools/converters/video-to-gif/types.ts @@ -0,0 +1,32 @@ +export type Quality = 'low' | 'mid' | 'high' | 'ultra'; + +export type InitialValuesType = { + quality: Quality; + start: number; + end: number; +}; + +export const GIF_PRESETS: Record< + Quality, + { + fps: string; + scale: string; + } +> = { + low: { + fps: '5', + scale: '240:-1:flags=bilinear' + }, + mid: { + fps: '10', + scale: '320:-1:flags=bicubic' + }, + high: { + fps: '15', + scale: '480:-1:flags=lanczos' + }, + ultra: { + fps: '15', + scale: '640:-1:flags=lanczos' + } +}; diff --git a/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts b/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts new file mode 100644 index 00000000..cea67ca5 --- /dev/null +++ b/src/pages/tools/csv/csv-to-xml/csv-to-xml.service.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect } from 'vitest'; +import { convertCsvToXml } from './service'; + +const defaultOptions = { + delimiter: ',', + quote: '"', + comment: '#', + useHeaders: true, + skipEmptyLines: true +}; + +describe('convertCsvToXml', () => { + it('should convert basic CSV to XML with headers', () => { + const result = convertCsvToXml( + 'name,age\nJohn,30\nAlice,25', + defaultOptions + ); + expect(result).toContain('John'); + expect(result).toContain('Alice'); + expect(result).toContain('30'); + expect(result).toContain('25'); + }); + + it('should escape ampersands in cell values', () => { + const result = convertCsvToXml('name\nA&B', defaultOptions); + expect(result).toContain('A&B'); + expect(result).not.toContain('A&B'); + }); + + it('should escape less-than and greater-than in cell values', () => { + const result = convertCsvToXml('name\n', defaultOptions); + expect(result).toContain('<tag>'); + }); + + it('should escape double quotes in cell values', () => { + const result = convertCsvToXml('name\nsay "hello"', defaultOptions); + expect(result).toContain('"'); + }); + + it('should handle normal data without corruption', () => { + const result = convertCsvToXml( + 'name,age,city\nJohn,30,New York', + defaultOptions + ); + expect(result).toContain('John'); + expect(result).toContain('30'); + expect(result).toContain('New York'); + }); + + it('should sanitize header names containing spaces', () => { + const result = convertCsvToXml( + 'first name,last name\nJohn,Doe', + defaultOptions + ); + expect(result).toContain('John'); + expect(result).toContain('Doe'); + }); + + it('should handle empty cell values', () => { + const result = convertCsvToXml('name,age,city\nJohn,,', defaultOptions); + expect(result).toContain('John'); + expect(result).toContain(''); + expect(result).toContain(''); + }); + + it('should return empty root element for empty input', () => { + const result = convertCsvToXml('', defaultOptions); + expect(result).toBe( + '\n' + ); + }); + + it('should include XML declaration', () => { + const result = convertCsvToXml('name\nJohn', defaultOptions); + expect(result).toContain(''); + }); + + it('should escape all five XML special characters', () => { + const result = convertCsvToXml('name\n& < > " \'', defaultOptions); + expect(result).toContain('&'); + expect(result).toContain('<'); + expect(result).toContain('>'); + expect(result).toContain('"'); + expect(result).toContain('''); + }); +}); diff --git a/src/pages/tools/csv/csv-to-xml/index.tsx b/src/pages/tools/csv/csv-to-xml/index.tsx index 1178a81f..892e0420 100644 --- a/src/pages/tools/csv/csv-to-xml/index.tsx +++ b/src/pages/tools/csv/csv-to-xml/index.tsx @@ -8,14 +8,7 @@ import { ToolComponentProps } from '@tools/defineTool'; import { Box } from '@mui/material'; import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; - -type InitialValuesType = { - delimiter: string; - quote: string; - comment: string; - useHeaders: boolean; - skipEmptyLines: boolean; -}; +import { InitialValuesType } from './types'; const initialValues: InitialValuesType = { delimiter: ',', diff --git a/src/pages/tools/csv/csv-to-xml/service.ts b/src/pages/tools/csv/csv-to-xml/service.ts index da171cae..3f9f6b8f 100644 --- a/src/pages/tools/csv/csv-to-xml/service.ts +++ b/src/pages/tools/csv/csv-to-xml/service.ts @@ -1,14 +1,10 @@ -type CsvToXmlOptions = { - delimiter: string; - quote: string; - comment: string; - useHeaders: boolean; - skipEmptyLines: boolean; -}; +import { InitialValuesType } from './types'; +import { escapeMarkup } from '@utils/string'; +import { normalizeXmlTagName } from '@utils/xml'; export const convertCsvToXml = ( csv: string, - options: CsvToXmlOptions + options: InitialValuesType ): string => { const lines = csv.split('\n').map((line) => line.trim()); @@ -27,15 +23,23 @@ export const convertCsvToXml = ( } if (options.useHeaders) { - headers = parseCsvLine(validLines[0], options); + headers = parseCsvLine(validLines[0], options).map(normalizeXmlTagName); validLines.shift(); + } else { + // No header row to source tag names from - fall back to positional + // column names (col1, col2, ...) based on the first data row's width, + // so rows still get real field tags instead of coming out empty. + const columnCount = parseCsvLine(validLines[0], options).length; + headers = Array.from({ length: columnCount }, (_, i) => `col${i + 1}`); } validLines.forEach((line, index) => { const values = parseCsvLine(line, options); xmlResult += ` \n`; headers.forEach((header, i) => { - xmlResult += ` <${header}>${values[i] || ''}${header}>\n`; + xmlResult += ` <${header}>${escapeMarkup( + values[i] || '' + )}${header}>\n`; }); xmlResult += ` \n`; }); @@ -44,7 +48,7 @@ export const convertCsvToXml = ( return xmlResult; }; -const parseCsvLine = (line: string, options: CsvToXmlOptions): string[] => { +const parseCsvLine = (line: string, options: InitialValuesType): string[] => { const values: string[] = []; let currentValue = ''; let inQuotes = false; @@ -52,9 +56,25 @@ const parseCsvLine = (line: string, options: CsvToXmlOptions): string[] => { for (let i = 0; i < line.length; i++) { const char = line[i]; - if (char === options.quote) { - inQuotes = !inQuotes; - } else if (char === options.delimiter && !inQuotes) { + if (inQuotes) { + if (char === options.quote) { + // A doubled quote ("") inside a quoted field is an escaped + // literal quote, not the end of the field. + if (line[i + 1] === options.quote) { + currentValue += options.quote; + i++; + } else { + inQuotes = false; + } + } else { + currentValue += char; + } + } else if (char === options.quote && currentValue === '') { + // Only treat a quote as opening a quoted field when it's the very + // first character of the field - a quote appearing mid-field + // (e.g. `say "hello"`) is just literal text, not a CSV delimiter. + inQuotes = true; + } else if (char === options.delimiter) { values.push(currentValue.trim()); currentValue = ''; } else { diff --git a/src/pages/tools/csv/csv-to-xml/types.ts b/src/pages/tools/csv/csv-to-xml/types.ts new file mode 100644 index 00000000..f45e44e8 --- /dev/null +++ b/src/pages/tools/csv/csv-to-xml/types.ts @@ -0,0 +1,7 @@ +export type InitialValuesType = { + delimiter: string; + quote: string; + comment: string; + useHeaders: boolean; + skipEmptyLines: boolean; +}; diff --git a/src/pages/tools/csv/tsv-to-json/service.ts b/src/pages/tools/csv/tsv-to-json/service.ts index dadd40a2..02ddc59e 100644 --- a/src/pages/tools/csv/tsv-to-json/service.ts +++ b/src/pages/tools/csv/tsv-to-json/service.ts @@ -48,12 +48,8 @@ export function convertTsvToJson( } return options.indentationType === 'none' - ? minifyJson(JSON.stringify(result)) - : beautifyJson( - JSON.stringify(result), - options.indentationType, - options.spacesCount - ); + ? minifyJson(JSON.stringify(result)).result + : beautifyJson(JSON.stringify(result), options); } const parseCsvLine = (line: string, options: InitialValuesType): string[] => { diff --git a/src/pages/tools/image/generic/index.ts b/src/pages/tools/image/generic/index.ts index bb39bd88..d868cf19 100644 --- a/src/pages/tools/image/generic/index.ts +++ b/src/pages/tools/image/generic/index.ts @@ -10,6 +10,7 @@ import { tool as imageToText } from './image-to-text/meta'; import { tool as qrCodeGenerator } from './qr-code/meta'; import { tool as rotateImage } from './rotate/meta'; import { tool as imageEditor } from './editor/meta'; +import { tool as watermark } from './watermark/meta'; export const imageGenericTools = [ imageEditor, @@ -23,5 +24,6 @@ export const imageGenericTools = [ imageToText, qrCodeGenerator, rotateImage, + watermark, splitImage ]; diff --git a/src/pages/tools/image/generic/qr-code/index.tsx b/src/pages/tools/image/generic/qr-code/index.tsx index 5d6a0213..4cc5804f 100644 --- a/src/pages/tools/image/generic/qr-code/index.tsx +++ b/src/pages/tools/image/generic/qr-code/index.tsx @@ -1,17 +1,15 @@ import React, { useCallback, useState } from 'react'; -import { Box } from '@mui/material'; -import * as Yup from 'yup'; +import { Box, MenuItem, TextField } from '@mui/material'; +import { useTranslation } from 'react-i18next'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import SelectWithDesc from '@components/options/SelectWithDesc'; import { InitialValuesType, QRCodeType, WifiEncryptionType } from './types'; import ColorSelector from '@components/options/ColorSelector'; import ToolFileResult from '@components/result/ToolFileResult'; -import { useTranslation } from 'react-i18next'; -import * as QRCode from 'qrcode'; import { debounce } from 'lodash'; +import { generateQrCodeFile } from './service'; const initialValues: InitialValuesType = { qrCodeType: 'URL', @@ -20,6 +18,7 @@ const initialValues: InitialValuesType = { size: '200', bgColor: '#FFFFFF', fgColor: '#000000', + correctionLevel: 'M', // URL url: 'https://example.com', @@ -53,172 +52,104 @@ const initialValues: InitialValuesType = { vCardTitle: '', vCardWebsite: '' }; - -// Function to format the QR code data based on the type -const formatQRCodeData = (values: InitialValuesType): string => { - switch (values.qrCodeType) { - case 'URL': - return values.url; - - case 'Text': - return values.text; - - case 'Email': { - let emailData = `mailto:${values.emailAddress}`; - if (values.emailSubject || values.emailBody) { - emailData += '?'; - if (values.emailSubject) { - emailData += `subject=${encodeURIComponent(values.emailSubject)}`; - } - if (values.emailBody) { - emailData += `${ - values.emailSubject ? '&' : '' - }body=${encodeURIComponent(values.emailBody)}`; - } - } - return emailData; - } - case 'Phone': - return `tel:${values.phoneNumber}`; - - case 'SMS': - return `sms:${values.smsNumber}${ - values.smsMessage - ? `?body=${encodeURIComponent(values.smsMessage)}` - : '' - }`; - - case 'WiFi': { - const encryption = - values.wifiEncryption === 'None' ? 'nopass' : values.wifiEncryption; - return `WIFI:T:${encryption};S:${values.wifiSsid};P:${values.wifiPassword};;`; - } - case 'vCard': - return `BEGIN:VCARD -VERSION:3.0 -N:${values.vCardName} -FN:${values.vCardName} -ORG:${values.vCardCompany} -TITLE:${values.vCardTitle} -TEL:${values.vCardPhone} -EMAIL:${values.vCardEmail} -ADR:${values.vCardAddress} -URL:${values.vCardWebsite} -END:VCARD`; - - default: - return ''; - } -}; - -const validationSchema = Yup.object().shape({ - qrCodeType: Yup.string().required('QR code type is required'), - size: Yup.number() - .min(100, 'Size must be at least 100px') - .max(1000, 'Size must be at most 1000px') - .required('Size is required'), - bgColor: Yup.string().required('Background color is required'), - fgColor: Yup.string().required('Foreground color is required'), - - // URL - url: Yup.string().when('qrCodeType', { - is: 'URL', - then: (schema) => - schema.url('Please enter a valid URL').required('URL is required') - }), - - // Text - text: Yup.string().when('qrCodeType', { - is: 'Text', - then: (schema) => schema.required('Text is required') - }), - - // Email - emailAddress: Yup.string().when('qrCodeType', { - is: 'Email', - then: (schema) => - schema - .email('Please enter a valid email address') - .required('Email address is required') - }), - - // Phone - phoneNumber: Yup.string().when('qrCodeType', { - is: 'Phone', - then: (schema) => schema.required('Phone number is required') - }), - - // SMS - smsNumber: Yup.string().when('qrCodeType', { - is: 'SMS', - then: (schema) => schema.required('Phone number is required') - }), - - // WiFi - wifiSsid: Yup.string().when('qrCodeType', { - is: 'WiFi', - then: (schema) => schema.required('SSID is required') - }), - - // vCard - vCardName: Yup.string().when('qrCodeType', { - is: 'vCard', - then: (schema) => schema.required('Name is required') - }) -}); - export default function QRCodeGenerator({ title }: ToolComponentProps) { const { t } = useTranslation('image'); const [result, setResult] = useState(null); + const getGroups: GetGroupsType = ({ values, updateField }) => { return [ { - title: 'QR Code Type', + title: t('qrCode.groups.type.title'), component: ( - - updateField('qrCodeType', value as QRCodeType) + + updateField('qrCodeType', e.target.value as QRCodeType) } - options={[ - { label: 'URL', value: 'URL' }, - { label: 'Text', value: 'Text' }, - { label: 'Email', value: 'Email' }, - { label: 'Phone', value: 'Phone' }, - { label: 'SMS', value: 'SMS' }, - { label: 'WiFi', value: 'WiFi' }, - { label: 'vCard', value: 'vCard' } - ]} - description={t('qrCode.options.qrType')} - /> + label={t('qrCode.groups.type.label')} + margin="normal" + > + + {t('qrCode.groups.type.options.url')} + + + {t('qrCode.groups.type.options.text')} + + + {t('qrCode.groups.type.options.email')} + + + {t('qrCode.groups.type.options.phone')} + + + {t('qrCode.groups.type.options.sms')} + + + {t('qrCode.groups.type.options.wifi')} + + + {t('qrCode.groups.type.options.vcard')} + + ) }, { - title: 'QR Code Settings', + title: t('qrCode.groups.settings.title'), component: ( updateField('size', val)} - description={t('qrCode.options.size')} + description={t('qrCode.groups.settings.size.description')} inputProps={{ type: 'number', min: 100, max: 1000 }} /> + + updateField( + 'correctionLevel', + e.target.value as 'L' | 'M' | 'Q' | 'H' + ) + } + helperText={t( + 'qrCode.groups.settings.correctionLevel.helperText' + )} + > + + {t('qrCode.groups.settings.correctionLevel.options.l')} + + + {t('qrCode.groups.settings.correctionLevel.options.m')} + + + {t('qrCode.groups.settings.correctionLevel.options.q')} + + + {t('qrCode.groups.settings.correctionLevel.options.h')} + + updateField('bgColor', val)} /> updateField('fgColor', val)} /> @@ -227,16 +158,16 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { }, // Dynamic form fields based on QR code type { - title: `${values.qrCodeType} Details`, + title: t('qrCode.groups.details.title', { type: values.qrCodeType }), component: ( {values.qrCodeType === 'URL' && ( updateField('url', val)} - description={t('qrCode.options.url')} + description={t('qrCode.groups.details.url.description')} inputProps={{ - placeholder: 'https://example.com' + placeholder: t('qrCode.groups.details.url.placeholder') }} /> )} @@ -245,11 +176,11 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('text', val)} - description={t('qrCode.options.text')} + description={t('qrCode.groups.details.text.description')} multiline rows={4} inputProps={{ - placeholder: 'Lorem Ipsum' + placeholder: t('qrCode.groups.details.text.placeholder') }} /> )} @@ -259,28 +190,40 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('emailAddress', val)} - description={t('qrCode.options.email')} + description={t( + 'qrCode.groups.details.email.address.description' + )} inputProps={{ - placeholder: 'example@example.com', + placeholder: t( + 'qrCode.groups.details.email.address.placeholder' + ), type: 'email' }} /> updateField('emailSubject', val)} - description={t('qrCode.options.emailSubject')} + description={t( + 'qrCode.groups.details.email.subject.description' + )} inputProps={{ - placeholder: 'Subject line' + placeholder: t( + 'qrCode.groups.details.email.subject.placeholder' + ) }} /> updateField('emailBody', val)} - description={t('qrCode.options.emailBody')} + description={t( + 'qrCode.groups.details.email.body.description' + )} multiline rows={4} inputProps={{ - placeholder: 'Body text' + placeholder: t( + 'qrCode.groups.details.email.body.placeholder' + ) }} /> > @@ -290,9 +233,9 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('phoneNumber', val)} - description={t('qrCode.options.phone')} + description={t('qrCode.groups.details.phone.description')} inputProps={{ - placeholder: '+1234567890', + placeholder: t('qrCode.groups.details.phone.placeholder'), type: 'tel' }} /> @@ -303,20 +246,28 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('smsNumber', val)} - description={t('qrCode.options.phone')} + description={t( + 'qrCode.groups.details.sms.number.description' + )} inputProps={{ - placeholder: '+1234567890', + placeholder: t( + 'qrCode.groups.details.sms.number.placeholder' + ), type: 'tel' }} /> updateField('smsMessage', val)} - description={t('qrCode.options.message')} + description={t( + 'qrCode.groups.details.sms.message.description' + )} multiline rows={4} inputProps={{ - placeholder: 'Lorem Ipsum' + placeholder: t( + 'qrCode.groups.details.sms.message.placeholder' + ) }} /> > @@ -327,32 +278,49 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('wifiSsid', val)} - description={t('qrCode.options.ssid')} + description={t('qrCode.groups.details.wifi.ssid.description')} inputProps={{ - placeholder: 'WIFI name' + placeholder: t( + 'qrCode.groups.details.wifi.ssid.placeholder' + ) }} /> updateField('wifiPassword', val)} - description={t('qrCode.options.password')} + description={t( + 'qrCode.groups.details.wifi.password.description' + )} inputProps={{ - placeholder: '******', + placeholder: t( + 'qrCode.groups.details.wifi.password.placeholder' + ), type: 'password' }} /> - - updateField('wifiEncryption', value as WifiEncryptionType) + + updateField( + 'wifiEncryption', + e.target.value as WifiEncryptionType + ) } - options={[ - { label: 'WPA', value: 'WPA' }, - { label: 'WEP', value: 'WEP' }, - { label: 'None', value: 'None' } - ]} - description={t('qrCode.options.encryptionType')} - /> + label={t('qrCode.groups.details.wifi.encryption.label')} + margin="normal" + > + + {t('qrCode.groups.details.wifi.encryption.options.wpa')} + + + {t('qrCode.groups.details.wifi.encryption.options.wep')} + + + {t('qrCode.groups.details.wifi.encryption.options.none')} + + > )} @@ -361,59 +329,87 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('vCardName', val)} - description={t('qrCode.options.fullName')} + description={t( + 'qrCode.groups.details.vcard.name.description' + )} inputProps={{ - placeholder: 'John Doe' + placeholder: t( + 'qrCode.groups.details.vcard.name.placeholder' + ) }} /> updateField('vCardEmail', val)} - description={t('qrCode.options.email')} + description={t( + 'qrCode.groups.details.vcard.email.description' + )} inputProps={{ - placeholder: 'john@example.com', + placeholder: t( + 'qrCode.groups.details.vcard.email.placeholder' + ), type: 'email' }} /> updateField('vCardPhone', val)} - description={t('qrCode.options.phone')} + description={t( + 'qrCode.groups.details.vcard.phone.description' + )} inputProps={{ - placeholder: '+1234567890', + placeholder: t( + 'qrCode.groups.details.vcard.phone.placeholder' + ), type: 'tel' }} /> updateField('vCardAddress', val)} - description={t('qrCode.options.address')} + description={t( + 'qrCode.groups.details.vcard.address.description' + )} inputProps={{ - placeholder: '123 Main St, City, Country' + placeholder: t( + 'qrCode.groups.details.vcard.address.placeholder' + ) }} /> updateField('vCardCompany', val)} - description={t('qrCode.options.company')} + description={t( + 'qrCode.groups.details.vcard.company.description' + )} inputProps={{ - placeholder: 'Company name' + placeholder: t( + 'qrCode.groups.details.vcard.company.placeholder' + ) }} /> updateField('vCardTitle', val)} - description={t('qrCode.options.job')} + description={t( + 'qrCode.groups.details.vcard.title.description' + )} inputProps={{ - placeholder: 'Software Developer' + placeholder: t( + 'qrCode.groups.details.vcard.title.placeholder' + ) }} /> updateField('vCardWebsite', val)} - description={t('qrCode.options.website')} + description={t( + 'qrCode.groups.details.vcard.website.description' + )} inputProps={{ - placeholder: 'https://example.com' + placeholder: t( + 'qrCode.groups.details.vcard.website.placeholder' + ) }} /> > @@ -425,27 +421,15 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { }; const compute = async (options: InitialValuesType) => { - const qrValue = formatQRCodeData(options); - if (!qrValue) return; - const canvas = document.createElement('canvas'); - QRCode.toDataURL( - canvas, - qrValue, - { - color: { - dark: options.fgColor, - light: options.bgColor - }, - width: Number(options.size) || 200 - }, - async (error, url) => { - const res = await fetch(url); - const blob = await res.blob(); - const file = new File([blob], 'Qr code.png', { type: 'image/png' }); - setResult(file); - } - ); + try { + const file = await generateQrCodeFile(options); + setResult(file); + } catch (err) { + console.error('Failed to generate QR code', err); + setResult(null); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); return ( @@ -453,14 +437,13 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { title={title} initialValues={initialValues} getGroups={getGroups} - validationSchema={validationSchema} compute={debouncedCompute} resultComponent={ - + } toolInfo={{ title: t('qrCode.title'), - description: t('qrCode.description') + description: t('qrCode.longDescription') }} /> ); diff --git a/src/pages/tools/image/generic/qr-code/service.ts b/src/pages/tools/image/generic/qr-code/service.ts new file mode 100644 index 00000000..69a33b93 --- /dev/null +++ b/src/pages/tools/image/generic/qr-code/service.ts @@ -0,0 +1,106 @@ +import * as QRCode from 'qrcode'; +import { InitialValuesType } from './types'; + +/** Formats the raw form values into the string that gets encoded in the QR code, based on the selected type. */ +export function formatQRCodeData(values: InitialValuesType): string { + switch (values.qrCodeType) { + case 'URL': + return values.url; + + case 'Text': + return values.text; + + case 'Email': { + let emailData = `mailto:${values.emailAddress}`; + if (values.emailSubject || values.emailBody) { + emailData += '?'; + if (values.emailSubject) { + emailData += `subject=${encodeURIComponent(values.emailSubject)}`; + } + if (values.emailBody) { + emailData += `${ + values.emailSubject ? '&' : '' + }body=${encodeURIComponent(values.emailBody)}`; + } + } + return emailData; + } + case 'Phone': + return `tel:${values.phoneNumber}`; + + case 'SMS': + return `sms:${values.smsNumber}${ + values.smsMessage + ? `?body=${encodeURIComponent(values.smsMessage)}` + : '' + }`; + + case 'WiFi': { + const encryption = + values.wifiEncryption === 'None' ? 'nopass' : values.wifiEncryption; + return `WIFI:T:${encryption};S:${values.wifiSsid};P:${values.wifiPassword};;`; + } + case 'vCard': + return `BEGIN:VCARD +VERSION:3.0 +N:${values.vCardName} +FN:${values.vCardName} +ORG:${values.vCardCompany} +TITLE:${values.vCardTitle} +TEL:${values.vCardPhone} +EMAIL:${values.vCardEmail} +ADR:${values.vCardAddress} +URL:${values.vCardWebsite} +END:VCARD`; + + default: + return ''; + } +} + +/** + * Renders the QR code for the given form values and returns it as a + * downloadable PNG File. Returns null if there's nothing to encode yet + * (e.g. required field for the current type is still empty). + */ +export function generateQrCodeFile( + options: InitialValuesType +): Promise { + const qrValue = formatQRCodeData(options); + if (!qrValue) return Promise.resolve(null); + + const canvas = document.createElement('canvas'); + + return new Promise((resolve, reject) => { + QRCode.toDataURL( + canvas, + qrValue, + { + color: { + dark: options.fgColor, + light: options.bgColor + }, + width: Number(options.size) || 200, + errorCorrectionLevel: options.correctionLevel + }, + async (error, url) => { + // The original callback never checked `error`, so a QR generation + // failure (e.g. text too long for the chosen correction level) + // would silently try to fetch `undefined` and throw a confusing + // error instead. Surface it properly here. + if (error) { + reject(error); + return; + } + try { + const res = await fetch(url); + const blob = await res.blob(); + const file = new File([blob], 'qr-code.png', { type: 'image/png' }); + resolve(file); + } catch (fetchErr) { + reject(fetchErr); + } + } + ); + }); +} diff --git a/src/pages/tools/image/generic/qr-code/types.ts b/src/pages/tools/image/generic/qr-code/types.ts index b9959247..4aa78280 100644 --- a/src/pages/tools/image/generic/qr-code/types.ts +++ b/src/pages/tools/image/generic/qr-code/types.ts @@ -7,6 +7,8 @@ export type QRCodeType = | 'WiFi' | 'vCard'; +export type QRErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; + export type WifiEncryptionType = 'WPA' | 'WEP' | 'None'; export interface InitialValuesType { @@ -16,6 +18,7 @@ export interface InitialValuesType { size: string; bgColor: string; fgColor: string; + correctionLevel: QRErrorCorrectionLevel; // URL url: string; diff --git a/src/pages/tools/image/generic/resize/index.tsx b/src/pages/tools/image/generic/resize/index.tsx index 447ee39f..ac2c9a63 100644 --- a/src/pages/tools/image/generic/resize/index.tsx +++ b/src/pages/tools/image/generic/resize/index.tsx @@ -223,6 +223,7 @@ export default function ResizeImage({ title }: ToolComponentProps) { ) diff --git a/src/pages/tools/image/generic/resize/service.ts b/src/pages/tools/image/generic/resize/service.ts index 8ed4859d..5b32e599 100644 --- a/src/pages/tools/image/generic/resize/service.ts +++ b/src/pages/tools/image/generic/resize/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import JSZip from 'jszip'; @@ -15,54 +15,54 @@ const processImage = async ( dimensionType, maintainAspectRatio } = options; + if (file.type === 'image/svg+xml') { try { - // Read the SVG file const fileText = await file.text(); const parser = new DOMParser(); const svgDoc = parser.parseFromString(fileText, 'image/svg+xml'); const svgElement = svgDoc.documentElement; - // Get original dimensions const viewBox = svgElement.getAttribute('viewBox'); + let originalWidth: string | number | null = svgElement.getAttribute('width'); + let originalHeight: string | number | null = svgElement.getAttribute('height'); - // Parse viewBox if available and width/height are not explicitly set let viewBoxValues = null; + if (viewBox) { viewBoxValues = viewBox.split(' ').map(Number); } - // Determine original dimensions from viewBox if not explicitly set - if (!originalWidth && viewBoxValues && viewBoxValues.length === 4) { + if (!originalWidth && viewBoxValues?.length === 4) { originalWidth = String(viewBoxValues[2]); } - if (!originalHeight && viewBoxValues && viewBoxValues.length === 4) { + + if (!originalHeight && viewBoxValues?.length === 4) { originalHeight = String(viewBoxValues[3]); } - // Default dimensions if still not available originalWidth = originalWidth ? parseFloat(originalWidth) : 300; originalHeight = originalHeight ? parseFloat(originalHeight) : 150; - // Calculate new dimensions let newWidth = originalWidth; let newHeight = originalHeight; if (resizeMethod === 'pixels') { if (dimensionType === 'width') { newWidth = parseInt(width); + if (maintainAspectRatio) { newHeight = Math.round((newWidth / originalWidth) * originalHeight); } else { newHeight = parseInt(height); } } else { - // height newHeight = parseInt(height); + if (maintainAspectRatio) { newWidth = Math.round((newHeight / originalHeight) * originalWidth); } else { @@ -70,17 +70,15 @@ const processImage = async ( } } } else { - // percentage const scale = parseInt(percentage) / 100; + newWidth = Math.round(originalWidth * scale); newHeight = Math.round(originalHeight * scale); } - // Update SVG attributes svgElement.setAttribute('width', String(newWidth)); svgElement.setAttribute('height', String(newHeight)); - // If viewBox isn't already set, add it to preserve scaling if (!viewBox) { svgElement.setAttribute( 'viewBox', @@ -88,134 +86,129 @@ const processImage = async ( ); } - // Serialize the modified SVG document const serializer = new XMLSerializer(); const svgString = serializer.serializeToString(svgDoc); - // Create a new file return new File([svgString], file.name, { type: 'image/svg+xml' }); } catch (error) { console.error('Error processing SVG:', error); - // Fall back to canvas method if SVG processing fails } - } else if (file.type === 'image/gif') { + } + + if (file.type === 'image/gif') { try { - const ffmpeg = new FFmpeg(); + return await runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.gif'); + const outputName = tempFile('.gif'); - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); + await ffmpeg.writeFile(inputName, await fetchFile(file)); - // Write the input file to memory - await ffmpeg.writeFile('input.gif', await fetchFile(file)); + let scaleFilter = ''; - // Calculate new dimensions - let newWidth = 0; - let newHeight = 0; - let scaleFilter = ''; + if (resizeMethod === 'pixels') { + if (dimensionType === 'width') { + const newWidth = parseInt(width); - if (resizeMethod === 'pixels') { - if (dimensionType === 'width') { - newWidth = parseInt(width); - if (maintainAspectRatio) { - scaleFilter = `scale=${newWidth}:-1`; + scaleFilter = maintainAspectRatio + ? `scale=${newWidth}:-1` + : `scale=${newWidth}:${parseInt(height)}`; } else { - newHeight = parseInt(height); - scaleFilter = `scale=${newWidth}:${newHeight}`; + const newHeight = parseInt(height); + + scaleFilter = maintainAspectRatio + ? `scale=-1:${newHeight}` + : `scale=${parseInt(width)}:${newHeight}`; } } else { - // height - newHeight = parseInt(height); - if (maintainAspectRatio) { - scaleFilter = `scale=-1:${newHeight}`; - } else { - newWidth = parseInt(width); - scaleFilter = `scale=${newWidth}:${newHeight}`; - } + const scale = parseInt(percentage) / 100; + scaleFilter = `scale=iw*${scale}:ih*${scale}`; } - } else { - // percentage - const scale = parseInt(percentage) / 100; - scaleFilter = `scale=iw*${scale}:ih*${scale}`; - } - // Run FFmpeg command - await ffmpeg.exec(['-i', 'input.gif', '-vf', scaleFilter, 'output.gif']); + await ffmpeg.exec([ + '-i', + inputName, + '-vf', + `${scaleFilter},split[a][b];[a]palettegen[p];[b][p]paletteuse`, + outputName + ]); - // Read the output file - const data = await ffmpeg.readFile('output.gif'); + const data = await ffmpeg.readFile(outputName); - // Create a new File object - return new File([data as any], file.name, { type: 'image/gif' }); + return new File([new Uint8Array(data as Uint8Array)], file.name, { + type: 'image/gif' + }); + }); } catch (error) { console.error('Error processing GIF with FFmpeg:', error); - // Fall back to canvas method if FFmpeg processing fails } } - // Create canvas - const canvas = document.createElement('canvas'); - const ctx = canvas.getContext('2d'); - if (ctx == null) return null; - // Load image - const img = new Image(); - img.src = URL.createObjectURL(file); - await img.decode(); + try { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); - // Calculate new dimensions - let newWidth = img.width; - let newHeight = img.height; + if (!ctx) return null; - if (resizeMethod === 'pixels') { - if (dimensionType === 'width') { - newWidth = parseInt(width); - if (maintainAspectRatio) { - newHeight = Math.round((newWidth / img.width) * img.height); + const img = new Image(); + img.src = URL.createObjectURL(file); + + await img.decode(); + + let newWidth = img.width; + let newHeight = img.height; + + if (resizeMethod === 'pixels') { + if (dimensionType === 'width') { + newWidth = parseInt(width); + + if (maintainAspectRatio) { + newHeight = Math.round((newWidth / img.width) * img.height); + } else { + newHeight = parseInt(height); + } } else { newHeight = parseInt(height); + + if (maintainAspectRatio) { + newWidth = Math.round((newHeight / img.height) * img.width); + } else { + newWidth = parseInt(width); + } } } else { - // height - newHeight = parseInt(height); - if (maintainAspectRatio) { - newWidth = Math.round((newHeight / img.height) * img.width); - } else { - newWidth = parseInt(width); - } + const scale = parseInt(percentage) / 100; + + newWidth = Math.round(img.width * scale); + newHeight = Math.round(img.height * scale); } - } else { - // percentage - const scale = parseInt(percentage) / 100; - newWidth = Math.round(img.width * scale); - newHeight = Math.round(img.height * scale); + + canvas.width = newWidth; + canvas.height = newHeight; + + ctx.drawImage(img, 0, 0, newWidth, newHeight); + + const outputType = file.type || 'image/png'; + + return new Promise((resolve) => { + canvas.toBlob((blob) => { + if (!blob) { + resolve(null); + return; + } + + resolve( + new File([blob], file.name, { + type: outputType + }) + ); + }, outputType); + }); + } catch (error) { + console.error('Error processing image:', error); + return null; } - - // Set canvas dimensions - canvas.width = newWidth; - canvas.height = newHeight; - - // Draw resized image - ctx.drawImage(img, 0, 0, newWidth, newHeight); - - // Determine output type based on input file - let outputType = 'image/png'; - if (file.type) { - outputType = file.type; - } - - // Convert canvas to blob and create file - return new Promise((resolve) => { - canvas.toBlob((blob) => { - if (blob) { - resolve(new File([blob], file.name, { type: outputType })); - } else { - resolve(null); - } - }, outputType); - }); }; export const resizeImages = async ( @@ -234,20 +227,35 @@ export const resizeImages = async ( }) ); - const results = processed.filter((f): f is File => f !== null); + const results = processed.filter((file): file is File => file !== null); - if (results.length === 0) return null; + if (results.length === 0) { + return null; + } - if (results.length === 1) return { results, zipFile: null }; + if (results.length === 1) { + return { + results, + zipFile: null + }; + } const zip = new JSZip(); - results.forEach((file) => zip.file(file.name, file)); - const zipBlob = await zip.generateAsync({ type: 'blob' }); - const zipFile = new File([zipBlob], 'resized-images.zip', { - type: 'application/zip' + + results.forEach((file) => { + zip.file(file.name, file); }); - return { results, zipFile }; + const zipBlob = await zip.generateAsync({ + type: 'blob' + }); + + return { + results, + zipFile: new File([zipBlob], 'resized-images.zip', { + type: 'application/zip' + }) + }; } catch (error) { console.error('Error processing images:', error); return null; diff --git a/src/pages/tools/image/generic/rotate/index.tsx b/src/pages/tools/image/generic/rotate/index.tsx index 90e329a6..695331e7 100644 --- a/src/pages/tools/image/generic/rotate/index.tsx +++ b/src/pages/tools/image/generic/rotate/index.tsx @@ -1,7 +1,7 @@ import { ToolComponentProps } from '@tools/defineTool'; import { InitialValuesType } from './type'; import * as Yup from 'yup'; - +import { getFileExtension } from '@utils/file'; import { useState } from 'react'; import { GetGroupsType } from '@components/options/ToolOptions'; import SimpleRadio from '@components/options/SimpleRadio'; @@ -12,6 +12,7 @@ import ToolContent from '@components/ToolContent'; import ToolImageInput from '@components/input/ToolImageInput'; import ToolFileResult from '@components/result/ToolFileResult'; import { processImage } from './service'; +import { useTranslation } from 'react-i18next'; const initialValues: InitialValuesType = { rotateAngle: '90', @@ -30,32 +31,43 @@ const validationSchema = Yup.object({ }); export default function RotateImage({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); const compute = async (optionsValues: InitialValuesType, input: any) => { if (!input) return; - setResult(await processImage(input, optionsValues)); + setLoading(true); + try { + const rotatedFile = await processImage(input, optionsValues); + setResult(rotatedFile); + } catch (err) { + console.error(`Failed to rotate image input: ${err}`); + setResult(null); + } finally { + setLoading(false); + } }; const getGroups: GetGroupsType = ({ values, updateField }) => [ { - title: 'Rotate Method', + title: t('rotate.options.method'), component: ( updateField('rotateMethod', 'Preset')} checked={values.rotateMethod === 'Preset'} - description={'Rotate by a specific angle in degrees.'} - title={'Preset angle'} + description={t('rotate.options.presetDesc')} + title={t('rotate.options.presetTitle')} /> updateField('rotateMethod', 'Custom')} checked={values.rotateMethod === 'Custom'} - description={'Rotate by a custom angle in degrees.'} - title={'Custom angle'} + description={t('rotate.options.customDesc')} + title={t('rotate.options.customTitle')} /> ) @@ -63,13 +75,13 @@ export default function RotateImage({ title }: ToolComponentProps) { ...(values.rotateMethod === 'Preset' ? [ { - title: 'Preset angle', + title: t('rotate.options.angle'), component: ( updateField('rotateAngle', val)} - description={'Rotate by a specific angle in degrees.'} + description={''} options={[ { label: '90 degrees', value: '90' }, { label: '180 degrees', value: '180' }, @@ -82,15 +94,13 @@ export default function RotateImage({ title }: ToolComponentProps) { ] : [ { - title: 'Custom angle', + title: t('rotate.options.angle'), component: ( updateField('rotateAngle', val)} - description={ - 'Rotate by a custom angle in degrees(from -360 to 360).' - } + description={'- 360 ↔ 360'} inputProps={{ type: 'number', min: -360, @@ -115,22 +125,18 @@ export default function RotateImage({ title }: ToolComponentProps) { } resultComponent={ } - toolInfo={{ - title: 'Rotate Image', - description: - 'This tool allows you to rotate images by a specific angle in any degrees.' - }} /> ); } diff --git a/src/pages/tools/image/generic/rotate/service.ts b/src/pages/tools/image/generic/rotate/service.ts index 9ace4b19..8f4fe880 100644 --- a/src/pages/tools/image/generic/rotate/service.ts +++ b/src/pages/tools/image/generic/rotate/service.ts @@ -1,12 +1,13 @@ import { InitialValuesType } from './type'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; export const processImage = async ( file: File, options: InitialValuesType ): Promise => { - const { rotateAngle, rotateMethod } = options; + const { rotateAngle } = options; if (file.type === 'image/svg+xml') { try { // Read the SVG file @@ -45,30 +46,32 @@ export const processImage = async ( } // For non-SVG images, use FFmpeg - try { - const ffmpeg = new FFmpeg(); - await ffmpeg.load(); + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const extension = getFileExtension(file.name) ?? 'png'; - // Write input file - await ffmpeg.writeFile('input', await fetchFile(file)); + const inputName = tempFile(`.${extension}`); + const outputName = tempFile('.png'); - // Determine rotation command - const rotateCmd = `rotate=${rotateAngle}*PI/180`; + await ffmpeg.writeFile(inputName, await fetchFile(file)); + + const radians = `${Number(rotateAngle)}*PI/180`; - // Execute FFmpeg command await ffmpeg.exec([ '-i', - 'input', + inputName, '-vf', - rotateCmd, - 'output.' + file.name.split('.').pop() + `rotate=${radians}:ow=rotw(${radians}):oh=roth(${radians}):fillcolor=none`, + outputName ]); - // Read the output file - const data = await ffmpeg.readFile('output.' + file.name.split('.').pop()); - return new File([data as any], file.name, { type: file.type }); - } catch (error) { - console.error('Error processing image:', error); - return null; - } + const data = await ffmpeg.readFile(outputName); + + return new File( + [new Uint8Array(data as Uint8Array)], + `rotated_${file.name.replace(/\.[^/.]+$/, '.png')}`, + { + type: 'image/png' + } + ); + }); }; diff --git a/src/pages/tools/image/generic/watermark/index.tsx b/src/pages/tools/image/generic/watermark/index.tsx new file mode 100644 index 00000000..e0878d89 --- /dev/null +++ b/src/pages/tools/image/generic/watermark/index.tsx @@ -0,0 +1,228 @@ +import { Box } from '@mui/material'; +import React, { useState, useContext } from 'react'; +import * as Yup from 'yup'; +import ToolMultipleImageInput, { + MultiImageInput +} from '@components/input/ToolMultipleImageInput'; +import ToolMultiFileResult from '@components/result/ToolMultiFileResult'; +import ColorSelector from '@components/options/ColorSelector'; +import ToolFileResult from '@components/result/ToolFileResult'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; +import ToolContent from '@components/ToolContent'; +import { ToolComponentProps } from '@tools/defineTool'; +import SimpleRadio from '@components/options/SimpleRadio'; +import { watermarkImages } from './service'; +import { InitialValuesType } from './types'; +import { CustomSnackBarContext } from 'contexts/CustomSnackBarContext'; +import { useTranslation } from 'react-i18next'; +import { getFileExtension } from '@utils/file'; + +const initialValues: InitialValuesType = { + filename: true, + watermark: 'OMNITOOLS', + watermarkOpacity: 0.35, + fontSize: 32, + position: 'bottom-right', + color: '#ffffff' +}; + +const validationSchema = Yup.object({ + watermarkOpacity: Yup.number() + .min(0, 'Opacity must be between 0 and 1') + .max(1, 'Opacity must be between 0 and 1') + .required('Opacity is required'), + fontSize: Yup.number() + .min(8, 'Font size must be at least 8px') + .max(512, 'Font size is too large') + .required('Font size is required'), + color: Yup.string().required('Color is required') +}); + +export default function Watermark({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); + const [input, setInput] = useState([]); + const [result, setResult] = useState([]); + const [zipFile, setZipFile] = useState(null); + const [isProcessing, setIsProcessing] = useState(false); + const { showSnackBar } = useContext(CustomSnackBarContext); + + const compute = async ( + optionsValues: InitialValuesType, + input: MultiImageInput[] + ) => { + if (!input || input.length === 0) return; + + try { + setIsProcessing(true); + + const output = await watermarkImages( + input.map((img) => img.file), + optionsValues + ); + + if (!output) { + showSnackBar(t('watermark.failedToProcess'), 'error'); + return; + } else { + setResult(output.results); + setZipFile(output.zipFile); + } + } catch (error) { + showSnackBar(`Error converting files: ${error}`, 'error'); + setZipFile(null); + } finally { + setIsProcessing(false); + } + }; + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: t('watermark.options.watermarkTitle'), + component: ( + + + updateField('filename', true)} + checked={values.filename === true} + title={t('watermark.options.filenameWatermarkTitle')} + description={t('watermark.options.filenameWatermarkDesc')} + /> + updateField('filename', false)} + checked={values.filename === false} + title={t('watermark.options.customStringWatermarkTitle')} + description={t('watermark.options.customStringWatermarkDesc')} + /> + + {!values.filename && ( + updateField('watermark', val)} + description={t('watermark.options.watermark')} + inputProps={{ + 'data-testid': 'watermark-input', + type: 'string' + }} + /> + )} + + ) + }, + { + title: t('watermark.options.styleTitle'), + component: ( + + updateField('watermarkOpacity', Number(val))} + description={t('watermark.options.opacity')} + inputProps={{ + 'data-testid': 'opacity-input', + type: 'number', + min: 0, + max: 1, + step: 0.05 + }} + /> + updateField('fontSize', Number(val))} + description={t('watermark.options.fontSize')} + inputProps={{ + 'data-testid': 'font-size-input', + type: 'number', + min: 8, + max: 512, + step: 1 + }} + /> + updateField('color', val)} + description={t('watermark.options.color')} + inputProps={{ + 'data-testid': 'color-input' + }} + /> + + ) + }, + { + title: t('watermark.options.positionTitle'), + component: ( + + updateField('position', 'bottom-right')} + checked={values.position === 'bottom-right'} + title={t('watermark.options.position.bottomRight')} + /> + updateField('position', 'bottom-left')} + checked={values.position === 'bottom-left'} + title={t('watermark.options.position.bottomLeft')} + /> + updateField('position', 'top-right')} + checked={values.position === 'top-right'} + title={t('watermark.options.position.topRight')} + /> + updateField('position', 'top-left')} + checked={values.position === 'top-left'} + title={t('watermark.options.position.topLeft')} + /> + updateField('position', 'center')} + checked={values.position === 'center'} + title={t('watermark.options.position.center')} + /> + + ) + } + ]; + + return ( + + } + resultComponent={ + zipFile ? ( + + ) : ( + + ) + } + toolInfo={{ + title: t('watermark.toolInfo.title'), + description: t('watermark.toolInfo.longDescription') + }} + /> + ); +} diff --git a/src/pages/tools/image/generic/watermark/meta.ts b/src/pages/tools/image/generic/watermark/meta.ts new file mode 100644 index 00000000..79d1a286 --- /dev/null +++ b/src/pages/tools/image/generic/watermark/meta.ts @@ -0,0 +1,26 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('image-generic', { + i18n: { + name: 'image:watermark.title', + description: 'image:watermark.description', + shortDescription: 'image:watermark.shortDescription', + userTypes: ['generalUsers'] + }, + + path: 'watermark', + icon: 'mdi:watermark', + + keywords: [ + 'watermark', + 'image', + 'text', + 'filename', + 'overlay', + 'branding', + 'stamp' + ], + + component: lazy(() => import('./index')) +}); diff --git a/src/pages/tools/image/generic/watermark/service.ts b/src/pages/tools/image/generic/watermark/service.ts new file mode 100644 index 00000000..98736054 --- /dev/null +++ b/src/pages/tools/image/generic/watermark/service.ts @@ -0,0 +1,192 @@ +import { InitialValuesType, Position } from './types'; +import { heicTo, isHeic } from 'heic-to'; +import JSZip from 'jszip'; + +function computePosition( + position: Position, + canvasWidth: number, + canvasHeight: number, + padding: number +) { + switch (position) { + case 'top-left': + return { + x: padding, + y: padding, + align: 'left' as const, + baseline: 'top' as const + }; + case 'top-right': + return { + x: canvasWidth - padding, + y: padding, + align: 'right' as const, + baseline: 'top' as const + }; + case 'bottom-left': + return { + x: padding, + y: canvasHeight - padding, + align: 'left' as const, + baseline: 'bottom' as const + }; + case 'center': + return { + x: canvasWidth / 2, + y: canvasHeight / 2, + align: 'center' as const, + baseline: 'middle' as const + }; + case 'bottom-right': + default: + return { + x: canvasWidth - padding, + y: canvasHeight - padding, + align: 'right' as const, + baseline: 'bottom' as const + }; + } +} + +const processImage = async ( + file: File, + options: InitialValuesType +): Promise => { + const { watermarkOpacity, fontSize, position, color } = options; + + let processedFile = file; + + if (await isHeic(file)) { + const convertedBlob = await heicTo({ blob: file, type: 'image/jpeg' }); + processedFile = new File( + [convertedBlob], + file.name.replace(/\.[^/.]+$/, '') + '.jpg', + { type: 'image/jpeg' } + ); + } + + // Skip formats we don't watermark yet + if (processedFile.type === 'image/svg+xml') { + console.warn('SVG watermark not supported yet.'); + return; + } + if (processedFile.type === 'image/gif') { + console.warn('GIF watermark not supported yet.'); + return; + } + + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + if (ctx == null) return; + + const img = new Image(); + img.src = URL.createObjectURL(processedFile); + + try { + await img.decode(); + + canvas.width = img.width; + canvas.height = img.height; + ctx.drawImage(img, 0, 0); + + // Watermark text from the original filename + const text = options.filename + ? file.name + .replace(/\.[^/.]+$/, '') + .replace(/[_-]+/g, ' ') + .trim() + : options.watermark; + + if (!text) return; + + const padding = Math.max( + 12, + Math.round(Math.min(canvas.width, canvas.height) * 0.02) + ); + + ctx.save(); + ctx.globalAlpha = watermarkOpacity; + ctx.fillStyle = color; + ctx.font = `bold ${fontSize}px sans-serif`; + ctx.shadowColor = 'rgba(0,0,0,0.65)'; + ctx.shadowBlur = 6; + ctx.shadowOffsetX = 2; + ctx.shadowOffsetY = 2; + + const pos = computePosition(position, canvas.width, canvas.height, padding); + ctx.textAlign = pos.align; + ctx.textBaseline = pos.baseline; + + ctx.fillText(text, pos.x, pos.y); + ctx.restore(); + + // Keep the original format (PNG/JPEG/WebP), default to PNG otherwise + const outputType = + processedFile.type === 'image/jpeg' || processedFile.type === 'image/webp' + ? processedFile.type + : 'image/png'; + const ext = + outputType === 'image/jpeg' + ? 'jpeg' + : outputType === 'image/webp' + ? 'webp' + : 'png'; + const quality = outputType === 'image/jpeg' ? 0.92 : undefined; + + return new Promise((resolve) => { + canvas.toBlob( + (blob) => { + if (blob) { + const fileName = + file.name.replace(/\.[^/.]+$/, '') + `_watermarked.${ext}`; + resolve(new File([blob], fileName, { type: outputType })); + } else { + resolve(undefined); + } + }, + outputType, + quality + ); + }); + } catch (error) { + console.error('Error processing image:', error); + } finally { + URL.revokeObjectURL(img.src); + } +}; + +export const watermarkImages = async ( + files: File[], + options: InitialValuesType +): Promise<{ results: File[]; zipFile: File | null } | null> => { + try { + const watermarked = await Promise.all( + files.map(async (file) => { + try { + return (await processImage(file, options)) ?? null; + } catch (error) { + console.error(`Error watermarking ${file.name}:`, error); + return null; + } + }) + ); + + const results = watermarked.filter((f): f is File => f !== null); + + if (results.length === 0) return null; + + if (results.length === 1) return { results, zipFile: null }; + + const zip = new JSZip(); + results.forEach((file) => zip.file(file.name, file)); + const zipBlob = await zip.generateAsync({ type: 'blob' }); + const zipFile = new File([zipBlob], 'watermarked-images.zip', { + type: 'application/zip' + }); + + return { results, zipFile }; + } catch (error) { + console.error('Error watermarking images:', error); + return null; + } +}; diff --git a/src/pages/tools/image/generic/watermark/types.ts b/src/pages/tools/image/generic/watermark/types.ts new file mode 100644 index 00000000..59fa52db --- /dev/null +++ b/src/pages/tools/image/generic/watermark/types.ts @@ -0,0 +1,15 @@ +export type Position = + | 'bottom-right' + | 'bottom-left' + | 'top-right' + | 'top-left' + | 'center'; + +export type InitialValuesType = { + filename: boolean; + watermark: string; + watermarkOpacity: number; + fontSize: number; + position: Position; + color: string; +}; diff --git a/src/pages/tools/json/escape-json/index.tsx b/src/pages/tools/json/escape-json/index.tsx index 41c5d6e4..bca88458 100644 --- a/src/pages/tools/json/escape-json/index.tsx +++ b/src/pages/tools/json/escape-json/index.tsx @@ -1,13 +1,14 @@ import React, { useState } from 'react'; +import { Box } from '@mui/material'; +import { useTranslation } from 'react-i18next'; import ToolContent from '@components/ToolContent'; import ToolCodeInput from '@components/input/ToolCodeInput'; import ToolTextResult from '@components/result/ToolTextResult'; +import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; import { escapeJson } from './service'; import { CardExampleType } from '@components/examples/ToolExamples'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; -import { Box } from '@mui/material'; -import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; const initialValues = { wrapInQuotesFlag: false @@ -18,16 +19,18 @@ type InitialValuesType = typeof initialValues; const exampleCards: CardExampleType[] = [ { title: 'Escape a Simple JSON Object', - description: `In this example, we escape all quotes (") around the keys and values in a simple JSON object. This ensures that the JSON data is interpreted correctly if it's used in another JSON object or assigned to a variable as a string.`, + description: + 'In this example, we escape all double quotes in a JSON object. This makes the JSON safe to use as a string inside another JSON object or in source code.', sampleText: `{"country": "Spain", "capital": "Madrid"}`, - sampleResult: `{{\\"country\\": \\"Spain\\", \\"capital\\": \\"Madrid\\"}`, + sampleResult: `{\\"country\\": \\"Spain\\", \\"capital\\": \\"Madrid\\"}`, sampleOptions: { wrapInQuotesFlag: false } }, { title: 'Escape a Complex JSON Object', - description: `In this example, we escape a more complex JSON object with nested elements containing data about the Margherita pizza recipe. We escape all quotes within the object as well as convert all line breaks into special "\n" characters. Additionally, we wrap the entire output in double quotes by enabling the "Wrap Output in Quotes" option.`, + description: + 'In this example, we escape quotes and line breaks from a formatted JSON object. The output is wrapped in double quotes to create a JSON string value.', sampleText: `{ "name": "Pizza Margherita", "ingredients": [ @@ -38,14 +41,15 @@ const exampleCards: CardExampleType[] = [ "price": 12.50, "vegetarian": true }`, - sampleResult: `"{\\n \\"name\\": \\"Pizza Margherita\\",\\n \\"ingredients\\": [\\n\\"tomato sauce\\",\\n \\"mozzarella cheese\\",\\n \\"fresh basil\\"\\n ],\\n \\"price\\": 12.50,\\n \\"vegetarian\\": true\\n}"`, + sampleResult: `"{\\n \\"name\\": \\"Pizza Margherita\\",\\n \\"ingredients\\": [\\n \\"tomato sauce\\",\\n \\"mozzarella cheese\\",\\n \\"fresh basil\\"\\n ],\\n \\"price\\": 12.50,\\n \\"vegetarian\\": true\\n}"`, sampleOptions: { wrapInQuotesFlag: true } }, { - title: 'Escape a JSON Array of Numbers', - description: `This example showcases that escaping isn't necessary for JSON arrays containing only numbers. Since numbers themselves don't hold special meaning in JSON, the tool doesn't modify the input and the output remains the same as the original JSON array.`, + title: 'Escape a JSON Array', + description: + 'This example shows that JSON arrays containing only numbers do not require escaping because they do not contain characters that need special handling.', sampleText: `[1, 2, 3]`, sampleResult: `[1, 2, 3]`, sampleOptions: { @@ -54,10 +58,8 @@ const exampleCards: CardExampleType[] = [ } ]; -export default function EscapeJsonTool({ - title, - longDescription -}: ToolComponentProps) { +export default function EscapeJsonTool({ title }: ToolComponentProps) { + const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); @@ -70,14 +72,14 @@ export default function EscapeJsonTool({ updateField }) => [ { - title: 'Quote Output', + title: t('escapeJson.wrapOutputTitle'), component: ( updateField('wrapInQuotesFlag', val)} checked={values.wrapInQuotesFlag} - title={'Wrap Output In Quotes'} - description={'Add double quotes around the output JSON data.'} + title={t('escapeJson.wrapOutputTitle')} + description={t('escapeJson.wrapOutputDescription')} /> ) @@ -89,7 +91,7 @@ export default function EscapeJsonTool({ title={title} inputComponent={ } initialValues={initialValues} getGroups={getGroups} toolInfo={{ - title: 'What is a JSON Escaper?', - description: longDescription + title: t('escapeJson.title'), + description: t('escapeJson.longDescription') }} exampleCards={exampleCards} input={input} diff --git a/src/pages/tools/json/json-to-csv/index.tsx b/src/pages/tools/json/json-to-csv/index.tsx index 0ac36ed8..4a920f08 100644 --- a/src/pages/tools/json/json-to-csv/index.tsx +++ b/src/pages/tools/json/json-to-csv/index.tsx @@ -11,6 +11,7 @@ import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import SimpleRadio from '@components/options/SimpleRadio'; import { InitialValuesType } from './types'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from 'utils/json'; const initialValues: InitialValuesType = { delimiter: ',', @@ -75,17 +76,17 @@ export default function JsonToCsv({ title }: ToolComponentProps) { const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [inputFormat, setInputFormat] = useState('json'); const compute = (values: InitialValuesType, input: string) => { if (input) { try { - const csvResult = convertJsonToCsv(input, values); - setResult(csvResult); + const { result, inputFormat } = convertJsonToCsv(input, values); + setResult(result); + setInputFormat(inputFormat); } catch (error) { setResult( - `Error: ${ - error instanceof Error ? error.message : 'Invalid JSON format' - }` + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` ); } } @@ -104,7 +105,7 @@ export default function JsonToCsv({ title }: ToolComponentProps) { title={t('jsonToCsv.inputTitle')} value={input} onChange={setInput} - language="json" + language={inputFormat} /> } resultComponent={ diff --git a/src/pages/tools/json/json-to-csv/service.test.ts b/src/pages/tools/json/json-to-csv/service.test.ts index f6a2011c..d457bb6b 100644 --- a/src/pages/tools/json/json-to-csv/service.test.ts +++ b/src/pages/tools/json/json-to-csv/service.test.ts @@ -15,7 +15,7 @@ describe('convertJsonToCsv', () => { { name: 'Bob', age: 25 } ]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,age\r\nAlice,30\r\nBob,25` ); }); @@ -23,7 +23,7 @@ describe('convertJsonToCsv', () => { it('converts a single object', () => { const input = JSON.stringify({ name: 'Alice', age: 30 }); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,age\r\nAlice,30` ); }); @@ -33,6 +33,7 @@ describe('convertJsonToCsv', () => { expect( convertJsonToCsv(input, { ...defaultOptions, includeHeaders: false }) + .result ).toBe(`Alice,30`); }); }); @@ -43,7 +44,7 @@ describe('convertJsonToCsv', () => { { name: 'Alice', address: { city: 'Paris', zip: '75000' } } ]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,address.city,address.zip\r\nAlice,Paris,75000` ); }); @@ -53,7 +54,7 @@ describe('convertJsonToCsv', () => { { name: 'Alice', tags: ['admin', 'user'] } ]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,tags[0],tags[1]\r\nAlice,admin,user` ); }); @@ -63,7 +64,7 @@ describe('convertJsonToCsv', () => { { user: { address: { geo: { lat: 48.8566, lng: 2.3522 } } } } ]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `user.address.geo.lat,user.address.geo.lng\r\n48.8566,2.3522` ); }); @@ -76,7 +77,7 @@ describe('convertJsonToCsv', () => { { name: 'Bob', city: 'Paris' } ]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,age,city\r\nAlice,30,\r\nBob,,Paris` ); }); @@ -84,7 +85,9 @@ describe('convertJsonToCsv', () => { it('filters out empty objects', () => { const input = JSON.stringify([{}, { name: 'Alice' }]); - expect(convertJsonToCsv(input, defaultOptions)).toBe(`name\r\nAlice`); + expect(convertJsonToCsv(input, defaultOptions).result).toBe( + `name\r\nAlice` + ); }); }); @@ -92,7 +95,7 @@ describe('convertJsonToCsv', () => { it('quotes cells containing the delimiter', () => { const input = JSON.stringify([{ name: 'Smith, John' }]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name\r\n"Smith, John"` ); }); @@ -100,7 +103,7 @@ describe('convertJsonToCsv', () => { it('escapes double-quotes by doubling them', () => { const input = JSON.stringify([{ name: 'He said "hello"' }]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name\r\n"He said ""hello"""` ); }); @@ -110,13 +113,14 @@ describe('convertJsonToCsv', () => { expect( convertJsonToCsv(input, { ...defaultOptions, quoteStrings: 'always' }) + .result ).toBe(`"name","age"\r\n"Alice","30"`); }); it('quotes cells containing newlines', () => { const input = JSON.stringify([{ notes: 'line1\nline2' }]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `notes\r\n"line1\nline2"` ); }); @@ -127,7 +131,7 @@ describe('convertJsonToCsv', () => { const input = JSON.stringify([{ name: 'Alice', age: 30 }]); expect( - convertJsonToCsv(input, { ...defaultOptions, delimiter: ';' }) + convertJsonToCsv(input, { ...defaultOptions, delimiter: ';' }).result ).toBe(`name;age\r\nAlice;30`); }); @@ -135,7 +139,7 @@ describe('convertJsonToCsv', () => { const input = JSON.stringify([{ name: 'Alice', age: 30 }]); expect( - convertJsonToCsv(input, { ...defaultOptions, delimiter: '\t' }) + convertJsonToCsv(input, { ...defaultOptions, delimiter: '\t' }).result ).toBe(`name\tage\r\nAlice\t30`); }); }); @@ -144,7 +148,7 @@ describe('convertJsonToCsv', () => { it('converts null values to empty strings', () => { const input = JSON.stringify([{ name: 'Alice', age: null }]); - expect(convertJsonToCsv(input, defaultOptions)).toBe( + expect(convertJsonToCsv(input, defaultOptions).result).toBe( `name,age\r\nAlice,` ); }); @@ -152,9 +156,13 @@ describe('convertJsonToCsv', () => { describe('errors', () => { it('throws on invalid JSON', () => { - expect(() => convertJsonToCsv('invalid json', defaultOptions)).toThrow( - 'Invalid JSON input.' - ); + // A single malformed line isn't NDJSON, so parseJsonInput re-throws + // its own "Invalid JSON: " error (the text itself + // comes from the JS engine's JSON.parse and varies across engines, + // so we only assert on the stable prefix). + expect( + () => convertJsonToCsv('invalid json', defaultOptions).result + ).toThrow(/^Invalid JSON: /); }); it('throws on bare primitive', () => { @@ -164,9 +172,49 @@ describe('convertJsonToCsv', () => { }); it('throws when no data rows are found', () => { - expect(() => - convertJsonToCsv(JSON.stringify([{}, {}]), defaultOptions) + expect( + () => convertJsonToCsv(JSON.stringify([{}, {}]), defaultOptions).result ).toThrow('No data found in the provided JSON.'); }); }); + + describe('NDJSON (newline-delimited JSON)', () => { + it('converts objects on separate lines without an array wrapper', () => { + const input = [ + '{"key1": "AAA", "key2": "XXX"}', + '{"key1": "BBB", "key2": "YYY"}', + '{"key1": "CCC", "key2": "ZZZ"}' + ].join('\n'); + + expect(convertJsonToCsv(input, defaultOptions).result).toBe( + `key1,key2\r\nAAA,XXX\r\nBBB,YYY\r\nCCC,ZZZ` + ); + }); + + it('ignores blank lines between NDJSON records', () => { + const input = '{"a": 1}\n\n{"a": 2}\n'; + + expect(convertJsonToCsv(input, defaultOptions).result).toBe( + `a\r\n1\r\n2` + ); + }); + + it('handles sparse keys across NDJSON records', () => { + const input = '{"a": 1}\n{"b": 2}'; + + expect(convertJsonToCsv(input, defaultOptions).result).toBe( + `a,b\r\n1,\r\n,2` + ); + }); + + it('still throws when one NDJSON line is not valid JSON', () => { + // Two non-blank lines triggers the NDJSON path; the failing line's + // 1-based line number (2) is reported alongside the parse error. + const input = '{"a": 1}\nnot json'; + + expect(() => convertJsonToCsv(input, defaultOptions).result).toThrow( + /^Invalid JSON at line 2: / + ); + }); + }); }); diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index 33ddeb4e..af3b1855 100644 --- a/src/pages/tools/json/json-to-csv/service.ts +++ b/src/pages/tools/json/json-to-csv/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { getJsonHeaders } from 'utils/json'; +import { getJsonHeaders, parseJsonInput, JsonFormat } from 'utils/json'; /** * Recursively flattens any JSON value into a flat object. @@ -79,22 +79,14 @@ function quoteCell(value: string, options: InitialValuesType): string { export function convertJsonToCsv( input: string, options: InitialValuesType -): string { +): { result: string; inputFormat: JsonFormat } { const { delimiter, includeHeaders } = options; if (!delimiter) throw new Error('No CSV delimiter.'); - let parsed: unknown; + const { data, format } = parseJsonInput(input); - try { - parsed = JSON.parse(input); - } catch { - throw new Error('Invalid JSON input.'); - } - - const rows = flattenToRows(parsed).filter( - (row) => Object.keys(row).length > 0 - ); + const rows = flattenToRows(data).filter((row) => Object.keys(row).length > 0); if (rows.length === 0) { throw new Error('No data found in the provided JSON.'); @@ -116,5 +108,5 @@ export function convertJsonToCsv( lines.push(line); } - return lines.join('\r\n'); + return { result: lines.join('\r\n'), inputFormat: format }; } diff --git a/src/pages/tools/json/json-to-xml/index.tsx b/src/pages/tools/json/json-to-xml/index.tsx index 5c20ee22..7437532c 100644 --- a/src/pages/tools/json/json-to-xml/index.tsx +++ b/src/pages/tools/json/json-to-xml/index.tsx @@ -1,18 +1,16 @@ import { useState } from 'react'; import ToolContent from '@components/ToolContent'; import ToolCodeInput from '@components/input/ToolCodeInput'; -import ToolTextResult from '@components/result/ToolTextResult'; +import ToolCodeResult from '@components/result/ToolCodeResult'; import { convertJsonToXml } from './service'; import { CardExampleType } from '@components/examples/ToolExamples'; import { ToolComponentProps } from '@tools/defineTool'; import { Box } from '@mui/material'; import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; import SimpleRadio from '@components/options/SimpleRadio'; - -type InitialValuesType = { - indentationType: 'space' | 'tab' | 'none'; - addMetaTag: boolean; -}; +import { InitialValuesType } from './types'; +import { useTranslation } from 'react-i18next'; +import { JsonFormat } from 'utils/json'; const initialValues: InitialValuesType = { indentationType: 'space', @@ -57,19 +55,20 @@ const exampleCards: CardExampleType[] = [ ]; export default function JsonToXml({ title }: ToolComponentProps) { + const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [inputFormat, setInputFormat] = useState('json'); const compute = (values: InitialValuesType, input: string) => { if (input) { try { - const xmlResult = convertJsonToXml(input, values); - setResult(xmlResult); + const { result, inputFormat } = convertJsonToXml(input, values); + setResult(result); + setInputFormat(inputFormat); } catch (error) { setResult( - `Error: ${ - error instanceof Error ? error.message : 'Invalid Json format' - }` + `${error instanceof Error ? error.message : 'Invalid Json format'}` ); } } @@ -85,14 +84,18 @@ export default function JsonToXml({ title }: ToolComponentProps) { exampleCards={exampleCards} inputComponent={ } resultComponent={ - + } getGroups={({ values, updateField }) => [ { @@ -101,38 +104,34 @@ export default function JsonToXml({ title }: ToolComponentProps) { updateField('indentationType', 'space')} /> updateField('indentationType', 'tab')} /> updateField('indentationType', 'none')} /> ) }, { - title: 'XML Meta Information', + title: t('jsonToXml.options.metaInfoTitle'), component: ( updateField('addMetaTag', value)} - title="Add an XML Meta Tag" - description="Add a meta tag at the beginning of the XML output." + title={t('jsonToXml.options.addMetaTagTitle')} + description={t('jsonToXml.options.addMetaTagDesc')} /> ) diff --git a/src/pages/tools/json/json-to-xml/service.test.ts b/src/pages/tools/json/json-to-xml/service.test.ts new file mode 100644 index 00000000..769a010d --- /dev/null +++ b/src/pages/tools/json/json-to-xml/service.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { convertJsonToXml } from './service'; + +const defaultOptions: Parameters[1] = { + indentationType: 'none', + addMetaTag: false +}; + +describe('convertJsonToXml', () => { + it('converts basic objects to XML', () => { + const result = convertJsonToXml( + JSON.stringify({ name: 'Alice', active: true }), + defaultOptions + ).result; + + expect(result).toBe('Alicetrue'); + }); + + it('normalizes JSON keys into valid XML tag names', () => { + const result = convertJsonToXml( + JSON.stringify({ + 'hello world': 'value', + '1st place': 'gold', + 'avalue<_1st_place>goldxss<_>empty' + ); + }); + + it('guards against excessive JSON nesting', () => { + const input = JSON.stringify(createNestedObject(101)); + + expect(() => convertJsonToXml(input, defaultOptions)).toThrow( + 'JSON nesting exceeds maximum depth of 100.' + ); + }); +}); + +const createNestedObject = (depth: number): object => { + let current: Record = { value: 'end' }; + + for (let index = 0; index < depth; index += 1) { + current = { item: current }; + } + + return current; +}; diff --git a/src/pages/tools/json/json-to-xml/service.ts b/src/pages/tools/json/json-to-xml/service.ts index bbc05c15..8b9bdb09 100644 --- a/src/pages/tools/json/json-to-xml/service.ts +++ b/src/pages/tools/json/json-to-xml/service.ts @@ -1,99 +1,129 @@ -type JsonToXmlOptions = { - indentationType: 'space' | 'tab' | 'none'; - addMetaTag: boolean; -}; +import { InitialValuesType } from './types'; +import { escapeMarkup } from '@utils/string'; +import { normalizeXmlTagName } from '@utils/xml'; +import { parseJsonInput, JsonFormat } from '@utils/json'; + +type JsonObject = Record; + +const MAX_JSON_DEPTH = 100; export const convertJsonToXml = ( json: string, - options: JsonToXmlOptions -): string => { - const obj = JSON.parse(json); - return convertObjectToXml(obj, options); + options: InitialValuesType +): { result: string; inputFormat: JsonFormat } => { + const { data: parsed, format: inputFormat } = parseJsonInput(json); + + if (typeof parsed !== 'object' || parsed === null) { + throw new Error('JSON root value must be an object or array.'); + } + + const chunks: string[] = []; + const newline = options.indentationType === 'none' ? '' : '\n'; + + if (options.addMetaTag) { + chunks.push(`${newline}`); + } + + chunks.push(`${newline}`); + + if (Array.isArray(parsed)) { + parsed.forEach((item) => { + chunks.push(convertArrayItemToXml(item, options, 1)); + }); + } else { + chunks.push(convertObjectToXml(parsed, options, 1)); + } + + chunks.push(''); + + return { result: chunks.join(''), inputFormat: inputFormat }; }; -const getIndentation = (options: JsonToXmlOptions, depth: number): string => { +const convertArrayItemToXml = ( + item: any, + options: InitialValuesType, + depth: number +): string => { + const indentation = getIndentation(options, depth); + const newline = options.indentationType === 'none' ? '' : '\n'; + + if (typeof item === 'object' && item !== null && !Array.isArray(item)) { + return `${indentation}${newline}${convertObjectToXml( + item, + options, + depth + 1 + )}${indentation}${newline}`; + } + + return `${indentation}${escapeMarkup(String(item))}${newline}`; +}; + +const convertObjectToXml = ( + obj: JsonObject, + options: InitialValuesType, + depth: number +): string => { + if (depth > MAX_JSON_DEPTH) { + throw new Error(`JSON nesting exceeds maximum depth of ${MAX_JSON_DEPTH}.`); + } + + const chunks: string[] = []; + const newline = options.indentationType === 'none' ? '' : '\n'; + + for (const [key, value] of Object.entries(obj)) { + const tagName = normalizeXmlTagName(key); + const indentation = getIndentation(options, depth); + + if (value === null) { + chunks.push(`${indentation}<${tagName}>${tagName}>${newline}`); + continue; + } + + if (Array.isArray(value)) { + value.forEach((item) => { + chunks.push(`${indentation}<${tagName}>`); + + if (typeof item === 'object' && item !== null && !Array.isArray(item)) { + chunks.push(newline); + chunks.push(convertObjectToXml(item, options, depth + 1)); + chunks.push(indentation); + } else { + chunks.push(escapeMarkup(String(item))); + } + + chunks.push(`${tagName}>${newline}`); + }); + + continue; + } + + if (typeof value === 'object') { + chunks.push(`${indentation}<${tagName}>${newline}`); + + chunks.push(convertObjectToXml(value, options, depth + 1)); + + chunks.push(`${indentation}${tagName}>${newline}`); + + continue; + } + + chunks.push( + `${indentation}<${tagName}>${escapeMarkup( + String(value) + )}${tagName}>${newline}` + ); + } + + return chunks.join(''); +}; + +const getIndentation = (options: InitialValuesType, depth: number): string => { switch (options.indentationType) { case 'space': - return ' '.repeat(depth + 1); + return ' '.repeat(depth); case 'tab': - return '\t'.repeat(depth + 1); - case 'none': + return '\t'.repeat(depth); default: return ''; } }; - -const convertObjectToXml = ( - obj: any, - options: JsonToXmlOptions, - depth: number = 0 -): string => { - let xml = ''; - - const newline = options.indentationType === 'none' ? '' : '\n'; - - if (depth === 0) { - if (options.addMetaTag) { - xml += '' + newline; - } - xml += '' + newline; - } - - for (const key in obj) { - const value = obj[key]; - const keyString = isNaN(Number(key)) ? key : `row-${key}`; - - // Handle null values - if (value === null) { - xml += `${getIndentation( - options, - depth - )}<${keyString}>${keyString}>${newline}`; - continue; - } - - // Handle arrays - if (Array.isArray(value)) { - value.forEach((item) => { - xml += `${getIndentation(options, depth)}<${keyString}>`; - if (item === null) { - xml += `${keyString}>${newline}`; - } else if (typeof item === 'object') { - xml += `${newline}${convertObjectToXml( - item, - options, - depth + 1 - )}${getIndentation(options, depth)}`; - xml += `${keyString}>${newline}`; - } else { - xml += `${escapeXml(String(item))}${keyString}>${newline}`; - } - }); - continue; - } - - // Handle objects - if (typeof value === 'object') { - xml += `${getIndentation(options, depth)}<${keyString}>${newline}`; - xml += convertObjectToXml(value, options, depth + 1); - xml += `${getIndentation(options, depth)}${keyString}>${newline}`; - continue; - } - - // Handle primitive values (string, number, boolean, etc.) - xml += `${getIndentation(options, depth)}<${keyString}>${escapeXml( - String(value) - )}${keyString}>${newline}`; - } - - return depth === 0 ? `${xml}` : xml; -}; - -const escapeXml = (str: string): string => { - return str - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -}; diff --git a/src/pages/tools/json/json-to-xml/types.ts b/src/pages/tools/json/json-to-xml/types.ts new file mode 100644 index 00000000..e0128f9e --- /dev/null +++ b/src/pages/tools/json/json-to-xml/types.ts @@ -0,0 +1,4 @@ +export type InitialValuesType = { + indentationType: 'space' | 'tab' | 'none'; + addMetaTag: boolean; +}; diff --git a/src/pages/tools/json/minify/index.tsx b/src/pages/tools/json/minify/index.tsx index 379d0f37..4eaebcdc 100644 --- a/src/pages/tools/json/minify/index.tsx +++ b/src/pages/tools/json/minify/index.tsx @@ -1,11 +1,12 @@ import React, { useState } from 'react'; import ToolContent from '@components/ToolContent'; import ToolCodeInput from '@components/input/ToolCodeInput'; -import ToolTextResult from '@components/result/ToolTextResult'; +import ToolCodeResult from '@components/result/ToolCodeResult'; import { minifyJson } from './service'; import { CardExampleType } from '@components/examples/ToolExamples'; import { ToolComponentProps } from '@tools/defineTool'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from '@utils/json'; type InitialValuesType = Record; @@ -51,9 +52,20 @@ export default function MinifyJson({ title }: ToolComponentProps) { const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [format, setFormat] = useState('json'); const compute = (_: InitialValuesType, input: string) => { - if (input) setResult(minifyJson(input)); + if (input) { + try { + const { result, format } = minifyJson(input); + setResult(result); + setFormat(format); + } catch (error) { + setResult( + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` + ); + } + } }; return ( @@ -64,14 +76,14 @@ export default function MinifyJson({ title }: ToolComponentProps) { title={t('minify.inputTitle')} value={input} onChange={setInput} - language="json" + language={format} /> } resultComponent={ - } initialValues={initialValues} diff --git a/src/pages/tools/json/minify/service.ts b/src/pages/tools/json/minify/service.ts index a5bbc50d..a3f133de 100644 --- a/src/pages/tools/json/minify/service.ts +++ b/src/pages/tools/json/minify/service.ts @@ -1,10 +1,19 @@ -export const minifyJson = (text: string) => { - let parsedJson; - try { - parsedJson = JSON.parse(text); - } catch (e) { - throw new Error('Invalid JSON string'); +import { parseJsonInput, JsonFormat } from '@utils/json'; + +export interface MinifyJsonResult { + result: string; + format: JsonFormat; +} + +export const minifyJson = (text: string): MinifyJsonResult => { + const { data, format } = parseJsonInput(text); + + if (format === 'jsonl' && Array.isArray(data)) { + return { + result: data.map((item) => JSON.stringify(item)).join('\n'), + format + }; } - return JSON.stringify(parsedJson); + return { result: JSON.stringify(data), format }; }; diff --git a/src/pages/tools/json/prettify/index.tsx b/src/pages/tools/json/prettify/index.tsx index 0d43d270..54f1bb55 100644 --- a/src/pages/tools/json/prettify/index.tsx +++ b/src/pages/tools/json/prettify/index.tsx @@ -1,25 +1,16 @@ import { Box } from '@mui/material'; -import React, { useRef, useState } from 'react'; +import React, { useState } from 'react'; import ToolCodeInput from '@components/input/ToolCodeInput'; -import ToolTextResult from '@components/result/ToolTextResult'; +import ToolCodeResult from '@components/result/ToolCodeResult'; import { beautifyJson } from './service'; -import ToolInfo from '@components/ToolInfo'; -import Separator from '@components/Separator'; -import ToolExamples, { - CardExampleType -} from '@components/examples/ToolExamples'; -import { FormikProps } from 'formik'; +import { CardExampleType } from '@components/examples/ToolExamples'; import { ToolComponentProps } from '@tools/defineTool'; import RadioWithTextField from '@components/options/RadioWithTextField'; import SimpleRadio from '@components/options/SimpleRadio'; -import { isNumber, updateNumberField } from '../../../../utils/string'; +import { updateNumberField } from '../../../../utils/string'; import ToolContent from '@components/ToolContent'; import { useTranslation } from 'react-i18next'; - -type InitialValuesType = { - indentationType: 'tab' | 'space'; - spacesCount: number; -}; +import { InitialValuesType } from './types'; const initialValues: InitialValuesType = { indentationType: 'space', @@ -121,8 +112,7 @@ export default function PrettifyJson({ title }: ToolComponentProps) { const [result, setResult] = useState(''); const compute = (optionsValues: InitialValuesType, input: any) => { - const { indentationType, spacesCount } = optionsValues; - if (input) setResult(beautifyJson(input, indentationType, spacesCount)); + if (input) setResult(beautifyJson(input, optionsValues)); }; return ( @@ -138,10 +128,10 @@ export default function PrettifyJson({ title }: ToolComponentProps) { /> } resultComponent={ - } initialValues={initialValues} diff --git a/src/pages/tools/json/prettify/service.ts b/src/pages/tools/json/prettify/service.ts index b1f0281e..1f09d1d5 100644 --- a/src/pages/tools/json/prettify/service.ts +++ b/src/pages/tools/json/prettify/service.ts @@ -1,8 +1,7 @@ -export const beautifyJson = ( - text: string, - indentationType: 'tab' | 'space', - spacesCount: number -) => { +import { InitialValuesType } from './types'; +export const beautifyJson = (text: string, options: InitialValuesType) => { + const { indentationType, spacesCount } = options; + let parsedJson; try { parsedJson = JSON.parse(text); diff --git a/src/pages/tools/json/prettify/types.ts b/src/pages/tools/json/prettify/types.ts new file mode 100644 index 00000000..11bc6b81 --- /dev/null +++ b/src/pages/tools/json/prettify/types.ts @@ -0,0 +1,4 @@ +export type InitialValuesType = { + indentationType: 'tab' | 'space' | 'none'; + spacesCount: number; +}; diff --git a/src/pages/tools/json/sort/index.tsx b/src/pages/tools/json/sort/index.tsx index 85677ff0..92dfc9ab 100644 --- a/src/pages/tools/json/sort/index.tsx +++ b/src/pages/tools/json/sort/index.tsx @@ -1,7 +1,7 @@ import { Box } from '@mui/material'; import React, { useState } from 'react'; import ToolCodeInput from '@components/input/ToolCodeInput'; -import ToolTextResult from '@components/result/ToolTextResult'; +import ToolCodeResult from '@components/result/ToolCodeResult'; import { sortJson } from './service'; import { CardExampleType } from '@components/examples/ToolExamples'; import SelectWithDesc from '@components/options/SelectWithDesc'; @@ -11,6 +11,7 @@ import { InitialValuesType } from './types'; import { GetGroupsType } from '@components/options/ToolOptions'; import { getJsonHeaders } from '@utils/json'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from '@utils/json'; const initialValues: InitialValuesType = { mode: 'value', @@ -61,10 +62,20 @@ export default function SortJson({ const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [format, setFormat] = useState('json'); const compute = (values: InitialValuesType, input: string) => { - if (!input.trim()) return; - setResult(sortJson(input, values)); + if (input) { + try { + const { result, format } = sortJson(input, values); + setResult(result); + setFormat(format); + } catch (error) { + setResult( + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` + ); + } + } }; const keys = getJsonHeaders(input); @@ -141,14 +152,14 @@ export default function SortJson({ title={t('sortJson.inputTitle')} value={input} onChange={setInput} - language={'json'} + language={format} /> } resultComponent={ - } initialValues={initialValues} diff --git a/src/pages/tools/json/sort/service.ts b/src/pages/tools/json/sort/service.ts index 1a745390..136451ac 100644 --- a/src/pages/tools/json/sort/service.ts +++ b/src/pages/tools/json/sort/service.ts @@ -1,4 +1,5 @@ -import { order, InitialValuesType } from './types'; +import { order, InitialValuesType, SortJsonResult } from './types'; +import { parseJsonInput, JsonFormat } from '@utils/json'; const sortObject = ( obj: Record, @@ -13,37 +14,50 @@ const sortObject = ( return result; }; -export const sortJson = (text: string, options: InitialValuesType): string => { - const { mode, order, key } = options; - let parsed; - try { - parsed = JSON.parse(text); - } catch (e) { - throw new Error('Invalid JSON string'); +/** + * Serializes the final value back to a string, matching the shape of the + * original input: NDJSON (one compact JSON value per line) for 'jsonl' + * input, pretty-printed JSON otherwise. + */ +const serialize = (value: unknown, format: JsonFormat): string => { + if (format === 'jsonl' && Array.isArray(value)) { + return value.map((item) => JSON.stringify(item)).join('\n'); } + return JSON.stringify(value, null, 2); +}; + +export const sortJson = ( + text: string, + options: InitialValuesType +): SortJsonResult => { + const { mode, order, key } = options; + + const { data, format } = parseJsonInput(text); if (mode === 'key') { - if (Array.isArray(parsed)) { - if (parsed.length === 0) throw new Error('Array is empty'); - return JSON.stringify( - parsed.map((item) => sortObject(item, order)), - null, - 2 + if (Array.isArray(data)) { + if (data.length === 0) throw new Error('Array is empty'); + const sortedArray = data.map((item) => + sortObject(item as Record, order) ); + return { result: serialize(sortedArray, format), format }; } - if (typeof parsed !== 'object' || parsed === null) { + if (typeof data !== 'object' || data === null) { throw new Error('Input must be a JSON object or array of objects'); } - return JSON.stringify(sortObject(parsed, order), null, 2); + return { result: serialize(sortObject(data, order), format), format }; } // value mode - if (!Array.isArray(parsed)) throw new Error('Input must be a JSON array'); - if (parsed.length === 0) throw new Error('Array is empty'); + if (!Array.isArray(data)) throw new Error('Input must be a JSON array'); + if (data.length === 0) throw new Error('Array is empty'); - const sorted = [...parsed].sort((a, b) => { - const aVal = a[key]; - const bVal = b[key]; + const sorted = [...data].sort((a, b) => { + const aRow = a as Record; + const bRow = b as Record; + const aVal = aRow[key]; + const bVal = bRow[key]; + if (aVal == null && bVal == null) return 0; if (aVal == null) return 1; if (bVal == null) return -1; if (typeof aVal === 'object' && typeof bVal === 'object') { @@ -58,5 +72,5 @@ export const sortJson = (text: string, options: InitialValuesType): string => { return 0; }); - return JSON.stringify(sorted, null, 2); + return { result: serialize(sorted, format), format }; }; diff --git a/src/pages/tools/json/sort/types.ts b/src/pages/tools/json/sort/types.ts index a17a255f..bc330fbb 100644 --- a/src/pages/tools/json/sort/types.ts +++ b/src/pages/tools/json/sort/types.ts @@ -1,3 +1,5 @@ +import { JsonFormat } from '@utils/json'; + export type mode = 'value' | 'key'; export type order = 'asc' | 'desc'; @@ -6,3 +8,8 @@ export type InitialValuesType = { key: string; order: order; }; + +export interface SortJsonResult { + result: string; + format: JsonFormat; +} diff --git a/src/pages/tools/json/stringify/index.tsx b/src/pages/tools/json/stringify/index.tsx index e8ba3bf5..2cd2197f 100644 --- a/src/pages/tools/json/stringify/index.tsx +++ b/src/pages/tools/json/stringify/index.tsx @@ -2,20 +2,16 @@ import { Box } from '@mui/material'; import React, { useState } from 'react'; import ToolContent from '@components/ToolContent'; import ToolCodeInput from '@components/input/ToolCodeInput'; -import ToolTextResult from '@components/result/ToolTextResult'; +import ToolCodeResult from '@components/result/ToolCodeResult'; import { stringifyJson } from './service'; import { ToolComponentProps } from '@tools/defineTool'; import RadioWithTextField from '@components/options/RadioWithTextField'; import SimpleRadio from '@components/options/SimpleRadio'; import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; -import { isNumber, updateNumberField } from '@utils/string'; +import { updateNumberField } from '@utils/string'; import { CardExampleType } from '@components/examples/ToolExamples'; - -type InitialValuesType = { - indentationType: 'tab' | 'space'; - spacesCount: number; - escapeHtml: boolean; -}; +import { InitialValuesType } from './types'; +import { useTranslation } from 'react-i18next'; const initialValues: InitialValuesType = { indentationType: 'space', @@ -78,19 +74,19 @@ const exampleCards: CardExampleType[] = [ ]; export default function StringifyJson({ title }: ToolComponentProps) { + const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); const compute = (values: InitialValuesType, input: string) => { if (input) { - setResult( - stringifyJson( - input, - values.indentationType, - values.spacesCount, - values.escapeHtml - ) - ); + try { + setResult(stringifyJson(input, values)); + } catch (error) { + setResult( + `${error instanceof Error ? error.message : 'Invalid Json format'}` + ); + } } }; @@ -104,25 +100,29 @@ export default function StringifyJson({ title }: ToolComponentProps) { exampleCards={exampleCards} inputComponent={ } resultComponent={ - + } getGroups={({ values, updateField }) => [ { - title: 'Indentation', + title: t('stringify.options.indentationTitle'), component: ( updateField('indentationType', 'space')} onTextChange={(val) => @@ -133,27 +133,26 @@ export default function StringifyJson({ title }: ToolComponentProps) { onClick={() => updateField('indentationType', 'tab')} checked={values.indentationType === 'tab'} description="Indent output with tabs" - title="Use Tabs" + title={t('stringify.options.useTabTitle')} /> ) }, { - title: 'Options', + title: t('stringify.options.optionsTitle'), component: ( updateField('escapeHtml', value)} - title="Escape HTML Characters" - description="Convert HTML special characters to their entity references" + title={t('stringify.options.escapeHtmlTitle')} + description={t('stringify.options.escapeHtmlDesc')} /> ) } ]} toolInfo={{ - title: 'What Is JSON Stringify?', - description: - 'JSON Stringify is a tool that converts JavaScript objects and arrays into their JSON string representation. It properly formats the output with customizable indentation and offers the option to escape HTML special characters, making it safe for web usage. This tool is particularly useful when you need to serialize data structures for storage or transmission, or when you need to prepare JSON data for HTML embedding.' + title: t('stringify.toolInfo.title'), + description: t('stringify.toolInfo.description') }} /> ); diff --git a/src/pages/tools/json/stringify/service.ts b/src/pages/tools/json/stringify/service.ts index 1532790f..18359f11 100644 --- a/src/pages/tools/json/stringify/service.ts +++ b/src/pages/tools/json/stringify/service.ts @@ -1,18 +1,21 @@ +import { InitialValuesType } from './types'; +import JSON5 from 'json5'; + export const stringifyJson = ( input: string, - indentationType: 'tab' | 'space', - spacesCount: number, - escapeHtml: boolean + options: InitialValuesType ): string => { + const { indentationType, spacesCount, escapeHtml } = options; let parsedInput; try { - // Safely evaluate the input string as JavaScript - parsedInput = eval('(' + input + ')'); + // Json5 safer than eval + parsedInput = JSON5.parse(input); } catch (e) { throw new Error('Invalid JavaScript object/array'); } const indent = indentationType === 'tab' ? '\t' : ' '.repeat(spacesCount); + let result = JSON.stringify(parsedInput, null, indent); if (escapeHtml) { diff --git a/src/pages/tools/json/stringify/types.ts b/src/pages/tools/json/stringify/types.ts new file mode 100644 index 00000000..f1658c7c --- /dev/null +++ b/src/pages/tools/json/stringify/types.ts @@ -0,0 +1,5 @@ +export type InitialValuesType = { + indentationType: 'tab' | 'space'; + spacesCount: number; + escapeHtml: boolean; +}; diff --git a/src/pages/tools/json/validateJson/index.tsx b/src/pages/tools/json/validateJson/index.tsx index ca8ec1fe..a181c3db 100644 --- a/src/pages/tools/json/validateJson/index.tsx +++ b/src/pages/tools/json/validateJson/index.tsx @@ -6,6 +6,7 @@ import { validateJson } from './service'; import { ToolComponentProps } from '@tools/defineTool'; import ToolContent from '@components/ToolContent'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from '@utils/json'; const exampleCards: CardExampleType<{}>[] = [ { @@ -50,14 +51,18 @@ export default function ValidateJson({ title }: ToolComponentProps) { const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [format, setFormat] = useState('json'); const compute = (options: any, input: string) => { - const { valid, error } = validateJson(input); + if (input) { + const { valid, error, format } = validateJson(input); - if (valid) { - setResult(t('validateJson.validJson')); - } else { - setResult(t('validateJson.invalidJson', { error })); + if (valid) { + setResult(t('validateJson.validJson')); + setFormat(format); + } else { + setResult(t('validateJson.invalidJson', { error })); + } } }; @@ -69,7 +74,7 @@ export default function ValidateJson({ title }: ToolComponentProps) { title={t('validateJson.inputTitle')} value={input} onChange={setInput} - language="json" + language={format ? format : 'json'} /> } resultComponent={ diff --git a/src/pages/tools/json/validateJson/service.ts b/src/pages/tools/json/validateJson/service.ts index 2d53367e..e8aa1477 100644 --- a/src/pages/tools/json/validateJson/service.ts +++ b/src/pages/tools/json/validateJson/service.ts @@ -1,11 +1,13 @@ +import { parseJsonInput, JsonFormat } from '@utils/json'; + export const validateJson = ( input: string -): { valid: boolean; error?: string } => { +): { valid: boolean; error?: string; format?: JsonFormat } => { try { - JSON.parse(input); - return { valid: true }; + const { format } = parseJsonInput(input); + return { valid: true, format: format }; } catch (error) { - if (error instanceof SyntaxError) { + if (error instanceof Error) { return { valid: false, error: error.message }; } return { valid: false, error: 'Unknown error occurred' }; diff --git a/src/pages/tools/number/index.ts b/src/pages/tools/number/index.ts index 90d6f6fe..e72d2f39 100644 --- a/src/pages/tools/number/index.ts +++ b/src/pages/tools/number/index.ts @@ -4,6 +4,7 @@ import { tool as numberSum } from './sum/meta'; import { tool as numberGenerate } from './generate/meta'; import { tool as numberArithmeticSequence } from './arithmetic-sequence/meta'; import { tool as numberByteConverter } from './byte-converter/meta'; +import { tool as numberNumberToWords } from './number-to-words/meta'; import { tools as genericCalcTools } from './generic-calc/meta'; export const numberTools = [ @@ -13,5 +14,6 @@ export const numberTools = [ numberRandomPortGenerator, numberRandomNumberGenerator, numberByteConverter, + numberNumberToWords, ...genericCalcTools ]; diff --git a/src/pages/tools/number/number-to-words/index.tsx b/src/pages/tools/number/number-to-words/index.tsx new file mode 100644 index 00000000..6e933ecb --- /dev/null +++ b/src/pages/tools/number/number-to-words/index.tsx @@ -0,0 +1,124 @@ +import React, { useState } from 'react'; +import ToolContent from '@components/ToolContent'; +import ToolTextInput from '@components/input/ToolTextInput'; +import ToolTextResult from '@components/result/ToolTextResult'; +import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; +import { CardExampleType } from '@components/examples/ToolExamples'; +import { ToolComponentProps } from '@tools/defineTool'; +import { useTranslation } from 'react-i18next'; +import { numberToWords } from './service'; +import { InitialValuesType } from './types'; + +const initialValues: InitialValuesType = { + uppercase: false, + useAnd: true +}; + +const exampleCards: CardExampleType[] = [ + { + title: 'Spell Out a Large Number', + description: + 'This example converts 1,234,567 into words. The output language matches your selected UI language automatically.', + sampleText: `1234567`, + sampleResult: `One Million Two Hundred And Thirty Four Thousand Five Hundred And Sixty Seven`, + sampleOptions: { + uppercase: false, + useAnd: true + } + }, + { + title: 'Convert Decimal Numbers', + description: + 'Decimal numbers are converted with the fractional part read after the decimal point word.', + sampleText: `3.14`, + sampleResult: `Three Point Fourteen`, + sampleOptions: { + uppercase: false, + useAnd: true + } + }, + { + title: 'Uppercase Output for Cheques', + description: + 'Uppercase output is commonly required on bank cheques and legal documents to prevent alteration.', + sampleText: `9500`, + sampleResult: `NINE THOUSAND FIVE HUNDRED`, + sampleOptions: { + uppercase: true, + useAnd: true + } + }, + { + title: 'Batch Convert a List of Numbers', + description: + 'Each line is processed independently, preserving the line structure in the output.', + sampleText: `42 +100 +0 +-7`, + sampleResult: `Forty Two +One Hundred +Zero +Minus Seven`, + sampleOptions: { + uppercase: false, + useAnd: true + } + } +]; + +export default function NumberToWords({ title }: ToolComponentProps) { + const { t } = useTranslation('number'); + const [input, setInput] = useState(''); + const [result, setResult] = useState(''); + + const compute = (optionsValues: InitialValuesType, input: string) => { + setResult(numberToWords(input, optionsValues)); + }; + + return ( + + } + resultComponent={ + + } + getGroups={({ values, updateField }) => [ + { + title: t('numberToWords.options.title'), + component: ( + + updateField('uppercase', value)} + /> + updateField('useAnd', value)} + /> + + ) + } + ]} + compute={compute} + toolInfo={{ + title: t('numberToWords.toolInfo.title'), + description: t('numberToWords.toolInfo.description') + }} + /> + ); +} diff --git a/src/pages/tools/number/number-to-words/meta.ts b/src/pages/tools/number/number-to-words/meta.ts new file mode 100644 index 00000000..b150e147 --- /dev/null +++ b/src/pages/tools/number/number-to-words/meta.ts @@ -0,0 +1,16 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('number', { + path: 'number-to-words', + icon: 'fluent:text-number-format-24-regular', + + keywords: ['number', 'words', 'spell', 'text', 'convert', 'cheque'], + component: lazy(() => import('./index')), + i18n: { + name: 'number:numberToWords.title', + description: 'number:numberToWords.description', + shortDescription: 'number:numberToWords.shortDescription', + userTypes: ['generalUsers'] + } +}); diff --git a/src/pages/tools/number/number-to-words/number-to-words.service.test.ts b/src/pages/tools/number/number-to-words/number-to-words.service.test.ts new file mode 100644 index 00000000..712dbcbc --- /dev/null +++ b/src/pages/tools/number/number-to-words/number-to-words.service.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; +import { numberToWords } from './service'; + +describe('numberToWords', () => { + it('converts zero', () => { + expect(numberToWords('0', { uppercase: false, useAnd: true })).toBe('Zero'); + }); + + it('converts single-digit numbers', () => { + expect(numberToWords('7', { uppercase: false, useAnd: true })).toBe( + 'Seven' + ); + }); + + it('converts teens', () => { + expect(numberToWords('15', { uppercase: false, useAnd: true })).toBe( + 'Fifteen' + ); + }); + + it('converts tens', () => { + expect(numberToWords('42', { uppercase: false, useAnd: true })).toBe( + 'Forty Two' + ); + }); + + it('converts exact tens', () => { + expect(numberToWords('40', { uppercase: false, useAnd: true })).toBe( + 'Forty' + ); + }); + + it('converts hundreds with "and"', () => { + expect(numberToWords('123', { uppercase: false, useAnd: true })).toBe( + 'One Hundred And Twenty Three' + ); + }); + + it('omits "and" when option is disabled', () => { + expect(numberToWords('123', { uppercase: false, useAnd: false })).toBe( + 'One Hundred Twenty Three' + ); + }); + + it('converts large numbers', () => { + expect(numberToWords('1234567', { uppercase: false, useAnd: true })).toBe( + 'One Million Two Hundred And Thirty Four Thousand Five Hundred And Sixty Seven' + ); + }); + + it('handles zero groups within large numbers', () => { + expect(numberToWords('1000001', { uppercase: false, useAnd: true })).toBe( + 'One Million And One' + ); + }); + + it('converts decimal numbers', () => { + expect(numberToWords('3.14', { uppercase: false, useAnd: true })).toBe( + 'Three Point Fourteen' + ); + }); + + it('trims trailing zeros in the fraction', () => { + expect(numberToWords('2.50', { uppercase: false, useAnd: true })).toBe( + 'Two Point Five' + ); + }); + + it('converts negative numbers', () => { + expect(numberToWords('-7', { uppercase: false, useAnd: true })).toBe( + 'Minus Seven' + ); + }); + + it('uppercases the output when enabled', () => { + expect(numberToWords('123', { uppercase: true, useAnd: true })).toBe( + 'ONE HUNDRED AND TWENTY THREE' + ); + }); + + it('processes multiple lines independently', () => { + const input = '1\n2\n3'; + expect(numberToWords(input, { uppercase: false, useAnd: true })).toBe( + 'One\nTwo\nThree' + ); + }); + + it('preserves empty lines', () => { + const input = '5\n\n10'; + expect(numberToWords(input, { uppercase: false, useAnd: true })).toBe( + 'Five\n\nTen' + ); + }); + + it('returns empty string for empty input', () => { + expect(numberToWords('', { uppercase: false, useAnd: true })).toBe(''); + }); + + it('returns empty string for non-numeric input', () => { + expect(numberToWords('hello', { uppercase: false, useAnd: true })).toBe(''); + }); + + it('supports a leading decimal point', () => { + expect(numberToWords('.25', { uppercase: false, useAnd: true })).toBe( + 'Zero Point Twenty Five' + ); + }); + + it('supports a trailing decimal point', () => { + expect(numberToWords('5.', { uppercase: false, useAnd: true })).toBe( + 'Five' + ); + }); + + it('rejects a lone dot', () => { + expect(numberToWords('.', { uppercase: false, useAnd: true })).toBe(''); + }); +}); diff --git a/src/pages/tools/number/number-to-words/service.ts b/src/pages/tools/number/number-to-words/service.ts new file mode 100644 index 00000000..26d325b4 --- /dev/null +++ b/src/pages/tools/number/number-to-words/service.ts @@ -0,0 +1,60 @@ +import { toWords } from 'to-words'; +import { InitialValuesType } from './types'; + +/** + * Maps omni-tools' i18n language codes (stored in localStorage under 'lang') + * to the locale codes expected by the `to-words` package. + * Mirrors the pattern used in tools/time/crontab-guru/service.ts. + */ +const LANG_MAP: Record = { + en: 'en-US', + de: 'de-DE', + es: 'es-ES', + fr: 'fr-FR', + pt: 'pt-BR', + ja: 'ja-JP', + hi: 'hi-IN', + nl: 'nl-NL', + ru: 'ru-RU', + zh: 'zh-CN' +}; + +const getLocaleCode = (): string => { + const lang = localStorage.getItem('lang') || 'en'; + return LANG_MAP[lang] || 'en-US'; +}; + +/** + * Converts each line of the input into words using the `to-words` package. + * The locale is auto-detected from the user's language preference in localStorage, + * so the output matches their selected UI language. + * + * Empty lines are preserved so the output line count matches the input. + */ +export function numberToWords( + input: string, + options: InitialValuesType +): string { + if (!input) return ''; + + const localeCode = getLocaleCode(); + + return input + .split('\n') + .map((line) => { + const trimmed = line.trim(); + if (trimmed === '') return ''; + + try { + let result = toWords(trimmed, { + localeCode, + useAnd: options.useAnd + }); + if (options.uppercase) result = result.toUpperCase(); + return result; + } catch { + return ''; + } + }) + .join('\n'); +} diff --git a/src/pages/tools/number/number-to-words/types.ts b/src/pages/tools/number/number-to-words/types.ts new file mode 100644 index 00000000..f73a3711 --- /dev/null +++ b/src/pages/tools/number/number-to-words/types.ts @@ -0,0 +1,4 @@ +export type InitialValuesType = { + uppercase: boolean; + useAnd: boolean; +}; diff --git a/src/pages/tools/number/random-number-generator/index.tsx b/src/pages/tools/number/random-number-generator/index.tsx index ae4f471b..85fdd4ac 100644 --- a/src/pages/tools/number/random-number-generator/index.tsx +++ b/src/pages/tools/number/random-number-generator/index.tsx @@ -20,6 +20,21 @@ const initialValues: InitialValuesType = { separator: ', ' }; +/** + * Parses a numeric field without silently snapping back to a default. + * Empty or non-numeric input becomes NaN so that validateInput can + * surface a proper, specific error instead of the field just reverting. + */ +const parseNumericField = (value: string): number => { + if (value.trim() === '') { + return NaN; + } + + const parsed = Number(value); + + return Number.isNaN(parsed) ? NaN : parsed; +}; + export default function RandomNumberGenerator({ title, longDescription @@ -35,7 +50,8 @@ export default function RandomNumberGenerator({ setResult(null); setFormattedResult(''); - // Validate input + // Validate input - this is the single source of truth for what + // counts as valid, including range/count/domain-size checks. const validationError = validateInput(values); if (validationError) { setError(validationError); @@ -55,7 +71,13 @@ export default function RandomNumberGenerator({ setFormattedResult(formatted); } catch (err) { console.error('Random number generation failed:', err); - setError(t('randomNumberGenerator.error.generationFailed')); + // Prefer the specific error message when we have one (e.g. thrown + // from generateRandomNumbers), falling back to a generic message + const message = + err instanceof Error && err.message + ? err.message + : t('randomNumberGenerator.error.generationFailed'); + setError(message); } }; @@ -70,7 +92,7 @@ export default function RandomNumberGenerator({ - updateField('minValue', parseInt(value) || 1) + updateField('minValue', parseNumericField(value)) } description={t( 'randomNumberGenerator.options.range.minDescription' @@ -83,7 +105,7 @@ export default function RandomNumberGenerator({ - updateField('maxValue', parseInt(value) || 100) + updateField('maxValue', parseNumericField(value)) } description={t( 'randomNumberGenerator.options.range.maxDescription' @@ -102,7 +124,9 @@ export default function RandomNumberGenerator({ updateField('count', parseInt(value) || 10)} + onOwnChange={(value) => + updateField('count', parseNumericField(value)) + } description={t( 'randomNumberGenerator.options.generation.countDescription' )} diff --git a/src/pages/tools/number/random-number-generator/random-number-generator.service.test.ts b/src/pages/tools/number/random-number-generator/random-number-generator.service.test.ts index ef42d519..451b8eb2 100644 --- a/src/pages/tools/number/random-number-generator/random-number-generator.service.test.ts +++ b/src/pages/tools/number/random-number-generator/random-number-generator.service.test.ts @@ -72,6 +72,44 @@ describe('Random Number Generator Service', () => { expect(uniqueNumbers.size).toBe(3); }); + it('should generate unique decimals within a narrow range without exceeding the max (#404)', () => { + const options: InitialValuesType = { + minValue: 0, + maxValue: 1, + count: 3, + allowDecimals: true, + allowDuplicates: false, + sortResults: false, + separator: ', ' + }; + + const result = generateRandomNumbers(options); + + expect(result.numbers).toHaveLength(3); + expect(new Set(result.numbers).size).toBe(3); + result.numbers.forEach((num) => { + expect(num).toBeGreaterThanOrEqual(0); + expect(num).toBeLessThanOrEqual(1); + }); + }); + + it('should still reject a unique count larger than the decimal domain (#404)', () => { + const options: InitialValuesType = { + minValue: 0, + maxValue: 1, + // hundredths in [0, 1] inclusive give 101 distinct values + count: 102, + allowDecimals: true, + allowDuplicates: false, + sortResults: false, + separator: ', ' + }; + + expect(() => generateRandomNumbers(options)).toThrow( + 'Count exceeds the number of unique values available in this range' + ); + }); + it('should sort results when sortResults is true', () => { const options: InitialValuesType = { minValue: 1, @@ -138,7 +176,7 @@ describe('Random Number Generator Service', () => { }; expect(() => generateRandomNumbers(options)).toThrow( - 'Cannot generate unique numbers: count exceeds available range' + 'Count exceeds the number of unique values available in this range' ); }); }); diff --git a/src/pages/tools/number/random-number-generator/service.ts b/src/pages/tools/number/random-number-generator/service.ts index 104a725d..15a90d5c 100644 --- a/src/pages/tools/number/random-number-generator/service.ts +++ b/src/pages/tools/number/random-number-generator/service.ts @@ -1,11 +1,27 @@ import { InitialValuesType, RandomNumberResult } from './types'; +/** + * Internal precision used for decimal generation (2 = hundredths). + * Change this single constant to support a different precision everywhere. + */ +const DECIMAL_PRECISION = 2; +const DECIMAL_SCALE = 10 ** DECIMAL_PRECISION; + +/** Safety valve for the random-sampling path (rejection sampling). */ +const MAX_SAMPLING_ATTEMPTS_MULTIPLIER = 50; + /** * Generate random numbers within a specified range */ export function generateRandomNumbers( options: InitialValuesType ): RandomNumberResult { + const validationError = validateInput(options); + + if (validationError) { + throw new Error(validationError); + } + const { minValue, maxValue, @@ -15,66 +31,32 @@ export function generateRandomNumbers( sortResults } = options; - if (minValue >= maxValue) { - throw new Error('Minimum value must be less than maximum value'); - } - - if (count <= 0) { - throw new Error('Count must be greater than 0'); - } - - if (!allowDuplicates && count > maxValue - minValue + 1) { - throw new Error( - 'Cannot generate unique numbers: count exceeds available range' - ); - } - const numbers: number[] = []; if (allowDuplicates) { - // Generate random numbers with possible duplicates for (let i = 0; i < count; i++) { - const randomNumber = generateRandomNumber( - minValue, - maxValue, - allowDecimals - ); - numbers.push(randomNumber); + numbers.push(generateRandomNumber(minValue, maxValue, allowDecimals)); } } else { - // Generate unique random numbers - const availableNumbers = new Set(); + const domainSize = getUniqueDomainSize(minValue, maxValue, allowDecimals); - // Create a pool of available numbers - for (let i = minValue; i <= maxValue; i++) { - if (allowDecimals) { - // For decimals, we need to generate more granular values - for (let j = 0; j < 100; j++) { - availableNumbers.add(i + j / 100); - } - } else { - availableNumbers.add(i); - } - } + /** + * If we need only a small part of the domain, + * avoid creating the whole array. + */ + if (count < domainSize / 4) { + numbers.push( + ...generateUniqueRandomValues(minValue, maxValue, count, allowDecimals) + ); + } else { + const domain = buildUniqueDomain(minValue, maxValue, allowDecimals); - const availableArray = Array.from(availableNumbers); + shuffle(domain); - // Shuffle the available numbers - for (let i = availableArray.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); - [availableArray[i], availableArray[j]] = [ - availableArray[j], - availableArray[i] - ]; - } - - // Take the first 'count' numbers - for (let i = 0; i < Math.min(count, availableArray.length); i++) { - numbers.push(availableArray[i]); + numbers.push(...domain.slice(0, count)); } } - // Sort if requested if (sortResults) { numbers.sort((a, b) => a - b); } @@ -84,13 +66,102 @@ export function generateRandomNumbers( min: minValue, max: maxValue, count, - hasDuplicates: !allowDuplicates && hasDuplicatesInArray(numbers), + // Only worth checking when duplicates were actually allowed; + // otherwise they're guaranteed unique by construction. + hasDuplicates: allowDuplicates ? hasDuplicatesInArray(numbers) : false, isSorted: sortResults }; } /** - * Generate a single random number within the specified range + * Calculate the amount of possible unique values + * without creating the domain. + */ +function getUniqueDomainSize( + min: number, + max: number, + allowDecimals: boolean +): number { + if (allowDecimals) { + return ( + Math.round(max * DECIMAL_SCALE) - Math.round(min * DECIMAL_SCALE) + 1 + ); + } + + return Math.floor(max) - Math.ceil(min) + 1; +} + +/** + * Generate unique values using random sampling. + * Optimized when count is small compared to the domain. + * Includes a safety valve in case of unexpectedly high collision rates. + */ +function generateUniqueRandomValues( + min: number, + max: number, + count: number, + allowDecimals: boolean +): number[] { + const result = new Set(); + const maxAttempts = Math.max(count * MAX_SAMPLING_ATTEMPTS_MULTIPLIER, 1000); + let attempts = 0; + + while (result.size < count) { + if (attempts >= maxAttempts) { + // Extremely unlikely given the count < domainSize/4 guard upstream, + // but this prevents an infinite loop if that invariant is ever broken. + throw new Error( + 'Unable to generate enough unique values within a reasonable number of attempts' + ); + } + + result.add(generateRandomNumber(min, max, allowDecimals)); + attempts++; + } + + return [...result]; +} + +/** + * Build bounded unique domain. + * Decimal values use DECIMAL_PRECISION internally. + */ +function buildUniqueDomain( + min: number, + max: number, + allowDecimals: boolean +): number[] { + const domain: number[] = []; + + if (allowDecimals) { + const start = Math.round(min * DECIMAL_SCALE); + const end = Math.round(max * DECIMAL_SCALE); + + for (let value = start; value <= end; value++) { + domain.push(value / DECIMAL_SCALE); + } + } else { + for (let value = Math.ceil(min); value <= Math.floor(max); value++) { + domain.push(value); + } + } + + return domain; +} + +/** + * Fisher-Yates shuffle + */ +function shuffle(array: number[]): void { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + + [array[i], array[j]] = [array[j], array[i]]; + } +} + +/** + * Generate a single random number */ function generateRandomNumber( min: number, @@ -98,24 +169,19 @@ function generateRandomNumber( allowDecimals: boolean ): number { if (allowDecimals) { - return Math.random() * (max - min) + min; - } else { - return Math.floor(Math.random() * (max - min + 1)) + min; + return Number( + (Math.random() * (max - min) + min).toFixed(DECIMAL_PRECISION) + ); } + + return Math.floor(Math.random() * (max - min + 1)) + min; } /** - * Check if an array has duplicate values + * Check duplicate values */ function hasDuplicatesInArray(arr: number[]): boolean { - const seen = new Set(); - for (const num of arr) { - if (seen.has(num)) { - return true; - } - seen.add(num); - } - return false; + return new Set(arr).size !== arr.length; } /** @@ -127,16 +193,27 @@ export function formatNumbers( allowDecimals: boolean ): string { return numbers - .map((num) => (allowDecimals ? num.toFixed(2) : Math.round(num).toString())) + .map((num) => + allowDecimals + ? num.toFixed(DECIMAL_PRECISION) + : Math.round(num).toString() + ) .join(separator); } /** - * Validate input parameters + * Validate input parameters. + * This is the single source of truth for input constraints and is + * enforced both here (for early/explicit checks) and internally by + * generateRandomNumbers (so it's safe to call standalone). */ export function validateInput(options: InitialValuesType): string | null { const { minValue, maxValue, count } = options; + if (Number.isNaN(minValue) || Number.isNaN(maxValue) || Number.isNaN(count)) { + return 'Please enter valid numbers for min, max, and count'; + } + if (minValue >= maxValue) { return 'Minimum value must be less than maximum value'; } @@ -153,5 +230,17 @@ export function validateInput(options: InitialValuesType): string | null { return 'Range cannot exceed 1,000,000'; } + if (!options.allowDuplicates) { + const domainSize = getUniqueDomainSize( + minValue, + maxValue, + options.allowDecimals + ); + + if (count > domainSize) { + return 'Count exceeds the number of unique values available in this range'; + } + } + return null; } diff --git a/src/pages/tools/string/email-extractor/email-extractor.service.test.ts b/src/pages/tools/string/email-extractor/email-extractor.service.test.ts new file mode 100644 index 00000000..6c822823 --- /dev/null +++ b/src/pages/tools/string/email-extractor/email-extractor.service.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { extractEmails } from './service'; + +describe('extractEmails', () => { + it('should extract single email from text', () => { + const input = 'Contact us at hello@example.com'; + const result = extractEmails(input, false); + expect(result).toBe('hello@example.com'); + }); + + it('should extract multiple emails from text', () => { + const input = 'Emails: a@b.com, c@d.org, e@f.net'; + const result = extractEmails(input, false); + expect(result).toBe('a@b.com\nc@d.org\ne@f.net'); + }); + + it('should deduplicate emails when unique is true', () => { + const input = 'test@test.com, test@test.com, other@test.com'; + const result = extractEmails(input, true); + expect(result).toBe('test@test.com\nother@test.com'); + }); + + it('should return empty string for input with no emails', () => { + const input = 'This text has no email addresses.'; + const result = extractEmails(input, false); + expect(result).toBe(''); + }); + + it('should return empty string for empty input', () => { + const result = extractEmails('', false); + expect(result).toBe(''); + }); + + it('should handle emails with subdomains', () => { + const input = 'user@sub.example.com'; + const result = extractEmails(input, false); + expect(result).toBe('user@sub.example.com'); + }); + + it('should handle emails with plus addressing', () => { + const input = 'user+tag@example.com'; + const result = extractEmails(input, false); + expect(result).toBe('user+tag@example.com'); + }); + + it('should handle emails with dots in local part', () => { + const input = 'firstname.lastname@example.com'; + const result = extractEmails(input, false); + expect(result).toBe('firstname.lastname@example.com'); + }); +}); diff --git a/src/pages/tools/string/email-extractor/index.tsx b/src/pages/tools/string/email-extractor/index.tsx new file mode 100644 index 00000000..efe513f9 --- /dev/null +++ b/src/pages/tools/string/email-extractor/index.tsx @@ -0,0 +1,84 @@ +import React, { useState } from 'react'; +import ToolTextInput from '@components/input/ToolTextInput'; +import ToolTextResult from '@components/result/ToolTextResult'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import { extractEmails } from './service'; +import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; +import { CardExampleType } from '@components/examples/ToolExamples'; +import { ToolComponentProps } from '@tools/defineTool'; +import ToolContent from '@components/ToolContent'; +import { useTranslation } from 'react-i18next'; + +const initialValues = { + unique: true +}; + +const exampleCards: CardExampleType[] = [ + { + title: 'Extract Emails from Text', + description: 'Extract all email addresses from a block of text.', + sampleText: + 'Contact us at support@example.com or sales@example.org for more info. You can also reach john.doe@company.co.uk.', + sampleResult: + 'support@example.com\nsales@example.org\njohn.doe@company.co.uk', + sampleOptions: { ...initialValues } + }, + { + title: 'Duplicate Removal', + description: + 'When "Unique results only" is enabled, duplicate emails are removed.', + sampleText: 'admin@test.com, admin@test.com, user@test.com', + sampleResult: 'admin@test.com\nuser@test.com', + sampleOptions: { ...initialValues } + } +]; + +export default function EmailExtractor({ title }: ToolComponentProps) { + const { t } = useTranslation('string'); + const [input, setInput] = useState(''); + const [result, setResult] = useState(''); + + const computeExternal = ( + optionsValues: typeof initialValues, + input: string + ) => { + const { unique } = optionsValues; + setResult(extractEmails(input, unique)); + }; + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: t('emailExtractor.options.title'), + component: [ + updateField('unique', val)} + /> + ] + } + ]; + + return ( + + } + resultComponent={ + + } + exampleCards={exampleCards} + /> + ); +} diff --git a/src/pages/tools/string/email-extractor/meta.ts b/src/pages/tools/string/email-extractor/meta.ts new file mode 100644 index 00000000..76723672 --- /dev/null +++ b/src/pages/tools/string/email-extractor/meta.ts @@ -0,0 +1,15 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('string', { + path: 'email-extractor', + icon: 'material-symbols-light:alternate-email', + keywords: ['email', 'extract', 'address', 'mail'], + component: lazy(() => import('./index')), + i18n: { + name: 'string:emailExtractor.title', + description: 'string:emailExtractor.description', + shortDescription: 'string:emailExtractor.shortDescription', + userTypes: ['generalUsers', 'developers'] + } +}); diff --git a/src/pages/tools/string/email-extractor/service.ts b/src/pages/tools/string/email-extractor/service.ts new file mode 100644 index 00000000..ae02857f --- /dev/null +++ b/src/pages/tools/string/email-extractor/service.ts @@ -0,0 +1,14 @@ +const EMAIL_REGEX = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g; + +export function extractEmails(input: string, unique: boolean): string { + if (!input) return ''; + + const matches = input.match(EMAIL_REGEX); + if (!matches) return ''; + + if (unique) { + return [...new Set(matches)].join('\n'); + } + + return matches.join('\n'); +} diff --git a/src/pages/tools/string/index.ts b/src/pages/tools/string/index.ts index 9b1e62d8..2514ece8 100644 --- a/src/pages/tools/string/index.ts +++ b/src/pages/tools/string/index.ts @@ -22,8 +22,10 @@ import { tool as stringCensor } from './censor/meta'; import { tool as stringPasswordGenerator } from './password-generator/meta'; import { tool as stringEncodeUrl } from './url-encode/meta'; import { tool as stringDecodeUrl } from './url-decode/meta'; +import { tool as stringUrlEditor } from './url-editor/meta'; import { tool as stringCompare } from './text-compare/meta'; import { tool as stringUnicode } from './unicode/meta'; +import { tool as stringEmailExtractor } from './email-extractor/meta'; export const stringTools = [ stringSplit, @@ -48,8 +50,10 @@ export const stringTools = [ stringPasswordGenerator, stringEncodeUrl, stringDecodeUrl, + stringUrlEditor, stringUnicode, stringHiddenCharacterDetector, + stringEmailExtractor, stringCompare, stringSlugGenerator ]; diff --git a/src/pages/tools/string/password-generator/index.tsx b/src/pages/tools/string/password-generator/index.tsx index 9d7f62d1..253241ae 100644 --- a/src/pages/tools/string/password-generator/index.tsx +++ b/src/pages/tools/string/password-generator/index.tsx @@ -77,8 +77,26 @@ export default function PasswordGenerator({ title }: ToolComponentProps) { description={t('passwordGenerator.lengthDesc')} placeholder={t('passwordGenerator.lengthPlaceholder')} value={values.length} - onOwnChange={(val) => updateField('length', val)} + onOwnChange={(val) => { + const length = Number(val); + + if (length > 256) { + updateField('length', '256'); + return; + } + + if (length < 4 && val !== '') { + updateField('length', '4'); + return; + } + + updateField('length', val); + }} type="number" + inputProps={{ + min: 4, + max: 256 + }} /> diff --git a/src/pages/tools/string/password-generator/password-generator.service.test.ts b/src/pages/tools/string/password-generator/password-generator.service.test.ts index e6bb634f..042ab936 100644 --- a/src/pages/tools/string/password-generator/password-generator.service.test.ts +++ b/src/pages/tools/string/password-generator/password-generator.service.test.ts @@ -129,12 +129,6 @@ describe('generatePassword', () => { expect(result).toHaveLength(50); }); - it('should handle edge case with very short length', () => { - const options = { ...initialValues, length: '1' }; - const result = generatePassword(options); - expect(result).toHaveLength(1); - }); - it('should handle negative length', () => { const options = { ...initialValues, length: '-5' }; const result = generatePassword(options); diff --git a/src/pages/tools/string/password-generator/service.ts b/src/pages/tools/string/password-generator/service.ts index fe20a6bd..35f7235a 100644 --- a/src/pages/tools/string/password-generator/service.ts +++ b/src/pages/tools/string/password-generator/service.ts @@ -1,38 +1,75 @@ import type { InitialValuesType } from './initialValues'; +const LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'; +const UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; +const NUMBERS = '0123456789'; +const SYMBOLS = '!@#$%^&*()_+~`|}{[]:;?><,./-='; + +const AMBIGUOUS = new Set(['i', 'I', 'l', '0', 'O']); + +const MAX_PASSWORD_LENGTH = 256; + +function randomChar(chars: string): string { + const array = new Uint32Array(1); + globalThis.crypto.getRandomValues(array); + + return chars[array[0] % chars.length]; +} + +function shuffle(array: string[]): void { + for (let i = array.length - 1; i > 0; i--) { + const random = new Uint32Array(1); + globalThis.crypto.getRandomValues(random); + + const j = random[0] % (i + 1); + + [array[i], array[j]] = [array[j], array[i]]; + } +} + +function removeAmbiguous(chars: string): string { + return [...chars].filter((char) => !AMBIGUOUS.has(char)).join(''); +} + export function generatePassword(options: InitialValuesType): string { - const length = parseInt(options.length || '', 10); - if (isNaN(length) || length <= 0) { + const length = Number.parseInt(options.length || '', 10); + + if (Number.isNaN(length) || length <= 0 || length > MAX_PASSWORD_LENGTH) { return ''; } - let charset = ''; - const lower = 'abcdefghijklmnopqrstuvwxyz'; - const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - const numbers = '0123456789'; - const symbols = '!@#$%^&*()_+~`|}{[]:;?><,./-='; - - if (options.includeLowercase) charset += lower; - if (options.includeUppercase) charset += upper; - if (options.includeNumbers) charset += numbers; - if (options.includeSymbols) charset += symbols; + let pools = [ + options.includeLowercase ? LOWERCASE : '', + options.includeUppercase ? UPPERCASE : '', + options.includeNumbers ? NUMBERS : '', + options.includeSymbols ? SYMBOLS : '' + ].filter(Boolean); if (options.avoidAmbiguous) { - // ambiguous set = i, I, l, 0, O - const ambig = new Set(['i', 'I', 'l', '0', 'O']); - charset = Array.from(charset) - .filter((c) => !ambig.has(c)) - .join(''); + pools = pools.map(removeAmbiguous); } - if (!charset) { - return ''; // nothing to pick from + // Remove empty pools after filtering + pools = pools.filter(Boolean); + + if (pools.length === 0 || length < pools.length) { + return ''; } - let pwd = ''; - for (let i = 0; i < length; i++) { - const idx = Math.floor(Math.random() * charset.length); - pwd += charset[idx]; + const password: string[] = []; + + // Guarantee each selected category appears once + for (const pool of pools) { + password.push(randomChar(pool)); } - return pwd; + + const charset = pools.join(''); + + while (password.length < length) { + password.push(randomChar(charset)); + } + + shuffle(password); + + return password.join(''); } diff --git a/src/pages/tools/string/text-compare/service.ts b/src/pages/tools/string/text-compare/service.ts index 70309055..9565a7e5 100644 --- a/src/pages/tools/string/text-compare/service.ts +++ b/src/pages/tools/string/text-compare/service.ts @@ -1,6 +1,6 @@ import { diffWordsWithSpace, diffChars } from 'diff'; import { level } from './types'; -import { escapeHtml } from 'utils/string'; +import { escapeMarkup } from 'utils/string'; const DIFF_FN = { word: diffWordsWithSpace, @@ -16,7 +16,7 @@ export function compareTextsHtml( const html = diffs .map((part) => { - const val = escapeHtml(part.value).replace(/\n/g, ''); + const val = escapeMarkup(part.value).replace(/\n/g, ''); if (part.added) { return `${val}`; } diff --git a/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx new file mode 100644 index 00000000..61ecbd9a --- /dev/null +++ b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx @@ -0,0 +1,139 @@ +import { useId, useMemo } from 'react'; +import { + Box, + FormControl, + Grid, + InputAdornment, + InputLabel, + MenuItem, + Select, + TextField +} from '@mui/material'; +import { EditableUrlField, ParsedUrl } from './types'; + +const PROTOCOLS = ['https:', 'http:'] as const; + +export type { EditableUrlField as UrlDetailField }; + +function getProtocolOptions(protocol: string): string[] { + if (PROTOCOLS.includes(protocol as (typeof PROTOCOLS)[number])) { + return [...PROTOCOLS]; + } + + return [protocol, ...PROTOCOLS]; +} + +type UrlDetailsEditorProps = { + value: ParsedUrl; + onChange: (field: EditableUrlField, value: string) => void; + labels: { + protocol: string; + host: string; + path: string; + hash: string; + hostPlaceholder: string; + pathPlaceholder: string; + hashPlaceholder: string; + }; +}; + +export default function UrlDetailsEditor({ + value, + onChange, + labels +}: UrlDetailsEditorProps) { + const protocolLabelId = useId(); + const hashValue = value.hash.replace(/^#/, ''); + const protocolOptions = useMemo( + () => getProtocolOptions(value.protocol), + [value.protocol] + ); + + return ( + + + + + {labels.protocol} + onChange('protocol', event.target.value)} + > + {protocolOptions.map((protocol) => ( + + {protocol.replace(':', '')} + + ))} + + + + + + onChange('host', event.target.value)} + InputProps={{ + startAdornment: ( + :// + ) + }} + /> + + + + { + const next = event.target.value.replace(/^\//, ''); + onChange('pathname', next ? `/${next}` : '/'); + }} + InputProps={{ + startAdornment: ( + / + ) + }} + inputProps={{ sx: { pl: 0.5 } }} + /> + + + + { + const next = event.target.value.replace(/^#/, ''); + onChange('hash', next ? `#${next}` : ''); + }} + InputProps={{ + startAdornment: ( + # + ) + }} + inputProps={{ sx: { pl: 0.5 } }} + /> + + + + ); +} diff --git a/src/pages/tools/string/url-editor/index.tsx b/src/pages/tools/string/url-editor/index.tsx new file mode 100644 index 00000000..32bbf214 --- /dev/null +++ b/src/pages/tools/string/url-editor/index.tsx @@ -0,0 +1,265 @@ +import { useCallback, useState } from 'react'; +import { + Alert, + Box, + Button, + IconButton, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography +} from '@mui/material'; +import DeleteIcon from '@mui/icons-material/Delete'; +import AddIcon from '@mui/icons-material/Add'; +import ToolContent from '@components/ToolContent'; +import ToolTextInput from '@components/input/ToolTextInput'; +import ToolTextResult from '@components/result/ToolTextResult'; +import InputHeader from '@components/InputHeader'; +import { ToolComponentProps } from '@tools/defineTool'; +import { useTranslation } from 'react-i18next'; +import UrlDetailsEditor, { UrlDetailField } from './UrlDetailsEditor'; +import { + createQueryParam, + generateUrl, + parseUrl, + URL_PARSE_ERRORS +} from './service'; +import { ParsedUrl } from './types'; + +const initialValues = {}; +const noop = () => {}; + +export default function UrlEditor({ + title, + longDescription +}: ToolComponentProps) { + const { t } = useTranslation('string'); + const [inputUrl, setInputUrl] = useState(''); + const [parsedUrl, setParsedUrl] = useState(null); + const [parseError, setParseError] = useState(null); + + let generatedUrl = ''; + let generateError: string | null = null; + + if (parsedUrl) { + try { + generatedUrl = generateUrl(parsedUrl); + } catch { + generateError = t('urlEditor.invalidUrl'); + } + } + + const handleParse = useCallback(() => { + try { + setParsedUrl(parseUrl(inputUrl)); + setParseError(null); + } catch (error) { + setParsedUrl(null); + if ( + error instanceof Error && + error.message === URL_PARSE_ERRORS.CREDENTIALS + ) { + setParseError(t('urlEditor.credentialsNotSupported')); + } else { + setParseError(t('urlEditor.invalidUrl')); + } + } + }, [inputUrl, t]); + + const handleFieldChange = useCallback( + (field: UrlDetailField, value: string) => { + setParsedUrl((current) => + current ? { ...current, [field]: value } : current + ); + }, + [] + ); + + const handleAddParam = useCallback(() => { + setParsedUrl((current) => + current + ? { ...current, params: [...current.params, createQueryParam()] } + : current + ); + }, []); + + const handleRemoveParam = useCallback((id: string) => { + setParsedUrl((current) => + current + ? { + ...current, + params: current.params.filter((param) => param.id !== id) + } + : current + ); + }, []); + + const handleParamChange = useCallback( + (id: string, field: 'key' | 'value', value: string) => { + setParsedUrl((current) => { + if (!current) return current; + + const params = current.params.map((param) => + param.id === id ? { ...param, [field]: value } : param + ); + + return { ...current, params }; + }); + }, + [] + ); + + return ( + + + + + {t('urlEditor.parseButton')} + + + + {parseError && ( + + {parseError} + + )} + + {parsedUrl && ( + + + + + + + {parsedUrl.params.length > 0 ? ( + + + + {t('urlEditor.key')} + {t('urlEditor.value')} + + {t('urlEditor.delete')} + + + + + {parsedUrl.params.map((param, index) => ( + + + + handleParamChange( + param.id, + 'key', + event.target.value + ) + } + size="small" + fullWidth + inputProps={{ + 'aria-label': t('urlEditor.paramKeyAriaLabel', { + row: index + 1 + }) + }} + /> + + + + handleParamChange( + param.id, + 'value', + event.target.value + ) + } + size="small" + fullWidth + inputProps={{ + 'aria-label': t( + 'urlEditor.paramValueAriaLabel', + { row: index + 1 } + ) + }} + /> + + + handleRemoveParam(param.id)} + size="small" + > + + + + + ))} + + + ) : ( + + {t('urlEditor.noParameters')} + + )} + } + onClick={handleAddParam} + sx={{ mt: 2 }} + > + {t('urlEditor.addParameter')} + + + + {generateError && ( + + {generateError} + + )} + + )} + + } + resultComponent={ + + } + toolInfo={{ + title: t('urlEditor.toolInfo.title', { title }), + description: longDescription + }} + /> + ); +} diff --git a/src/pages/tools/string/url-editor/meta.ts b/src/pages/tools/string/url-editor/meta.ts new file mode 100644 index 00000000..88e7d55f --- /dev/null +++ b/src/pages/tools/string/url-editor/meta.ts @@ -0,0 +1,25 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('string', { + path: 'url-editor', + icon: 'mdi:link-edit', + + keywords: [ + 'url', + 'editor', + 'query', + 'parameters', + 'parse', + 'link', + 'href', + 'search params' + ], + component: lazy(() => import('./index')), + i18n: { + name: 'string:urlEditor.toolInfo.title', + description: 'string:urlEditor.toolInfo.description', + shortDescription: 'string:urlEditor.toolInfo.shortDescription', + longDescription: 'string:urlEditor.toolInfo.longDescription' + } +}); diff --git a/src/pages/tools/string/url-editor/service.ts b/src/pages/tools/string/url-editor/service.ts new file mode 100644 index 00000000..8a0599ef --- /dev/null +++ b/src/pages/tools/string/url-editor/service.ts @@ -0,0 +1,118 @@ +import { ParsedUrl, QueryParam } from './types'; + +export const URL_PARSE_ERRORS = { + INVALID: 'Invalid URL', + CREDENTIALS: 'URLs with credentials are not supported' +} as const; + +let fallbackParamIdCounter = 0; + +function createParamId(): string { + if (globalThis.crypto?.randomUUID) { + return globalThis.crypto.randomUUID(); + } + + fallbackParamIdCounter += 1; + return `param-${fallbackParamIdCounter}-${Date.now()}`; +} + +export function createQueryParam(key = '', value = ''): QueryParam { + return { id: createParamId(), key, value }; +} + +function detectOriginTrailingSlash(input: string, url: URL): boolean { + if (url.pathname !== '/') { + return false; + } + + const beforeQueryOrHash = input.split(/[?#]/)[0]; + const schemeEnd = beforeQueryOrHash.indexOf('://'); + if (schemeEnd === -1) { + return false; + } + + const firstSlashAfterScheme = beforeQueryOrHash.indexOf('/', schemeEnd + 3); + if (firstSlashAfterScheme === -1) { + return false; + } + + return firstSlashAfterScheme === beforeQueryOrHash.length - 1; +} + +export function parseUrl(input: string): ParsedUrl { + const trimmed = input.trim(); + if (!trimmed) { + throw new Error(URL_PARSE_ERRORS.INVALID); + } + + let url: URL; + try { + url = new URL(trimmed); + } catch { + throw new Error(URL_PARSE_ERRORS.INVALID); + } + + if (url.username || url.password) { + throw new Error(URL_PARSE_ERRORS.CREDENTIALS); + } + + const params: QueryParam[] = Array.from(url.searchParams.entries()).map( + ([key, value]) => createQueryParam(key, value) + ); + + return { + protocol: url.protocol, + host: url.host, + pathname: url.pathname, + hash: url.hash, + originTrailingSlash: detectOriginTrailingSlash(trimmed, url), + params + }; +} + +export function generateUrl(parsed: ParsedUrl): string { + const rawProtocol = parsed.protocol || 'https'; + const protocol = rawProtocol.endsWith(':') ? rawProtocol : `${rawProtocol}:`; + const host = parsed.host.trim(); + if (!host) { + throw new Error(URL_PARSE_ERRORS.INVALID); + } + + const checkUrl = new URL(`${protocol}//${host}`); + + if (checkUrl.username || checkUrl.password) { + throw new Error(URL_PARSE_ERRORS.CREDENTIALS); + } + + let pathname = parsed.pathname || '/'; + if (!pathname.startsWith('/')) { + pathname = `/${pathname}`; + } + + let base: string; + if (pathname === '/' && !parsed.originTrailingSlash) { + base = `${protocol}//${host}`; + } else if (pathname === '/') { + base = `${protocol}//${host}/`; + } else { + base = `${protocol}//${host}${pathname}`; + } + + const searchParams = new URLSearchParams(); + parsed.params.forEach(({ key, value }) => { + const trimmedKey = key.trim(); + if (trimmedKey) { + searchParams.append(trimmedKey, value); + } + }); + + const search = searchParams.toString(); + const query = search ? `?${search}` : ''; + + let hash = parsed.hash.trim(); + if (hash && !hash.startsWith('#')) { + hash = `#${hash}`; + } + + return `${base}${query}${hash}`; +} diff --git a/src/pages/tools/string/url-editor/types.ts b/src/pages/tools/string/url-editor/types.ts new file mode 100644 index 00000000..2fd88862 --- /dev/null +++ b/src/pages/tools/string/url-editor/types.ts @@ -0,0 +1,17 @@ +export type EditableUrlField = 'protocol' | 'host' | 'pathname' | 'hash'; + +export interface QueryParam { + id: string; + key: string; + value: string; +} + +export interface ParsedUrl { + protocol: string; + host: string; + pathname: string; + hash: string; + /** True when the input used a trailing slash on an origin-only URL (e.g. https://example.com/) */ + originTrailingSlash: boolean; + params: QueryParam[]; +} diff --git a/src/pages/tools/string/url-editor/url-editor.service.test.ts b/src/pages/tools/string/url-editor/url-editor.service.test.ts new file mode 100644 index 00000000..4867860f --- /dev/null +++ b/src/pages/tools/string/url-editor/url-editor.service.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it, vi } from 'vitest'; +import { generateUrl, parseUrl, URL_PARSE_ERRORS } from './service'; + +function paramEntries(parsed: ReturnType) { + return parsed.params.map(({ key, value }) => ({ key, value })); +} + +describe('url-editor', () => { + it('parses a valid URL with query parameters', () => { + const parsed = parseUrl('https://example.com/search?q=iphone&page=2'); + + expect(parsed.protocol).toBe('https:'); + expect(parsed.host).toBe('example.com'); + expect(parsed.pathname).toBe('/search'); + expect(parsed.hash).toBe(''); + expect(parsed.originTrailingSlash).toBe(false); + expect(paramEntries(parsed)).toEqual([ + { key: 'q', value: 'iphone' }, + { key: 'page', value: '2' } + ]); + }); + + it('parses multiple query parameters', () => { + expect(paramEntries(parseUrl('https://example.com?a=1&b=2&c=3'))).toEqual([ + { key: 'a', value: '1' }, + { key: 'b', value: '2' }, + { key: 'c', value: '3' } + ]); + }); + + it('parses URLs without query parameters', () => { + const parsed = parseUrl('https://example.com'); + + expect(parsed.pathname).toBe('/'); + expect(parsed.originTrailingSlash).toBe(false); + expect(parsed.params).toEqual([]); + }); + + it('tracks trailing slash on origin-only URLs', () => { + expect(parseUrl('https://example.com/').originTrailingSlash).toBe(true); + expect(parseUrl('https://example.com').originTrailingSlash).toBe(false); + }); + + it('tracks trailing slash using input path, not normalized host', () => { + expect(parseUrl('https://example.com:443/').originTrailingSlash).toBe(true); + expect(parseUrl('https://example.com:443').originTrailingSlash).toBe(false); + expect(parseUrl('http://example.com:80/').originTrailingSlash).toBe(true); + }); + + it('preserves unsupported protocols in round-trip generation', () => { + const input = 'ftp://files.example.com/resource'; + expect(generateUrl(parseUrl(input))).toBe(input); + }); + + it('parses URLs with a hash', () => { + const parsed = parseUrl('https://example.com/page#section1'); + + expect(parsed.pathname).toBe('/page'); + expect(parsed.hash).toBe('#section1'); + expect(parsed.originTrailingSlash).toBe(false); + }); + + it('throws for invalid URLs', () => { + expect(() => parseUrl('abc123')).toThrow(URL_PARSE_ERRORS.INVALID); + expect(() => parseUrl('')).toThrow(URL_PARSE_ERRORS.INVALID); + }); + + it('rejects URLs with credentials', () => { + expect(() => parseUrl('https://user:pass@example.com/')).toThrow( + URL_PARSE_ERRORS.CREDENTIALS + ); + }); + + it('generates an updated URL from parsed components', () => { + const parsed = parseUrl('https://example.com/search?q=iphone&page=2'); + parsed.params = parsed.params.map((param, index) => + index === 0 ? { ...param, value: 'samsung' } : { ...param, value: '5' } + ); + + expect(generateUrl(parsed)).toBe( + 'https://example.com/search?q=samsung&page=5' + ); + }); + + it('preserves origin-only URLs without a trailing slash', () => { + expect(generateUrl(parseUrl('https://example.com'))).toBe( + 'https://example.com' + ); + }); + + it('preserves origin-only URLs with a trailing slash', () => { + expect(generateUrl(parseUrl('https://example.com/'))).toBe( + 'https://example.com/' + ); + }); + + it('preserves hash on origin-only URLs without inserting a slash', () => { + expect(generateUrl(parseUrl('https://example.com#top'))).toBe( + 'https://example.com#top' + ); + }); + + it('round-trips URL components', () => { + const input = 'https://example.com/search?q=test&sort=desc#top'; + expect(generateUrl(parseUrl(input))).toBe(input); + }); + + it('generates URL with edited host and path', () => { + const parsed = parseUrl('https://example.com/search?q=test'); + parsed.host = 'github.com'; + parsed.pathname = '/topics/open-source'; + + expect(generateUrl(parsed)).toBe( + 'https://github.com/topics/open-source?q=test' + ); + }); + + it('normalizes path without a leading slash', () => { + const parsed = parseUrl('https://example.com/search'); + parsed.pathname = 'topics/open-source'; + + expect(generateUrl(parsed)).toBe('https://example.com/topics/open-source'); + }); + + it('normalizes hash without a leading hash symbol', () => { + const parsed = parseUrl('https://example.com/page'); + parsed.hash = 'section1'; + + expect(generateUrl(parsed)).toBe('https://example.com/page#section1'); + }); + + it('ignores whitespace-only query keys', () => { + const parsed = parseUrl('https://example.com?q=test'); + parsed.params.push({ + id: 'temp-id', + key: ' ', + value: 'ignored' + }); + + expect(generateUrl(parsed)).toBe('https://example.com?q=test'); + }); + + it('throws when host is empty', () => { + const parsed = parseUrl('https://example.com'); + parsed.host = ' '; + + expect(() => generateUrl(parsed)).toThrow(URL_PARSE_ERRORS.INVALID); + }); + + it('throws when host contains credentials', () => { + const parsed = parseUrl('https://example.com'); + parsed.host = 'user:pass@example.com'; + + expect(() => generateUrl(parsed)).toThrow(URL_PARSE_ERRORS.CREDENTIALS); + }); + + it('creates query param ids without randomUUID', () => { + vi.stubGlobal('crypto', { randomUUID: undefined }); + + try { + const parsed = parseUrl('https://example.com?q=test'); + expect(parsed.params[0]?.id).toMatch(/^param-\d+-\d+$/); + } finally { + vi.unstubAllGlobals(); + } + }); +}); diff --git a/src/pages/tools/time/date-weekday-calculator/date-weekday-calculator.service.test.ts b/src/pages/tools/time/date-weekday-calculator/date-weekday-calculator.service.test.ts new file mode 100644 index 00000000..3a37fd3e --- /dev/null +++ b/src/pages/tools/time/date-weekday-calculator/date-weekday-calculator.service.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest'; +import { + DATE_WEEKDAY_ERRORS, + findMatchingYears, + formatMatchingYearsResult, + parseAndFindMatchingYears +} from './service'; + +describe('date-weekday-calculator', () => { + it('finds multiple matching years for a normal date', () => { + const result = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2000, + endYear: 2050 + }); + + expect(result.count).toBe(7); + expect(result.matches.map((match) => match.year)).toEqual([ + 2004, 2010, 2021, 2027, 2032, 2038, 2049 + ]); + expect(result.matches[2]?.formatted).toBe('Friday, July 23, 2021'); + expect(result.matches[2]?.date).toBeInstanceOf(Date); + }); + + it('includes February 29 only in leap years that match the weekday', () => { + const result = findMatchingYears({ + month: 2, + day: 29, + weekday: 'monday', + startYear: 2000, + endYear: 2100 + }); + + expect(result.matches.map((match) => match.year)).toEqual([ + 2016, 2044, 2072 + ]); + expect(result.matches[0]?.formatted).toBe('Monday, February 29, 2016'); + }); + + it('rejects invalid dates like April 31', () => { + expect(() => + findMatchingYears({ + month: 4, + day: 31, + weekday: 'monday', + startYear: 2000, + endYear: 2050 + }) + ).toThrow(DATE_WEEKDAY_ERRORS.INVALID_DATE); + }); + + it('returns empty results when nothing matches', () => { + const result = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2022, + endYear: 2022 + }); + + expect(result.count).toBe(0); + expect(result.matches).toEqual([]); + expect(formatMatchingYearsResult(result)).toBe( + 'No matching years found in the selected range.' + ); + }); + + it('rejects invalid year ranges', () => { + expect(() => + findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2050, + endYear: 2000 + }) + ).toThrow(DATE_WEEKDAY_ERRORS.INVALID_YEAR_RANGE); + }); + + it('rejects years outside 1–9999', () => { + expect(() => + findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 0, + endYear: 2000 + }) + ).toThrow(DATE_WEEKDAY_ERRORS.INVALID_YEAR); + + expect(() => + findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2000, + endYear: 10000 + }) + ).toThrow(DATE_WEEKDAY_ERRORS.INVALID_YEAR); + }); + + it('handles boundary years when start equals end', () => { + const match = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2021, + endYear: 2021 + }); + expect(match.count).toBe(1); + expect(match.matches[0]?.year).toBe(2021); + + const miss = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2022, + endYear: 2022 + }); + expect(miss.count).toBe(0); + }); + + it('handles years below 100 without the Date 1900-offset', () => { + const result = findMatchingYears({ + month: 1, + day: 1, + weekday: 'saturday', + startYear: 50, + endYear: 50 + }); + + expect(result.matches.map((match) => match.year)).toEqual([50]); + expect(result.matches[0]?.date.getFullYear()).toBe(50); + }); + + it('handles the far end of the supported range', () => { + const result = findMatchingYears({ + month: 12, + day: 31, + weekday: 'friday', + startYear: 9999, + endYear: 9999 + }); + + expect(result.count).toBe(1); + expect(result.matches[0]?.year).toBe(9999); + }); + + it('rejects empty string inputs when parsing', () => { + expect(() => + parseAndFindMatchingYears({ + month: '7', + day: '23', + weekday: 'friday', + startYear: '', + endYear: '2050' + }) + ).toThrow(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + }); + + it('rejects non-integer numeric strings when parsing', () => { + expect(() => + parseAndFindMatchingYears({ + month: '7.5', + day: '23', + weekday: 'friday', + startYear: '2000', + endYear: '2050' + }) + ).toThrow(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + }); + + it('formats a summary with matching years', () => { + const result = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2021, + endYear: 2027 + }); + + expect(formatMatchingYearsResult(result)).toBe( + 'Found 2 matching years\n\nFriday, July 23, 2021\nFriday, July 23, 2027' + ); + }); + + it('formats a singular summary for one match', () => { + const result = findMatchingYears({ + month: 7, + day: 23, + weekday: 'friday', + startYear: 2021, + endYear: 2021 + }); + + expect(formatMatchingYearsResult(result)).toBe( + 'Found 1 matching year\n\nFriday, July 23, 2021' + ); + }); +}); diff --git a/src/pages/tools/time/date-weekday-calculator/index.tsx b/src/pages/tools/time/date-weekday-calculator/index.tsx new file mode 100644 index 00000000..f9b60b73 --- /dev/null +++ b/src/pages/tools/time/date-weekday-calculator/index.tsx @@ -0,0 +1,252 @@ +import { Box } from '@mui/material'; +import { useState } from 'react'; +import ToolContent from '@components/ToolContent'; +import ToolTextResult from '@components/result/ToolTextResult'; +import SelectWithDesc from '@components/options/SelectWithDesc'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; +import { CardExampleType } from '@components/examples/ToolExamples'; +import { ToolComponentProps } from '@tools/defineTool'; +import { useTranslation } from 'react-i18next'; +import { + DATE_WEEKDAY_ERRORS, + formatMatchingYearsResult, + parseAndFindMatchingYears, + MAX_DAY_BY_MONTH +} from './service'; +import { InitialValuesType, Weekday } from './types'; + +const initialValues: InitialValuesType = { + month: '7', + day: '23', + weekday: 'friday', + startYear: '2000', + endYear: '2050' +}; + +const MONTH_VALUES = [ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12' +] as const; + +const getDayOptions = (month: string) => { + const maxDay = MAX_DAY_BY_MONTH[Number(month) - 1] ?? 31; + + return Array.from({ length: maxDay }, (_, index) => { + const day = String(index + 1); + return { value: day, label: day }; + }); +}; + +const WEEKDAY_VALUES: Weekday[] = [ + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday' +]; + +const ERROR_I18N_KEYS = { + [DATE_WEEKDAY_ERRORS.INVALID_MONTH]: + 'dateWeekdayCalculator.errors.invalidMonth', + [DATE_WEEKDAY_ERRORS.INVALID_DAY]: 'dateWeekdayCalculator.errors.invalidDay', + [DATE_WEEKDAY_ERRORS.INVALID_DATE]: + 'dateWeekdayCalculator.errors.invalidDate', + [DATE_WEEKDAY_ERRORS.INVALID_WEEKDAY]: + 'dateWeekdayCalculator.errors.invalidWeekday', + [DATE_WEEKDAY_ERRORS.INVALID_YEAR]: + 'dateWeekdayCalculator.errors.invalidYear', + [DATE_WEEKDAY_ERRORS.INVALID_YEAR_RANGE]: + 'dateWeekdayCalculator.errors.invalidYearRange', + [DATE_WEEKDAY_ERRORS.EMPTY_INPUT]: 'dateWeekdayCalculator.errors.emptyInput' +} as const; + +const exampleCards: CardExampleType[] = [ + { + title: 'July 23 on Friday', + description: + 'Find every year between 2000 and 2050 where July 23 falls on a Friday.', + sampleOptions: { + month: '7', + day: '23', + weekday: 'friday', + startYear: '2000', + endYear: '2050' + }, + sampleResult: `Found 7 matching years + +Friday, July 23, 2004 +Friday, July 23, 2010 +Friday, July 23, 2021 +Friday, July 23, 2027 +Friday, July 23, 2032 +Friday, July 23, 2038 +Friday, July 23, 2049` + }, + { + title: 'Leap day on Monday', + description: + 'Find leap days (February 29) that fall on a Monday between 2000 and 2100. Non-leap years are skipped automatically.', + sampleOptions: { + month: '2', + day: '29', + weekday: 'monday', + startYear: '2000', + endYear: '2100' + }, + sampleResult: `Found 3 matching years + +Monday, February 29, 2016 +Monday, February 29, 2044 +Monday, February 29, 2072` + }, + { + title: 'Single-year range', + description: 'Check whether a specific year matches the selected weekday.', + sampleOptions: { + month: '7', + day: '23', + weekday: 'friday', + startYear: '2021', + endYear: '2021' + }, + sampleResult: `Found 1 matching year + +Friday, July 23, 2021` + } +]; + +export default function DateWeekdayCalculator({ + title, + longDescription +}: ToolComponentProps) { + const { t } = useTranslation('time'); + const [result, setResult] = useState(''); + + const monthOptions = MONTH_VALUES.map((value) => ({ + value, + label: t(`dateWeekdayCalculator.months.${value}`) + })); + + const weekdayOptions = WEEKDAY_VALUES.map((value) => ({ + value, + label: t(`dateWeekdayCalculator.weekdays.${value}`) + })); + + return ( + + } + initialValues={initialValues} + exampleCards={exampleCards} + toolInfo={{ + title: t('dateWeekdayCalculator.toolInfo.title', { title }), + description: longDescription + }} + getGroups={({ values, updateField }) => { + const dayOptions = getDayOptions(values.month); + + return [ + { + title: t('dateWeekdayCalculator.dateSelection'), + component: ( + + { + updateField('month', value); + + // Clamp the selected day down if it no longer fits + // the newly selected month (e.g. switching from + // January 31 to February should land on 29, not + // leave an out-of-range day selected). + const newMaxDay = MAX_DAY_BY_MONTH[Number(value) - 1]; + if (newMaxDay && Number(values.day) > newMaxDay) { + updateField('day', String(newMaxDay)); + } + }} + options={monthOptions} + /> + updateField('day', value)} + options={dayOptions} + /> + + ) + }, + { + title: t('dateWeekdayCalculator.weekdaySelection'), + component: ( + updateField('weekday', value)} + options={weekdayOptions} + /> + ) + }, + { + title: t('dateWeekdayCalculator.yearRange'), + component: ( + + updateField('startYear', value)} + type="number" + /> + updateField('endYear', value)} + type="number" + /> + + ) + } + ]; + }} + compute={(values) => { + try { + const matches = parseAndFindMatchingYears(values); + setResult( + formatMatchingYearsResult(matches, { + noMatches: t('dateWeekdayCalculator.noMatches'), + foundMatches: (count) => + t('dateWeekdayCalculator.foundMatches', { count }) + }) + ); + } catch (error) { + if (!(error instanceof Error)) { + setResult(t('dateWeekdayCalculator.errors.fallback')); + return; + } + + const key = + ERROR_I18N_KEYS[error.message as keyof typeof ERROR_I18N_KEYS]; + setResult(key ? t(key) : t('dateWeekdayCalculator.errors.fallback')); + } + }} + /> + ); +} diff --git a/src/pages/tools/time/date-weekday-calculator/meta.ts b/src/pages/tools/time/date-weekday-calculator/meta.ts new file mode 100644 index 00000000..b72d2d12 --- /dev/null +++ b/src/pages/tools/time/date-weekday-calculator/meta.ts @@ -0,0 +1,26 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('time', { + path: 'date-weekday-calculator', + icon: 'material-symbols:calendar-month', + + keywords: [ + 'date', + 'weekday', + 'day of week', + 'calendar', + 'year', + 'matching years', + 'what day', + 'leap day' + ], + component: lazy(() => import('./index')), + i18n: { + name: 'time:dateWeekdayCalculator.title', + description: 'time:dateWeekdayCalculator.description', + shortDescription: 'time:dateWeekdayCalculator.shortDescription', + longDescription: 'time:dateWeekdayCalculator.longDescription', + userTypes: ['generalUsers'] + } +}); diff --git a/src/pages/tools/time/date-weekday-calculator/service.ts b/src/pages/tools/time/date-weekday-calculator/service.ts new file mode 100644 index 00000000..968183b9 --- /dev/null +++ b/src/pages/tools/time/date-weekday-calculator/service.ts @@ -0,0 +1,183 @@ +import dayjs from 'dayjs'; +import { + FindMatchingYearsInput, + FindMatchingYearsResult, + MatchingYear, + Weekday +} from './types'; + +export const DATE_WEEKDAY_ERRORS = { + INVALID_MONTH: 'Month must be between 1 and 12', + INVALID_DAY: 'Day must be between 1 and 31', + INVALID_DATE: 'Invalid day for the selected month', + INVALID_WEEKDAY: 'Invalid weekday', + INVALID_YEAR: 'Years must be integers between 1 and 9999', + INVALID_YEAR_RANGE: 'Start year must be less than or equal to end year', + EMPTY_INPUT: 'All fields are required' +} as const; + +const WEEKDAY_TO_DAYJS: Record = { + sunday: 0, + monday: 1, + tuesday: 2, + wednesday: 3, + thursday: 4, + friday: 5, + saturday: 6 +}; + +/** Max valid day per month; February allows 29 (skipped in non-leap years). */ +export const MAX_DAY_BY_MONTH = [ + 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 +]; + +const MIN_YEAR = 1; +const MAX_YEAR = 9999; + +function isWeekday(value: string): value is Weekday { + return value in WEEKDAY_TO_DAYJS; +} + +function createDate(year: number, month: number, day: number): Date { + const date = new Date(year, month - 1, day); + // The Date constructor maps years 0-99 to 1900-1999, so set the year explicitly. + date.setFullYear(year); + return date; +} + +/** False when the day overflowed into the next month, e.g. Feb 29 in a non-leap year. */ +function dateExists( + date: Date, + year: number, + month: number, + day: number +): boolean { + return ( + date.getFullYear() === year && + date.getMonth() === month - 1 && + date.getDate() === day + ); +} + +export function findMatchingYears( + input: FindMatchingYearsInput +): FindMatchingYearsResult { + const { month, day, weekday, startYear, endYear } = input; + + if ( + !Number.isFinite(month) || + !Number.isFinite(day) || + !Number.isFinite(startYear) || + !Number.isFinite(endYear) + ) { + throw new Error(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + } + + if (!Number.isInteger(month) || month < 1 || month > 12) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_MONTH); + } + + if (!Number.isInteger(day) || day < 1 || day > 31) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_DAY); + } + + if (day > MAX_DAY_BY_MONTH[month - 1]) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_DATE); + } + + if (!isWeekday(weekday)) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_WEEKDAY); + } + + if ( + !Number.isInteger(startYear) || + !Number.isInteger(endYear) || + startYear < MIN_YEAR || + endYear > MAX_YEAR || + startYear > MAX_YEAR || + endYear < MIN_YEAR + ) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_YEAR); + } + + if (startYear > endYear) { + throw new Error(DATE_WEEKDAY_ERRORS.INVALID_YEAR_RANGE); + } + + const targetWeekday = WEEKDAY_TO_DAYJS[weekday]; + const matches: MatchingYear[] = []; + + for (let year = startYear; year <= endYear; year += 1) { + const date = createDate(year, month, day); + + if ( + !dateExists(date, year, month, day) || + date.getDay() !== targetWeekday + ) { + continue; + } + + matches.push({ + year, + date, + formatted: dayjs(date).format('dddd, MMMM D, YYYY') + }); + } + + return { matches, count: matches.length }; +} + +export type FormatMatchingYearsMessages = { + noMatches: string; + foundMatches: (count: number) => string; +}; + +export function formatMatchingYearsResult( + result: FindMatchingYearsResult, + messages: FormatMatchingYearsMessages = { + noMatches: 'No matching years found in the selected range.', + foundMatches: (count) => + count === 1 ? 'Found 1 matching year' : `Found ${count} matching years` + } +): string { + if (result.count === 0) { + return messages.noMatches; + } + + return `${messages.foundMatches(result.count)}\n\n${result.matches + .map((match) => match.formatted) + .join('\n')}`; +} + +function parseRequiredInt(value: string): number { + const trimmed = value.trim(); + if (trimmed === '') { + throw new Error(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + } + if (!/^\d+$/.test(trimmed)) { + throw new Error(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + } + return Number.parseInt(trimmed, 10); +} + +export function parseAndFindMatchingYears(values: { + month: string; + day: string; + weekday: string; + startYear: string; + endYear: string; +}): FindMatchingYearsResult { + const weekday = values.weekday.trim(); + + if (weekday === '') { + throw new Error(DATE_WEEKDAY_ERRORS.EMPTY_INPUT); + } + + return findMatchingYears({ + month: parseRequiredInt(values.month), + day: parseRequiredInt(values.day), + weekday: weekday as Weekday, + startYear: parseRequiredInt(values.startYear), + endYear: parseRequiredInt(values.endYear) + }); +} diff --git a/src/pages/tools/time/date-weekday-calculator/types.ts b/src/pages/tools/time/date-weekday-calculator/types.ts new file mode 100644 index 00000000..f207ff59 --- /dev/null +++ b/src/pages/tools/time/date-weekday-calculator/types.ts @@ -0,0 +1,35 @@ +export type Weekday = + | 'sunday' + | 'monday' + | 'tuesday' + | 'wednesday' + | 'thursday' + | 'friday' + | 'saturday'; + +export interface FindMatchingYearsInput { + month: number; + day: number; + weekday: Weekday; + startYear: number; + endYear: number; +} + +export interface MatchingYear { + year: number; + date: Date; + formatted: string; +} + +export interface FindMatchingYearsResult { + matches: MatchingYear[]; + count: number; +} + +export type InitialValuesType = { + month: string; + day: string; + weekday: Weekday; + startYear: string; + endYear: string; +}; diff --git a/src/pages/tools/time/index.ts b/src/pages/tools/time/index.ts index 9a51a611..3d44e8d0 100644 --- a/src/pages/tools/time/index.ts +++ b/src/pages/tools/time/index.ts @@ -9,6 +9,7 @@ import { tool as convertTimetoSeconds } from './convert-time-to-seconds/meta'; import { tool as truncateClockTime } from './truncate-clock-time/meta'; import { tool as checkLeapYear } from './check-leap-years/meta'; import { tool as discordTimestamp } from './discord-timestamp/meta'; +import { tool as dateWeekdayCalculator } from './date-weekday-calculator/meta'; export const timeTools = [ daysDoHours, @@ -21,5 +22,6 @@ export const timeTools = [ checkLeapYear, timeConvertUnixToDate, timeConvertTimeToDecimal, - discordTimestamp + discordTimestamp, + dateWeekdayCalculator ]; diff --git a/src/pages/tools/video/add-audio/index.tsx b/src/pages/tools/video/add-audio/index.tsx index 2fb769fc..fd6a5028 100644 --- a/src/pages/tools/video/add-audio/index.tsx +++ b/src/pages/tools/video/add-audio/index.tsx @@ -12,7 +12,7 @@ import SelectWithDesc from '@components/options/SelectWithDesc'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { useTranslation } from 'react-i18next'; import { addAudioToVideo } from './service'; -import { AudioMode, timingMode, initialValuesType } from './types'; +import { AudioMode, initialValuesType } from './types'; import debounce from 'lodash/debounce'; const initialValues: initialValuesType = { diff --git a/src/pages/tools/video/add-audio/service.ts b/src/pages/tools/video/add-audio/service.ts index 21b157df..5941d1ff 100644 --- a/src/pages/tools/video/add-audio/service.ts +++ b/src/pages/tools/video/add-audio/service.ts @@ -1,39 +1,39 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { initialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - -async function ensureLoaded() { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } -} - export function timeToSeconds(time: string): number { const parts = time.split(':').map(Number); - if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2]; - if (parts.length === 2) return parts[0] * 60 + parts[1]; + + if (parts.length === 3) { + return parts[0] * 3600 + parts[1] * 60 + parts[2]; + } + + if (parts.length === 2) { + return parts[0] * 60 + parts[1]; + } + return parts[0] || 0; } function hasDurationConstraint(options: initialValuesType): boolean { const start = timeToSeconds(options.startTime); const end = timeToSeconds(options.endTime); + return start > 0 || end > 0; } function buildAudioFilterChain(options: initialValuesType): string { const volumeScale = (options.volume / 100).toFixed(2); + const start = timeToSeconds(options.startTime); const end = timeToSeconds(options.endTime); + const hasConstraint = start > 0 || end > 0; const delay = start * 1000; const filters: string[] = []; + filters.push(`volume=${volumeScale}`); if (hasConstraint) { @@ -45,6 +45,7 @@ function buildAudioFilterChain(options: initialValuesType): string { } else if (end > 0) { filters.push(`atrim=start=0:end=${end}`); } + filters.push('apad'); } @@ -64,72 +65,77 @@ export async function addAudioToVideo( audio: File, options: initialValuesType ): Promise { - await ensureLoaded(); + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputVideo = tempFile('.mp4'); + const inputAudio = tempFile('.mp3'); + const outputName = tempFile('.mp4'); - const inputVideo = 'input.mp4'; - const inputAudio = 'input-audio.mp3'; - const outputName = 'output.mp4'; + await ffmpeg.writeFile(inputVideo, await fetchFile(video)); - await ffmpeg.writeFile(inputVideo, await fetchFile(video)); - await ffmpeg.writeFile(inputAudio, await fetchFile(audio)); + await ffmpeg.writeFile(inputAudio, await fetchFile(audio)); - const audioModeFilter = buildAudioModeFilter(options); + const audioModeFilter = buildAudioModeFilter(options); - const inputArgs: string[] = []; - inputArgs.push('-i', inputVideo); - if (options.loop) { - inputArgs.push('-stream_loop', '-1'); - } - inputArgs.push('-i', inputAudio); + const inputArgs: string[] = ['-i', inputVideo]; - const hasConstraint = hasDurationConstraint(options); + if (options.loop) { + inputArgs.push('-stream_loop', '-1'); + } - let args: string[]; + inputArgs.push('-i', inputAudio); - if (options.mode === 'replace') { - args = [ - ...inputArgs, - '-c:v', - 'copy', - '-filter_complex', - audioModeFilter, - '-map', - '0:v:0', - '-map', - '[aout]', - '-shortest', - '-y', - outputName - ]; - } else { - args = [ - ...inputArgs, - '-c:v', - 'copy', - '-filter_complex', - audioModeFilter, - '-map', - '0:v', - '-map', - '[aout]', - ...(hasConstraint ? [] : ['-shortest']), - '-y', - outputName - ]; - } + const hasConstraint = hasDurationConstraint(options); - try { - await ffmpeg.exec(args); - const data = await ffmpeg.readFile(outputName); - return new File( - [new Blob([data as any], { type: 'video/mp4' })], - `${video.name.replace(/\.[^/.]+$/, '')}_with_audio.mp4`, - { type: 'video/mp4' } - ); - } catch (error) { - console.error('FFmpeg execution failed:', error); - throw error; - } finally { - await ffmpeg.deleteFile(outputName); - } + const args = + options.mode === 'replace' + ? [ + ...inputArgs, + '-c:v', + 'copy', + '-filter_complex', + audioModeFilter, + '-map', + '0:v:0', + '-map', + '[aout]', + '-shortest', + '-y', + outputName + ] + : [ + ...inputArgs, + '-c:v', + 'copy', + '-filter_complex', + audioModeFilter, + '-map', + '0:v', + '-map', + '[aout]', + ...(hasConstraint ? [] : ['-shortest']), + '-y', + outputName + ]; + + try { + await ffmpeg.exec(args); + + const data = await ffmpeg.readFile(outputName); + + return new File( + [ + new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }) + ], + `${video.name.replace(/\.[^/.]+$/, '')}_with_audio.mp4`, + { + type: 'video/mp4' + } + ); + } catch (error) { + console.error('FFmpeg execution failed:', error); + throw error; + } + }); } diff --git a/src/pages/tools/video/change-speed/index.tsx b/src/pages/tools/video/change-speed/index.tsx index 12acee92..02bc772b 100644 --- a/src/pages/tools/video/change-speed/index.tsx +++ b/src/pages/tools/video/change-speed/index.tsx @@ -1,143 +1,67 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; +import { Box, Slider, Typography } from '@mui/material'; +import React, { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import { InitialValuesType } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; import ToolFileResult from '@components/result/ToolFileResult'; -import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { ChangeVideoSpeed } from './service'; import { useTranslation } from 'react-i18next'; +import debounce from 'lodash/debounce'; const initialValues: InitialValuesType = { - newSpeed: 2 + speed: 2 }; -export default function ChangeSpeed({ - title, - longDescription -}: ToolComponentProps) { +export default function ChangeSpeed({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); - // FFmpeg only supports a tempo between 0.5 and 2.0, so we chain filters - const computeAudioFilter = (speed: number): string => { - if (speed <= 2 && speed >= 0.5) { - return `atempo=${speed}`; - } - - // Break into supported chunks - const filters: string[] = []; - let remainingSpeed = speed; - while (remainingSpeed > 2.0) { - filters.push('atempo=2.0'); - remainingSpeed /= 2.0; - } - while (remainingSpeed < 0.5) { - filters.push('atempo=0.5'); - remainingSpeed /= 0.5; - } - filters.push(`atempo=${remainingSpeed.toFixed(2)}`); - - return filters.join(','); - }; - - const compute = (optionsValues: InitialValuesType, input: File | null) => { + const compute = async ( + optionsValues: InitialValuesType, + input: File | null + ) => { if (!input) return; - const { newSpeed } = optionsValues; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; - const processVideo = async ( - file: File, - newSpeed: number - ): Promise => { - if (newSpeed === 0) return; + try { setLoading(true); - - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - // Write file to FFmpeg FS - const fileName = file.name; - const outputName = 'output.mp4'; - - try { - ffmpeg.writeFile(fileName, await fetchFile(file)); - - const videoFilter = `setpts=${1 / newSpeed}*PTS`; - const audioFilter = computeAudioFilter(newSpeed); - - // Run FFmpeg command - await ffmpeg.exec([ - '-i', - fileName, - '-vf', - videoFilter, - '-filter:a', - audioFilter, - '-c:v', - 'libx264', - '-preset', - 'ultrafast', - '-c:a', - 'aac', - outputName - ]); - - const data = await ffmpeg.readFile(outputName); - - // Create new file from processed data - const blob = new Blob([data as any], { type: 'video/mp4' }); - const newFile = new File( - [blob], - file.name.replace('.mp4', `-${newSpeed}x.mp4`), - { type: 'video/mp4' } - ); - - // Clean up to free memory - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - - setResult(newFile); - } catch (err) { - console.error(`Failed to process video: ${err}`); - throw err; - } finally { - setLoading(false); - } - }; - - // Here we set the output video - processVideo(input, newSpeed); + const resultFile = await ChangeVideoSpeed(input, optionsValues); + setResult(resultFile); + } catch (error) { + console.error('Conversion failed:', error); + setResult(null); + } finally { + setLoading(false); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField }) => [ { - title: t('changeSpeed.newVideoSpeed'), + title: t('changeSpeed.options'), component: ( - updateField('newSpeed', Number(val))} - description={t('changeSpeed.defaultMultiplier')} - type="number" + + {t('changeSpeed.speedLabel')} {values.speed} + + + updateField('speed', Array.isArray(value) ? value[0] : value) + } + min={0.25} + max={4} + step={0.25} + valueLabelDisplay="auto" + valueLabelFormat={(value) => `x ${value}`} + sx={{ mt: 1 }} /> ) @@ -155,27 +79,20 @@ export default function ChangeSpeed({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} - compute={compute} + compute={debouncedCompute} toolInfo={{ title: t('changeSpeed.toolInfo.title', { title }), - description: longDescription + description: t('changeSpeed.toolInfo.longDescription', { title }) }} /> ); diff --git a/src/pages/tools/video/change-speed/service.ts b/src/pages/tools/video/change-speed/service.ts index 18d6dd6f..1dc8d35e 100644 --- a/src/pages/tools/video/change-speed/service.ts +++ b/src/pages/tools/video/change-speed/service.ts @@ -1,8 +1,75 @@ import { InitialValuesType } from './types'; +import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; +import { getFileExtension } from '@utils/file'; -export function main( - input: File | null, +const computeAudioFilter = (speed: number): string => { + if (speed >= 0.5 && speed <= 2) { + return `atempo=${speed}`; + } + + const filters: string[] = []; + let remainingSpeed = speed; + + while (remainingSpeed > 2) { + filters.push('atempo=2.0'); + remainingSpeed /= 2; + } + + while (remainingSpeed < 0.5) { + filters.push('atempo=0.5'); + remainingSpeed /= 0.5; + } + + filters.push(`atempo=${remainingSpeed.toFixed(2)}`); + + return filters.join(','); +}; + +export const ChangeVideoSpeed = async ( + file: File, options: InitialValuesType -): File | null { - return input; -} +): Promise => { + const { speed } = options; + + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const extension = getFileExtension(file.name); + + const fileName = tempFile(extension ? `.${extension}` : ''); + + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(fileName, await fetchFile(file)); + + const videoFilter = `setpts=${1 / speed}*PTS`; + const audioFilter = computeAudioFilter(speed); + + await ffmpeg.exec([ + '-i', + fileName, + '-vf', + videoFilter, + '-filter:a', + audioFilter, + '-c:v', + 'libx264', + '-preset', + 'ultrafast', + '-c:a', + 'aac', + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }); + + const baseName = file.name.replace(/\.[^/.]+$/, ''); + + return new File([blob], `${baseName}-${speed}x.mp4`, { + type: 'video/mp4' + }); + }); +}; diff --git a/src/pages/tools/video/change-speed/types.ts b/src/pages/tools/video/change-speed/types.ts index 9c748637..bb19b97f 100644 --- a/src/pages/tools/video/change-speed/types.ts +++ b/src/pages/tools/video/change-speed/types.ts @@ -1,3 +1,3 @@ export type InitialValuesType = { - newSpeed: number; + speed: number; }; diff --git a/src/pages/tools/video/compress/index.tsx b/src/pages/tools/video/compress/index.tsx index 069466fc..5440974e 100644 --- a/src/pages/tools/video/compress/index.tsx +++ b/src/pages/tools/video/compress/index.tsx @@ -7,16 +7,16 @@ import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; -import { compressVideo, VideoResolution } from './service'; +import { compressVideo } from './service'; +import { InitialValuesType } from './types'; import SimpleRadio from '@components/options/SimpleRadio'; import Slider from 'rc-slider'; import 'rc-slider/assets/index.css'; import { useTranslation } from 'react-i18next'; -export const initialValues = { - width: 480 as VideoResolution, - crf: 23, - preset: 'medium' +export const initialValues: InitialValuesType = { + width: 480, + crf: 23 }; export const validationSchema = Yup.object({ @@ -29,26 +29,13 @@ export const validationSchema = Yup.object({ crf: Yup.number() .min(0, 'CRF must be at least 0') .max(51, 'CRF must be at most 51') - .required('CRF is required'), - preset: Yup.string() - .oneOf( - [ - 'ultrafast', - 'superfast', - 'veryfast', - 'faster', - 'fast', - 'medium', - 'slow', - 'slower', - 'veryslow' - ], - 'Preset must be a valid ffmpeg preset' - ) - .required('Preset is required') + .required('CRF is required') }); -const resolutionOptions: { value: VideoResolution; label: string }[] = [ +const resolutionOptions: { + value: InitialValuesType['width']; + label: string; +}[] = [ { value: 240, label: '240p' }, { value: 360, label: '360p' }, { value: 480, label: '480p' }, @@ -56,18 +43,6 @@ const resolutionOptions: { value: VideoResolution; label: string }[] = [ { value: 1080, label: '1080p' } ]; -const presetOptions = [ - { value: 'ultrafast', label: 'Ultrafast (Lowest Quality, Smallest Size)' }, - { value: 'superfast', label: 'Superfast' }, - { value: 'veryfast', label: 'Very Fast' }, - { value: 'faster', label: 'Faster' }, - { value: 'fast', label: 'Fast' }, - { value: 'medium', label: 'Medium (Balanced)' }, - { value: 'slow', label: 'Slow' }, - { value: 'slower', label: 'Slower' }, - { value: 'veryslow', label: 'Very Slow (Highest Quality, Largest Size)' } -]; - export default function CompressVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); @@ -82,11 +57,7 @@ export default function CompressVideo({ title }: ToolComponentProps) { setLoading(true); try { - const compressedFile = await compressVideo(input, { - width: optionsValues.width, - crf: optionsValues.crf, - preset: optionsValues.preset - }); + const compressedFile = await compressVideo(input, optionsValues); setResult(compressedFile); } catch (error) { console.error('Error compressing video:', error); @@ -139,19 +110,6 @@ export default function CompressVideo({ title }: ToolComponentProps) { ) } - // { - // title: 'Encoding Preset', - // component: ( - // updateField('preset', value)} - // options={presetOptions} - // description={ - // 'Determines the compression speed. Slower presets provide better compression (quality per filesize) but take more time.' - // } - // /> - // ) - // } ]; return ( diff --git a/src/pages/tools/video/compress/service.ts b/src/pages/tools/video/compress/service.ts index 73838c7a..8dbf6bc5 100644 --- a/src/pages/tools/video/compress/service.ts +++ b/src/pages/tools/video/compress/service.ts @@ -1,60 +1,48 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; - -const ffmpeg = new FFmpeg(); - -export type VideoResolution = 240 | 360 | 480 | 720 | 1080; - -export interface CompressVideoOptions { - width: VideoResolution; - crf: number; // Constant Rate Factor (quality): lower = better quality, higher = smaller file - preset: string; // Encoding speed preset -} +import { InitialValuesType } from './types'; export async function compressVideo( input: File, - options: CompressVideoOptions + options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; + await ffmpeg.writeFile(inputName, await fetchFile(input)); - await ffmpeg.writeFile(inputName, await fetchFile(input)); + // Calculate height as -1 to maintain aspect ratio + const scaleFilter = `scale=${options.width}:-2`; - // Calculate height as -1 to maintain aspect ratio - const scaleFilter = `scale=${options.width}:-2`; + const args = [ + '-i', + inputName, + '-vf', + scaleFilter, + '-c:v', + 'libx264', + '-crf', + options.crf.toString(), + '-c:a', + 'aac', + '-b:a', + '128k', + outputName + ]; - const args = [ - '-i', - inputName, - '-vf', - scaleFilter, - '-c:v', - 'libx264', - '-crf', - options.crf.toString(), - '-preset', - options.preset, - '-c:a', - 'aac', // Copy audio stream - outputName - ]; - - try { await ffmpeg.exec(args); - } catch (error) { - console.error('FFmpeg execution failed:', error); - } - const compressedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([compressedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_compressed_${options.width}p.mp4`, - { type: 'video/mp4' } - ); + + const compressedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(compressedData as Uint8Array)], { + type: 'video/mp4' + }); + + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_compressed_${options.width}p.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/compress/types.ts b/src/pages/tools/video/compress/types.ts new file mode 100644 index 00000000..a197ac8c --- /dev/null +++ b/src/pages/tools/video/compress/types.ts @@ -0,0 +1,6 @@ +export type VideoResolution = 240 | 360 | 480 | 720 | 1080; + +export type InitialValuesType = { + width: VideoResolution; + crf: number; +}; diff --git a/src/pages/tools/video/crop-video/index.tsx b/src/pages/tools/video/crop-video/index.tsx index 939bb95d..61066a8f 100644 --- a/src/pages/tools/video/crop-video/index.tsx +++ b/src/pages/tools/video/crop-video/index.tsx @@ -1,5 +1,5 @@ import { Box, Typography, TextField, Alert } from '@mui/material'; -import React, { useState, useCallback } from 'react'; +import React, { useState, useMemo, useEffect } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { cropVideo, getVideoDimensions } from './service'; @@ -19,14 +19,17 @@ const initialValues: InitialValuesType = { export default function CropVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); + const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); + const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number; } | null>(null); - const [processingError, setProcessingError] = useState(''); + + const [processingError, setProcessingError] = useState(''); const validateDimensions = (values: InitialValuesType): string => { if (!videoDimensions) return ''; @@ -61,6 +64,7 @@ export default function CropVideo({ title }: ToolComponentProps) { if (!input) return; const error = validateDimensions(optionsValues); + if (error) { setProcessingError(error); return; @@ -80,87 +84,146 @@ export default function CropVideo({ title }: ToolComponentProps) { } }; - // 2 seconds to avoid starting job half way through - const debouncedCompute = useCallback(debounce(compute, 2000), [ - videoDimensions - ]); + const debouncedCompute = useMemo( + () => debounce(compute, 2000), + [videoDimensions] + ); + + useEffect(() => { + return () => { + debouncedCompute.cancel(); + }; + }, [debouncedCompute]); const getGroups: GetGroupsType = ({ values, updateField - }) => [ - { - title: t('cropVideo.videoInformation'), - component: ( - - {videoDimensions ? ( - - {t('cropVideo.videoDimensions', { - width: videoDimensions.width, - height: videoDimensions.height - })} - - ) : ( - - {t('cropVideo.loadVideoForDimensions')} - - )} - - ) - }, - { - title: t('cropVideo.cropCoordinates'), - component: ( - - {processingError && ( - - {processingError} - - )} - - updateField('x', parseInt(e.target.value) || 0)} - size="small" - inputProps={{ min: 0 }} - /> - updateField('y', parseInt(e.target.value) || 0)} - size="small" - inputProps={{ min: 0 }} - /> + }) => { + const maxVideoWidth = videoDimensions?.width ?? 0; + const maxVideoHeight = videoDimensions?.height ?? 0; + + const maxX = videoDimensions + ? Math.max(0, maxVideoWidth - values.width) + : 0; + + const maxY = videoDimensions + ? Math.max(0, maxVideoHeight - values.height) + : 0; + + return [ + { + title: t('cropVideo.videoInformation'), + component: ( + + {videoDimensions ? ( + + {t('cropVideo.videoDimensions', { + width: videoDimensions.width, + height: videoDimensions.height + })} + + ) : ( + + {t('cropVideo.loadVideoForDimensions')} + + )} - - - updateField('width', parseInt(e.target.value) || 0) - } - size="small" - inputProps={{ min: 1 }} - /> - - updateField('height', parseInt(e.target.value) || 0) - } - size="small" - inputProps={{ min: 1 }} - /> + ) + }, + { + title: t('cropVideo.cropCoordinates'), + component: ( + + {processingError && ( + {processingError} + )} + + + + updateField( + 'x', + Math.max(0, Math.min(maxX, Number(e.target.value) || 0)) + ) + } + size="small" + inputProps={{ + min: 0, + max: maxX + }} + disabled={!videoDimensions} + /> + + + updateField( + 'y', + Math.max(0, Math.min(maxY, Number(e.target.value) || 0)) + ) + } + size="small" + inputProps={{ + min: 0, + max: maxY + }} + disabled={!videoDimensions} + /> + + + + { + const width = Math.max( + 1, + Math.min(maxVideoWidth, Number(e.target.value) || 1) + ); + + updateField('width', width); + updateField('x', Math.min(values.x, maxVideoWidth - width)); + }} + size="small" + inputProps={{ + min: 1, + max: maxVideoWidth + }} + disabled={!videoDimensions} + /> + + { + const height = Math.max( + 1, + Math.min(maxVideoHeight, Number(e.target.value) || 1) + ); + + updateField('height', height); + updateField('y', Math.min(values.y, maxVideoHeight - height)); + }} + size="small" + inputProps={{ + min: 1, + max: maxVideoHeight + }} + disabled={!videoDimensions} + /> + - - ) - } - ]; + ) + } + ]; + }; return ( { - const newOptions: InitialValuesType = { - x: dimensions.width / 4, - y: dimensions.height / 4, - width: dimensions.width / 2, - height: dimensions.height / 2 + const newValues: InitialValuesType = { + x: Math.floor(dimensions.width / 4), + y: Math.floor(dimensions.height / 4), + width: Math.floor(dimensions.width / 2), + height: Math.floor(dimensions.height / 2) }; - setFieldValue('x', newOptions.x); - setFieldValue('y', newOptions.y); - setFieldValue('width', newOptions.width); - setFieldValue('height', newOptions.height); + + setFieldValue('x', newValues.x); + setFieldValue('y', newValues.y); + setFieldValue('width', newValues.width); + setFieldValue('height', newValues.height); setVideoDimensions(dimensions); setProcessingError(''); }) - .catch((error) => { - console.error('Error getting video dimensions:', error); + .catch(() => { setProcessingError(t('cropVideo.errorLoadingDimensions')); }); } else { setVideoDimensions(null); setProcessingError(''); } + setInput(video); }} title={t('cropVideo.inputTitle')} /> )} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/crop-video/service.ts b/src/pages/tools/video/crop-video/service.ts index de664ad3..704537f5 100644 --- a/src/pages/tools/video/crop-video/service.ts +++ b/src/pages/tools/video/crop-video/service.ts @@ -1,9 +1,7 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function getVideoDimensions( file: File ): Promise<{ width: number; height: number }> { @@ -32,36 +30,37 @@ export async function cropVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args = []; + + if (options.width <= 0 || options.height <= 0) { + throw new Error('Width and height must be positive'); + } + + args.push('-i', inputName); + args.push( + '-vf', + `crop=${options.width}:${options.height}:${options.x}:${options.y}` + ); + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const croppedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(croppedData as Uint8Array)], { + type: 'video/mp4' }); - } - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const args = []; - - if (options.width <= 0 || options.height <= 0) { - throw new Error('Width and height must be positive'); - } - - args.push('-i', inputName); - args.push( - '-vf', - `crop=${options.width}:${options.height}:${options.x}:${options.y}` - ); - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const croppedData = await ffmpeg.readFile(outputName); - return await new File( - [new Blob([croppedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_cropped.mp4`, - { type: 'video/mp4' } - ); + return await new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_cropped.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/flip/index.tsx b/src/pages/tools/video/flip/index.tsx index eef36b1c..60e98de1 100644 --- a/src/pages/tools/video/flip/index.tsx +++ b/src/pages/tools/video/flip/index.tsx @@ -90,20 +90,12 @@ export default function FlipVideo({ title }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/flip/service.ts b/src/pages/tools/video/flip/service.ts index 37f53d47..0a7d4556 100644 --- a/src/pages/tools/video/flip/service.ts +++ b/src/pages/tools/video/flip/service.ts @@ -1,43 +1,41 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { FlipOrientation } from './types'; -const ffmpeg = new FFmpeg(); +const flipMap: Record = { + horizontal: 'hflip', + vertical: 'vflip' +}; export async function flipVideo( input: File, orientation: FlipOrientation ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const flipFilter = flipMap[orientation]; + + const args = ['-i', inputName]; + if (flipFilter) { + args.push('-vf', flipFilter); + } + + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const flippedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(flippedData as Uint8Array)], { + type: 'video/mp4' }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const flipMap: Record = { - horizontal: 'hflip', - vertical: 'vflip' - }; - const flipFilter = flipMap[orientation]; - - const args = ['-i', inputName]; - if (flipFilter) { - args.push('-vf', flipFilter); - } - - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const flippedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([flippedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_flipped.mp4`, - { type: 'video/mp4' } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_flipped.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/gif/change-speed/index.tsx b/src/pages/tools/video/gif/change-speed/index.tsx index 1970412f..c37e93d2 100644 --- a/src/pages/tools/video/gif/change-speed/index.tsx +++ b/src/pages/tools/video/gif/change-speed/index.tsx @@ -1,98 +1,72 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; +import { Box, Typography, Slider } from '@mui/material'; +import React, { useState, useCallback } from 'react'; import ToolFileResult from '@components/result/ToolFileResult'; -import TextFieldWithDesc from 'components/options/TextFieldWithDesc'; import ToolContent from '@components/ToolContent'; +import { GetGroupsType } from '@components/options/ToolOptions'; import { ToolComponentProps } from '@tools/defineTool'; import ToolImageInput from '@components/input/ToolImageInput'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { InitialValuesType } from './types'; +import { changeGifSpeed } from './service'; +import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; -const initialValues = { - newSpeed: 2 +const initialValues: InitialValuesType = { + speed: 2 }; export default function ChangeSpeed({ title }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); - const compute = (optionsValues: typeof initialValues, input: File | null) => { + const compute = async ( + optionsValues: InitialValuesType, + input: File | null + ) => { if (!input) return; - const { newSpeed } = optionsValues; - // Initialize FFmpeg once in your component/app - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; + setLoading(true); - const processImage = async ( - file: File, - newSpeed: number - ): Promise => { - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - try { - await ffmpeg.writeFile('input.gif', await fetchFile(file)); - - // Process the GIF to change playback speed while preserving quality - // The filter_complex does three main operations: - // 1. [0:v]setpts=${1/newSpeed}*PTS - Adjusts frame timing: - // - PTS (Presentation Time Stamp) controls when each frame is displayed - // - Dividing by speed factor (e.g., 2 for 2x speed) reduces display time - // - Example: 1/2 = 0.5 → frames show for half their normal duration - // 2. split[a][b] - Creates two identical streams for parallel processing: - // - [a] goes to palettegen to create an optimized color palette - // - [b] contains the speed-adjusted frames - // 3. [b][p]paletteuse - Applies the generated palette to maintain: - // - Color accuracy - // - Transparency handling - // - Reduced file size - // This approach prevents visual artifacts that occur with simple re-encoding - await ffmpeg.exec([ - '-i', - 'input.gif', - '-filter_complex', - `[0:v]setpts=${ - 1 / newSpeed - }*PTS,split[a][b];[a]palettegen[p];[b][p]paletteuse`, - '-f', - 'gif', - 'output.gif' - ]); - - // Read the result - const data = await ffmpeg.readFile('output.gif'); - - // Create a new file from the processed data - const blob = new Blob([data as any], { type: 'image/gif' }); - const newFile = new File( - [blob], - file.name.replace('.gif', `-${newSpeed}x.gif`), - { - type: 'image/gif' - } - ); - - // Clean up to free memory - await ffmpeg.deleteFile('input.gif'); - await ffmpeg.deleteFile('output.gif'); - - setResult(newFile); - } catch (error) { - console.error('Error processing GIF:', error); - throw error; - } - }; - - processImage(input, newSpeed); + try { + const resultFile = await changeGifSpeed(input, optionsValues); + setResult(resultFile); + } catch (error) { + console.error('Error while processing video:', error); + } finally { + setLoading(false); + } }; + + const debouncedCompute = useCallback(debounce(compute, 1000), []); + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: t('gif.changeSpeed.options.title'), + component: ( + + + + {t('gif.changeSpeed.options.speedLabel')} {values.speed} + + + updateField('speed', Array.isArray(value) ? value[0] : value) + } + min={0.25} + max={4} + step={0.25} + valueLabelDisplay="auto" + valueLabelFormat={(value) => `x ${value}`} + sx={{ mt: 1 }} + /> + + + ) + } + ]; return ( } resultComponent={ } initialValues={initialValues} - getGroups={({ values, updateField }) => [ - { - title: 'New GIF speed', - component: ( - - updateField('newSpeed', Number(val))} - description={'Default multiplier: 2 means 2x faster'} - type={'number'} - /> - - ) - } - ]} - compute={compute} + getGroups={getGroups} + compute={debouncedCompute} setInput={setInput} /> ); diff --git a/src/pages/tools/video/gif/change-speed/service.ts b/src/pages/tools/video/gif/change-speed/service.ts new file mode 100644 index 00000000..3ac4bf74 --- /dev/null +++ b/src/pages/tools/video/gif/change-speed/service.ts @@ -0,0 +1,39 @@ +import { runFFmpegTask } from 'lib/ffmpeg'; +import { fetchFile } from '@ffmpeg/util'; +import { InitialValuesType } from './types'; + +export const changeGifSpeed = async ( + input: File, + options: InitialValuesType +): Promise => { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.gif'); + const outputName = tempFile('.gif'); + + const { speed } = options; + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + inputName, + '-filter_complex', + `[0:v]setpts=${ + 1 / speed + }*PTS,split[a][b];[a]palettegen[p];[b][p]paletteuse`, + '-f', + 'gif', + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'image/gif' + }); + + return new File([blob], input.name.replace('.gif', `-${speed}x.gif`), { + type: 'image/gif' + }); + }); +}; diff --git a/src/pages/tools/video/gif/change-speed/types.ts b/src/pages/tools/video/gif/change-speed/types.ts new file mode 100644 index 00000000..bb19b97f --- /dev/null +++ b/src/pages/tools/video/gif/change-speed/types.ts @@ -0,0 +1,3 @@ +export type InitialValuesType = { + speed: number; +}; diff --git a/src/pages/tools/video/index.ts b/src/pages/tools/video/index.ts index 05c285f3..8b18a566 100644 --- a/src/pages/tools/video/index.ts +++ b/src/pages/tools/video/index.ts @@ -1,5 +1,4 @@ import { tool as videoMergeVideo } from './merge-video/meta'; -import { tool as videoToGif } from './video-to-gif/meta'; import { tool as changeSpeed } from './change-speed/meta'; import { tool as flipVideo } from './flip/meta'; import { gifTools } from './gif'; @@ -19,7 +18,6 @@ export const videoTools = [ flipVideo, cropVideo, changeSpeed, - videoToGif, videoMergeVideo, addAudio ]; diff --git a/src/pages/tools/video/loop/index.tsx b/src/pages/tools/video/loop/index.tsx index 8c23d9fa..cc3722f2 100644 --- a/src/pages/tools/video/loop/index.tsx +++ b/src/pages/tools/video/loop/index.tsx @@ -1,9 +1,8 @@ import { Box } from '@mui/material'; -import { useState } from 'react'; +import { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; -import { CardExampleType } from '@components/examples/ToolExamples'; import { loopVideo } from './service'; import { InitialValuesType } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; @@ -12,6 +11,7 @@ import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; import * as Yup from 'yup'; import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; const initialValues: InitialValuesType = { loops: 2 @@ -21,7 +21,7 @@ const validationSchema = Yup.object({ loops: Yup.number().min(1, 'Number of loops must be greater than 1') }); -export default function Loop({ title, longDescription }: ToolComponentProps) { +export default function Loop({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -32,7 +32,7 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { try { setLoading(true); const resultFile = await loopVideo(input, values); - await setResult(resultFile); + setResult(resultFile); } catch (error) { console.error(error); } finally { @@ -40,6 +40,8 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField @@ -50,10 +52,18 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { - updateNumberField(value, 'loops', updateField) + updateNumberField( + String(Math.max(1, Number(value) || 1)), + 'loops', + updateField + ) } value={values.loops} label={t('loop.numberOfLoops')} + type="number" + inputProps={{ + min: 1 + }} /> ) @@ -65,29 +75,21 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { input={input} inputComponent={} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} validationSchema={validationSchema} getGroups={getGroups} setInput={setInput} - compute={compute} + compute={debouncedCompute} toolInfo={{ title: t('loop.toolInfo.title', { title }), - description: longDescription + description: t('loop.toolInfo.description') }} /> ); diff --git a/src/pages/tools/video/loop/service.ts b/src/pages/tools/video/loop/service.ts index 5478853e..002a8193 100644 --- a/src/pages/tools/video/loop/service.ts +++ b/src/pages/tools/video/loop/service.ts @@ -1,41 +1,38 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; -const ffmpeg = new FFmpeg(); - export async function loopVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args = []; + const loopCount = options.loops - 1; + + if (loopCount <= 0) { + return input; + } + + args.push('-stream_loop', loopCount.toString()); + args.push('-i', inputName); + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const loopedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(loopedData as Uint8Array)], { + type: 'video/mp4' }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const args = []; - const loopCount = options.loops - 1; - - if (loopCount <= 0) { - return input; - } - - args.push('-stream_loop', loopCount.toString()); - args.push('-i', inputName); - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const loopedData = await ffmpeg.readFile(outputName); - return await new File( - [new Blob([loopedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_looped.mp4`, - { type: 'video/mp4' } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_looped.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/merge-video/index.tsx b/src/pages/tools/video/merge-video/index.tsx index 8a7de659..57d77f02 100644 --- a/src/pages/tools/video/merge-video/index.tsx +++ b/src/pages/tools/video/merge-video/index.tsx @@ -1,4 +1,3 @@ -import { Box } from '@mui/material'; import React, { useState } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; @@ -7,14 +6,17 @@ import ToolMultipleVideoInput, { MultiVideoInput } from '@components/input/ToolMultipleVideoInput'; import { mergeVideos } from './service'; -import { InitialValuesType } from './types'; +import { useTranslation } from 'react-i18next'; -const initialValues: InitialValuesType = {}; +const initialValues = {}; + +type InitialValuesType = typeof initialValues; export default function MergeVideo({ title, longDescription }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState([]); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); @@ -28,12 +30,9 @@ export default function MergeVideo({ } setLoading(true); try { - const files = input.map((item) => item.file); - const mergedBlob = await mergeVideos(files, initialValues); - const mergedFile = new File([mergedBlob], 'merged-video.mp4', { - type: 'video/mp4' - }); - setResult(mergedFile); + const resultFile = await mergeVideos(input.map((item) => item.file)); + + setResult(resultFile); } catch (err) { setResult(null); } finally { @@ -51,15 +50,15 @@ export default function MergeVideo({ onChange={(newInput) => { setInput(newInput); }} - accept={['video/*', '.mp4', '.avi', '.mov', '.mkv']} - title="Input Videos" + accept={['video/*']} + title={t('mergeVideo.inputTitle')} type="video" /> } resultComponent={ @@ -68,7 +67,7 @@ export default function MergeVideo({ getGroups={null} setInput={setInput} compute={compute} - toolInfo={{ title: `What is a ${title}?`, description: longDescription }} + toolInfo={{ title: `${title} ?`, description: longDescription }} /> ); } diff --git a/src/pages/tools/video/merge-video/merge-video.service.test.ts b/src/pages/tools/video/merge-video/merge-video.service.test.ts deleted file mode 100644 index 311c0673..00000000 --- a/src/pages/tools/video/merge-video/merge-video.service.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg and fetchFile to avoid Node.js compatibility issues -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])) -})); - -// Import after mocking -import { mergeVideos } from './service'; - -function createMockFile(name: string, type = 'video/mp4') { - return new File([new Uint8Array([0, 1, 2])], name, { type }); -} - -describe('merge-video', () => { - it('throws if less than two files are provided', async () => { - await expect(mergeVideos([], {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - await expect(mergeVideos([createMockFile('a.mp4')], {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - }); - - it('throws if input is not an array', async () => { - // @ts-ignore - testing invalid input - await expect(mergeVideos(null, {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - }); - - it('successfully merges video files (mocked)', async () => { - const mockFile1 = createMockFile('video1.mp4'); - const mockFile2 = createMockFile('video2.mp4'); - - const result = await mergeVideos([mockFile1, mockFile2], {}); - - expect(result).toBeInstanceOf(Blob); - expect(result.type).toBe('video/mp4'); - }); - - it('handles different video formats by re-encoding', async () => { - const mockFile1 = createMockFile('video1.avi', 'video/x-msvideo'); - const mockFile2 = createMockFile('video2.mov', 'video/quicktime'); - - const result = await mergeVideos([mockFile1, mockFile2], {}); - - expect(result).toBeInstanceOf(Blob); - expect(result.type).toBe('video/mp4'); - }); -}); diff --git a/src/pages/tools/video/merge-video/service.ts b/src/pages/tools/video/merge-video/service.ts index 6089125b..d2fec2e5 100644 --- a/src/pages/tools/video/merge-video/service.ts +++ b/src/pages/tools/video/merge-video/service.ts @@ -1,134 +1,58 @@ -import { InitialValuesType, MergeVideoInput, MergeVideoOutput } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; -export async function mergeVideos( - input: MergeVideoInput, - options: InitialValuesType -): Promise { - if (!Array.isArray(input) || input.length < 2) { - throw new Error('Please provide at least two video files to merge.'); - } +export async function mergeVideos(input: File[]): Promise { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const fileNames: string[] = []; + const outputName = tempFile('.mp4'); + const concatListName = tempFile('.txt'); - // Create a new FFmpeg instance for each operation to avoid conflicts - const ffmpeg = new FFmpeg(); - - const fileNames: string[] = []; - const outputName = 'output.mp4'; - - try { - // Load FFmpeg with proper error handling - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm', - workerURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.worker.js' - }); - } - - // Write all input files to ffmpeg FS with better error handling for (let i = 0; i < input.length; i++) { - const fileName = `input${i}.mp4`; + const fileName = tempFile('.mp4'); + fileNames.push(fileName); - try { - const fileData = await fetchFile(input[i]); - await ffmpeg.writeFile(fileName, fileData); - console.log(`Successfully wrote ${fileName}`); - } catch (fileError) { - console.error(`Failed to write ${fileName}:`, fileError); - throw new Error(`Failed to process input file ${i + 1}: ${fileError}`); - } + await ffmpeg.writeFile(fileName, await fetchFile(input[i])); } - // Build the filter_complex string for concat filter - const videoInputs = fileNames.map((_, idx) => `[${idx}:v]`).join(' '); - const audioInputs = fileNames.map((_, idx) => `[${idx}:a]`).join(' '); - const filterComplex = `${videoInputs} ${audioInputs} concat=n=${input.length}:v=1:a=1 [v] [a]`; + // Create concat file + const concatList = fileNames.map((name) => `file '${name}'`).join('\n'); - // Build input arguments - const inputArgs = []; - for (const fileName of fileNames) { - inputArgs.push('-i', fileName); - } + await ffmpeg.writeFile( + concatListName, + new TextEncoder().encode(concatList) + ); - console.log('Starting FFmpeg processing...'); - console.log('Filter complex:', filterComplex); + await ffmpeg.exec([ + '-f', + 'concat', + '-safe', + '0', + '-i', + concatListName, + '-c:v', + 'libx264', + '-preset', + 'ultrafast', + '-crf', + '30', + '-c:a', + 'aac', + outputName + ]); - // Method 2: Fallback to concat demuxer - try { - console.log('Trying concat demuxer method...'); + const data = await ffmpeg.readFile(outputName); - const concatList = fileNames.map((name) => `file '${name}'`).join('\n'); - await ffmpeg.writeFile( - 'concat_list.txt', - new TextEncoder().encode(concatList) - ); + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }); - await ffmpeg.exec([ - '-f', - 'concat', - '-safe', - '0', - '-i', - 'concat_list.txt', - '-c:v', - 'libx264', - '-preset', - 'ultrafast', - '-crf', - '30', - '-threads', - '0', - '-y', - outputName - ]); - - // Check if output was created - try { - const testRead = await ffmpeg.readFile(outputName); - if (testRead && testRead.length > 0) { - console.log('Concat demuxer method succeeded'); - } - } catch (readError) { - console.log('Concat demuxer method failed to produce output'); - } - } catch (execError) { - console.error('Concat demuxer method failed:', execError); - } - - // Check if output file exists and read it - let mergedData; - try { - mergedData = await ffmpeg.readFile(outputName); - console.log('Successfully read output file'); - } catch (readError) { - console.error('Failed to read output file:', readError); - throw new Error('Failed to read merged video file'); - } - - if (!mergedData || mergedData.length === 0) { - throw new Error('Output file is empty or corrupted'); - } - - return new Blob([mergedData as any], { type: 'video/mp4' }); - } catch (error) { - console.error('Error merging videos:', error); - throw error instanceof Error - ? error - : new Error('Unknown error occurred during video merge'); - } finally { - // Clean up temporary files with better error handling - const filesToClean = [...fileNames, outputName, 'concat_list.txt']; - - for (const fileName of filesToClean) { - try { - await ffmpeg.deleteFile(fileName); - } catch (cleanupError) { - // Ignore cleanup errors - they're not critical - console.warn(`Could not delete ${fileName}:`, cleanupError); - } - } - } + return new File( + [blob], + `${input[0].name.replace(/\.[^/.]+$/, '')}_merged_with_${ + input.length - 1 + }_videos.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/merge-video/types.ts b/src/pages/tools/video/merge-video/types.ts deleted file mode 100644 index 7cb6a522..00000000 --- a/src/pages/tools/video/merge-video/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type InitialValuesType = { - // Add any future options here (e.g., output format, resolution) -}; - -// Type for the main function input -export type MergeVideoInput = File[]; - -// Type for the main function output -export type MergeVideoOutput = Blob; diff --git a/src/pages/tools/video/rotate/index.tsx b/src/pages/tools/video/rotate/index.tsx index 32c66646..23a7fb4d 100644 --- a/src/pages/tools/video/rotate/index.tsx +++ b/src/pages/tools/video/rotate/index.tsx @@ -8,17 +8,17 @@ import { GetGroupsType } from '@components/options/ToolOptions'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; import { rotateVideo } from './service'; -import { RotationAngle } from '../../pdf/rotate-pdf/types'; import SimpleRadio from '@components/options/SimpleRadio'; import { useTranslation } from 'react-i18next'; +import { InitialValuesType, RotationAngle } from './types'; -export const initialValues = { +export const initialValues: InitialValuesType = { rotation: 90 }; export const validationSchema = Yup.object({ rotation: Yup.number() - .oneOf([0, 90, 180, 270], 'Rotation must be 0, 90, 180, or 270 degrees') + .oneOf([90, 180, 270], 'Rotation must be 90, 180, or 270 degrees') .required('Rotation is required') }); @@ -34,14 +34,14 @@ export default function RotateVideo({ title }: ToolComponentProps) { const [loading, setLoading] = useState(false); const compute = async ( - optionsValues: typeof initialValues, + optionsValues: InitialValuesType, input: File | null ) => { if (!input) return; setLoading(true); try { - const rotatedFile = await rotateVideo(input, optionsValues.rotation); + const rotatedFile = await rotateVideo(input, optionsValues); setResult(rotatedFile); } catch (error) { console.error('Error rotating video:', error); @@ -52,7 +52,7 @@ export default function RotateVideo({ title }: ToolComponentProps) { const debouncedCompute = useCallback(debounce(compute, 1000), []); - const getGroups: GetGroupsType = ({ + const getGroups: GetGroupsType = ({ values, updateField }) => [ @@ -87,20 +87,12 @@ export default function RotateVideo({ title }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/rotate/service.ts b/src/pages/tools/video/rotate/service.ts index 30e5665d..f27d343b 100644 --- a/src/pages/tools/video/rotate/service.ts +++ b/src/pages/tools/video/rotate/service.ts @@ -1,44 +1,46 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { RotationAngle, InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); +const rotateMap: Record = { + 90: 'transpose=1', + 180: 'transpose=2,transpose=2', + 270: 'transpose=2' +}; export async function rotateVideo( input: File, - rotation: number + options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const { rotation } = options; + + const rotateFilter = rotateMap[rotation]; + + const args = ['-i', inputName]; + if (rotateFilter) { + args.push('-vf', rotateFilter); + } + + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const rotatedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(rotatedData as Uint8Array)], { + type: 'video/mp4' }); - } - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const rotateMap: Record = { - 90: 'transpose=1', - 180: 'transpose=2,transpose=2', - 270: 'transpose=2', - 0: '' - }; - const rotateFilter = rotateMap[rotation]; - - const args = ['-i', inputName]; - if (rotateFilter) { - args.push('-vf', rotateFilter); - } - - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const rotatedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([rotatedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_rotated.mp4`, - { type: 'video/mp4' } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_rotated.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/rotate/types.ts b/src/pages/tools/video/rotate/types.ts new file mode 100644 index 00000000..982c3185 --- /dev/null +++ b/src/pages/tools/video/rotate/types.ts @@ -0,0 +1,5 @@ +export type RotationAngle = 270 | 180 | 90; + +export type InitialValuesType = { + rotation: RotationAngle; +}; diff --git a/src/pages/tools/video/trim/index.tsx b/src/pages/tools/video/trim/index.tsx index a3fefcc3..f5af1863 100644 --- a/src/pages/tools/video/trim/index.tsx +++ b/src/pages/tools/video/trim/index.tsx @@ -7,23 +7,21 @@ import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { trimVideo } from './service'; +import { InitialValuesType } from './types'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; import { useTranslation } from 'react-i18next'; -const ffmpeg = new FFmpeg(); - -const initialValues = { - trimStart: 0, - trimEnd: 100 +const initialValues: InitialValuesType = { + start: 0, + end: 100 }; const validationSchema = Yup.object({ - trimStart: Yup.number().min(0, 'Start time must be positive'), - trimEnd: Yup.number().min( - Yup.ref('trimStart'), + start: Yup.number().min(0, 'Start time must be positive'), + end: Yup.number().min( + Yup.ref('start'), 'End time must be greater than start time' ) }); @@ -32,57 +30,27 @@ export default function TrimVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); const compute = async ( - optionsValues: typeof initialValues, + optionsValues: InitialValuesType, input: File | null ) => { if (!input) return; - - const { trimStart, trimEnd } = optionsValues; + setLoading(true); try { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - // Load file into FFmpeg's virtual filesystem - await ffmpeg.writeFile(inputName, await fetchFile(input)); - // Run FFmpeg command to trim video - await ffmpeg.exec([ - '-i', - inputName, - '-ss', - trimStart.toString(), - '-to', - trimEnd.toString(), - '-c', - 'copy', - outputName - ]); - // Retrieve the processed file - const trimmedData = await ffmpeg.readFile(outputName); - const trimmedBlob = new Blob([trimmedData as any], { type: 'video/mp4' }); - const trimmedFile = new File( - [trimmedBlob], - `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.mp4`, - { - type: 'video/mp4' - } - ); - - setResult(trimmedFile); + const resultFile = await trimVideo(input, optionsValues); + setResult(resultFile); } catch (error) { console.error('Error trimming video:', error); + } finally { + setLoading(false); } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); - const getGroups: GetGroupsType = ({ + const getGroups: GetGroupsType = ({ values, updateField }) => [ @@ -92,17 +60,17 @@ export default function TrimVideo({ title }: ToolComponentProps) { - updateNumberField(value, 'trimStart', updateField) + updateNumberField(value, 'start', updateField) } - value={values.trimStart} + value={Number(values.start)} label={t('trim.startTime')} sx={{ mb: 2, backgroundColor: 'background.paper' }} /> - updateNumberField(value, 'trimEnd', updateField) + updateNumberField(value, 'end', updateField) } - value={values.trimEnd} + value={Number(values.end)} label={t('trim.endTime')} /> @@ -113,19 +81,19 @@ export default function TrimVideo({ title }: ToolComponentProps) { { + renderCustomInput={({ start, end }, setFieldValue) => { return ( { - setFieldValue('trimStart', trimStart); - setFieldValue('trimEnd', trimEnd); + onTrimChange={(start, end) => { + setFieldValue('start', start); + setFieldValue('end', end); }} - trimStart={trimStart} - trimEnd={trimEnd} + trimStart={Number(start)} + trimEnd={Number(end)} /> ); }} @@ -133,6 +101,7 @@ export default function TrimVideo({ title }: ToolComponentProps) { } diff --git a/src/pages/tools/video/trim/service.ts b/src/pages/tools/video/trim/service.ts new file mode 100644 index 00000000..af05218e --- /dev/null +++ b/src/pages/tools/video/trim/service.ts @@ -0,0 +1,42 @@ +import { InitialValuesType } from './types'; +import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; + +export async function trimVideo( + input: File, + options: InitialValuesType +): Promise { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { start, end } = options; + + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + inputName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-c', + 'copy', + outputName + ]); + + const trimmedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(trimmedData as Uint8Array)], { + type: 'video/mp4' + }); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.mp4`, + { + type: 'video/mp4' + } + ); + }); +} diff --git a/src/pages/tools/video/trim/types.ts b/src/pages/tools/video/trim/types.ts new file mode 100644 index 00000000..d45ce19d --- /dev/null +++ b/src/pages/tools/video/trim/types.ts @@ -0,0 +1,4 @@ +export type InitialValuesType = { + start: Number; + end: number; +}; diff --git a/src/pages/tools/video/video-to-gif/index.tsx b/src/pages/tools/video/video-to-gif/index.tsx deleted file mode 100644 index 4c0f61bc..00000000 --- a/src/pages/tools/video/video-to-gif/index.tsx +++ /dev/null @@ -1,234 +0,0 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; -import * as Yup from 'yup'; -import ToolContent from '@components/ToolContent'; -import { ToolComponentProps } from '@tools/defineTool'; -import { GetGroupsType } from '@components/options/ToolOptions'; -import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import { updateNumberField } from '@utils/string'; -import { InitialValuesType } from './types'; -import ToolVideoInput from '@components/input/ToolVideoInput'; -import ToolFileResult from '@components/result/ToolFileResult'; -import SimpleRadio from '@components/options/SimpleRadio'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; - -const initialValues: InitialValuesType = { - quality: 'mid', - fps: '10', - scale: '320:-1:flags=bicubic', - start: 0, - end: 100 -}; - -const validationSchema = Yup.object({ - start: Yup.number().min(0, 'Start time must be positive'), - end: Yup.number().min( - Yup.ref('start'), - 'End time must be greater than start time' - ) -}); - -export default function VideoToGif({ - title, - longDescription -}: ToolComponentProps) { - const [input, setInput] = useState(null); - const [result, setResult] = useState(null); - const [loading, setLoading] = useState(false); - - const compute = (values: InitialValuesType, input: File | null) => { - if (!input) return; - const { fps, scale, start, end } = values; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; - - const convertVideoToGif = async ( - file: File, - fps: string, - scale: string, - start: number, - end: number - ): Promise => { - setLoading(true); - - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - const fileName = file.name; - const outputName = 'output.gif'; - - try { - ffmpeg.writeFile(fileName, await fetchFile(file)); - - await ffmpeg.exec([ - '-i', - fileName, - '-ss', - start.toString(), - '-to', - end.toString(), - '-vf', - `fps=${fps},scale=${scale},palettegen`, - 'palette.png' - ]); - - await ffmpeg.exec([ - '-i', - fileName, - '-i', - 'palette.png', - '-ss', - start.toString(), - '-to', - end.toString(), - '-filter_complex', - `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, - outputName - ]); - - const data = await ffmpeg.readFile(outputName); - - const blob = new Blob([data as any], { type: 'image/gif' }); - const convertedFile = new File([blob], outputName, { - type: 'image/gif' - }); - - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - - setResult(convertedFile); - } catch (err) { - console.error(`Failed to convert video: ${err}`); - throw err; - } finally { - setLoading(false); - } - }; - - convertVideoToGif(input, fps, scale, start, end); - }; - - const getGroups: GetGroupsType | null = ({ - values, - updateField - }) => [ - { - title: 'Set Quality', - component: ( - - { - updateField('quality', 'low'); - updateField('fps', '5'); - updateField('scale', '240:-1:flags=bilinear'); - }} - checked={values.quality === 'low'} - /> - { - updateField('quality', 'mid'); - updateField('fps', '10'); - updateField('scale', '320:-1:flags=bicubic'); - }} - checked={values.quality === 'mid'} - /> - { - updateField('quality', 'high'); - updateField('fps', '15'); - updateField('scale', '480:-1:flags=lanczos'); - }} - checked={values.quality === 'high'} - /> - { - updateField('quality', 'ultra'); - updateField('fps', '15'); - updateField('scale', '640:-1:flags=lanczos'); - }} - checked={values.quality === 'ultra'} - /> - - ) - }, - { - title: 'Timestamps', - component: ( - - - updateNumberField(value, 'start', updateField) - } - value={values.start} - label="Start Time" - sx={{ mb: 2, backgroundColor: 'background.paper' }} - /> - - updateNumberField(value, 'end', updateField) - } - value={values.end} - label="End Time" - /> - - ) - } - ]; - - return ( - { - return ( - { - setFieldValue('start', start); - setFieldValue('end', end); - }} - trimStart={start} - trimEnd={end} - /> - ); - }} - resultComponent={ - loading ? ( - - ) : ( - - ) - } - initialValues={initialValues} - getGroups={getGroups} - setInput={setInput} - compute={compute} - toolInfo={{ title: `What is a ${title}?`, description: longDescription }} - /> - ); -} diff --git a/src/pages/tools/video/video-to-gif/types.ts b/src/pages/tools/video/video-to-gif/types.ts deleted file mode 100644 index 0bd16ffd..00000000 --- a/src/pages/tools/video/video-to-gif/types.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type InitialValuesType = { - quality: 'mid' | 'high' | 'low' | 'ultra'; - fps: string; - scale: string; - start: number; - end: number; -}; diff --git a/src/utils/json.ts b/src/utils/json.ts index c243ab37..f1020007 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,3 +1,73 @@ +export type ParsedJson = + | Record + | unknown[] + | string + | number + | boolean + | null; + +export type JsonFormat = 'json' | 'jsonl'; + +export interface ParseJsonResult { + data: ParsedJson; + format: JsonFormat; +} + +/** + * Parses a JSON string into its JavaScript representation. + * + * Supports: + * - Standard JSON (objects, arrays, and primitives) + * - JSON Lines (NDJSON), where each non-empty line is a valid JSON value + * + * @param input - The JSON string to parse. + * @returns The parsed JSON value, or an array of parsed values for JSON Lines input. + * Returns an empty string if the input is empty or whitespace-only. + * @throws {Error} If the input contains invalid JSON. + */ +export function parseJsonInput(input: string): ParseJsonResult { + try { + return { data: JSON.parse(input), format: 'json' }; + } catch (originalError) { + const lines = input.split(/\r?\n/); + + // preserve blank lines numbers + const nonBlankLines: { text: string; lineNumber: number }[] = []; + lines.forEach((line, index) => { + const trimmed = line.trim(); + if (trimmed) { + nonBlankLines.push({ text: trimmed, lineNumber: index + 1 }); + } + }); + + // A single line that fails isn't NDJSON, it's just malformed JSON - + // surface the original error instead of a misleading one. + if (nonBlankLines.length <= 1) { + const reason = + originalError instanceof Error + ? originalError.message + : 'Unknown error'; + throw new Error(`Invalid JSON: ${reason}`); + } + + const parsedLines: unknown[] = []; + + for (const { text, lineNumber } of nonBlankLines) { + try { + parsedLines.push(JSON.parse(text)); + } catch (error) { + const reason = + error instanceof Error + ? error.message.replace(/\s*\(line \d+ column \d+\)$/, '') + : 'Unknown error'; + + throw new Error(`Invalid JSON at line ${lineNumber}: ${reason}`); + } + } + + return { data: parsedLines, format: 'jsonl' }; + } +} /** * Collects all unique keys from an array of row objects, preserving first-encountered order. * Handles sparse rows where different rows may have different keys. @@ -15,8 +85,8 @@ export function getJsonHeaders( if (typeof input === 'string') { try { - const parsed = JSON.parse(input); - rows = Array.isArray(parsed) ? parsed : [parsed]; + const { data } = parseJsonInput(input); + rows = (Array.isArray(data) ? data : [data]) as Record[]; } catch { return []; } @@ -26,7 +96,11 @@ export function getJsonHeaders( return Array.from( rows.reduce>((set, row) => { - Object.keys(row).forEach((key) => set.add(key)); + // Skip anything that isn't a plain object (null, arrays, strings, etc.) + // to avoid crashing or pulling in bogus "headers" from those values. + if (row && typeof row === 'object' && !Array.isArray(row)) { + Object.keys(row).forEach((key) => set.add(key)); + } return set; }, new Set()) ); diff --git a/src/utils/string.ts b/src/utils/string.ts index e874c28c..296f8051 100644 --- a/src/utils/string.ts +++ b/src/utils/string.ts @@ -162,25 +162,29 @@ export function stripAndDecodeHtml(html: string): string { } /** - * Escapes special HTML characters in a string to prevent HTML injection. + * Escapes special characters shared by HTML and XML into their + * corresponding entities, making a string safe for insertion into + * either markup language. * - * Replaces the following characters with their corresponding HTML entities: + * Replaces: * - & → & * - < → < * - > → > * - " → " + * - ' → ' * * @param {string} str - The input string to escape. - * @returns {string} The escaped string safe for insertion into HTML. + * @returns {string} The escaped string, safe for insertion into HTML or XML. * * @example - * escapeHtml('Hello & welcome'); + * escapeMarkup('Hello & welcome'); * // Returns: '<div class="test">Hello & welcome</div>' */ -export function escapeHtml(str: string): string { +export function escapeMarkup(str: string): string { return str .replace(/&/g, '&') .replace(//g, '>') - .replace(/"/g, '"'); + .replace(/"/g, '"') + .replace(/'/g, '''); } diff --git a/src/utils/xml.ts b/src/utils/xml.ts new file mode 100644 index 00000000..c966e9b5 --- /dev/null +++ b/src/utils/xml.ts @@ -0,0 +1,24 @@ +/** + * Normalizes an arbitrary string into a valid XML tag name. + * + * - Purely numeric keys are prefixed with "row-" (XML tag names can't + * start with a digit). + * - Any character outside [a-zA-Z0-9_.-] is replaced with an underscore. + * - If the result still doesn't start with a letter or underscore + * (e.g. it started with '.' or '-'), an underscore is prepended. + * + * @param {string} key - The raw key/field name to convert into a tag name. + * @returns {string} A valid XML tag name. + * + * @example + * normalizeXmlTagName('0'); // 'row-0' + * normalizeXmlTagName('user name'); // 'user_name' + * normalizeXmlTagName('-id'); // '_-id' + */ +export const normalizeXmlTagName = (key: string): string => { + const tagName = key !== '' && !isNaN(Number(key)) ? `row-${key}` : key; + + const sanitized = tagName.replace(/[^a-zA-Z0-9_.-]/g, '_'); + + return /^[a-zA-Z_]/.test(sanitized) ? sanitized : `_${sanitized}`; +}; diff --git a/vite.config.ts b/vite.config.ts index e6faab71..92f32f75 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,12 +2,18 @@ import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; import tsconfigPaths from 'vite-tsconfig-paths'; +import packageJson from './package.json'; +import { execSync } from 'node:child_process'; + +const commitHash = execSync('git rev-parse --short HEAD').toString().trim(); // https://vitejs.dev/config https://vitest.dev/config export default defineConfig({ plugins: [react(), tsconfigPaths()], define: { - 'process.env': {} + 'process.env': {}, + __APP_VERSION__: JSON.stringify(packageJson.version), + __COMMIT_HASH__: JSON.stringify(commitHash) }, optimizeDeps: { exclude: ['@ffmpeg/ffmpeg', '@ffmpeg/util']