Days
Hours
Minutes
Seconds
x

New Froala Editor v4.5.1 is here – Learn More

Skip to content

Customizing Filestack File Picker: the New Froala File Uploading Option – Part 2

file uploading

Imagine a JavaScript tool – where it can effortlessly handle upload, store, and process your files with a few lines of code. That’s the power of Filestack, a file management tool that has processed over 1 billion files and counting.

Filestack now has official integration with Froala, offering many customization options that allow developers to create a truly seamless and intuitive file uploading process within the Froala editor tailored for your users.

We explored some of the Filestack File Picker customization options available to developers before. In this second part of the series, we will explore additional customization options related to events, uncovering how you can customize the file uploading experience from start to finish – from the moment the user opens the picker to handle the successful (or failed) upload.

Let’s delve into these customization features that help you create a smooth and intuitive file management workflow within your Froala-powered applications, significantly improving user experience.

Key Takeaways:

  1. Filestack provides a range of customization options and events that allow developers to create a highly responsive and tailored file picker experience within Froala-powered applications.
  2. The onOpen event can be used to enhance the user experience when the File Picker UI mounts, such as displaying a custom loading indicator or updating the UI.
  3. The onFileSelected event enables developers to validate selected files, reject files that don’t meet certain criteria, and even modify the file name if needed.
  4. The onFileCropped event provides metadata about the cropped image, allowing developers to perform additional processing before inserting it into the Froala editor.
  5. The onCancel event can be used to customize the user experience when file uploads are cancelled, ensuring the application remains responsive and user-friendly.
  6. The onClose event triggers when the File Picker UI is exited, providing an opportunity to perform any necessary cleanup or additional actions.

Enhance File Uploading experience

Customize the File Picker Opening Experience

Filestack’s onOpen event triggers when the File Picker UI mounts. You can use this event to enhance the user experience. For example, you can display a custom loading indicator or update the UI to provide feedback.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onOpen: filepicker => {
                console.log(filepicker);
            }
        }
    }
});

The onOpen callback receives the PickerInstance interface, which provides the following methods:

  • cancel() Cancels any ongoing uploads. This operation is idempotent and returns a Promise.
    new FroalaEditor("div#froala-editor", {
        filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    //Cancel picker uploads. 
                    PickerInstance.cancel();
                }
            }
        }
    });
    
  • close() Closes the File Picker. This operation is idempotent and returns a Promise.
    new FroalaEditor("div#froala-editor", {
        filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    //Close the File Picker.
                    PickerInstance.close();
                }
            }
        }
    });
    
  • open() Opens the File Picker. This operation is idempotent.
  • crop(urls) Specifies a list of file URLs to open in the Picker for cropping.
    new FroalaEditor("div#froala-editor", {
    filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    const urls = [
                        'https://d1wtqaffaaj63z.cloudfront.net/images/fox_in_forest1.jpg',
                        'https://d1wtqaffaaj63z.cloudfront.net/images/sail.jpg',
                    ];
                    PickerInstance.crop(urls);
                }
            }
        }
    });
    

Leverage the onOpen event and the PickerInstance methods to create a more engaging user experience.

Handling User Selected Files

The onFileSelected event in Filestack triggers whenever a user selects a file. You can use this event to validate the selected file and, if necessary, reject the selection by throwing an error. The error message will be displayed to the user as an alert.

For example, you can reject files that exceed a certain size limit:

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                if (file.size > 1000 * 1000) {
                    throw new Error('File too big, select something smaller than 1MB');
                }
            }
        }
    }
});

Developers can use this event to change the selected file name if it’s uploaded from the local source.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                // It's important to return a new file by the end of this function.
                return { ...file, name: 'foo' };
            }
        }
    }
});

The onFileSelected event also supports asynchronous validation logic. You can return a Promise from the callback function and then resolve or reject the Promise as needed:

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                return new Promise((resolve, reject) => {
                    // Do something async
                    resolve();
                    // Or reject the selection with reject()
                  });
            }
        }
    }
});

By leveraging the onFileSelected event, you can create a more robust and user-friendly file selection experience within your Froala-powered applications.

Handling Cropped Files

When a user uploads an image using the File Picker, Filestack displays a simple image editor. This editor allows the user to crop, circle crop, and rotate the image.

Filestack triggers the onFileCropped event when the user crops the image. This event provides an object with the file metadata, such as the file size. You can use this metadata to perform additional processing on the cropped image before inserting it into the Froala editor.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileCropped : (file) => {
                console.log(file.size);
            }
        }
    }
});

The onFileCropped event provides the necessary information to handle the cropped image, allowing you to integrate the cropping functionality seamlessly into your application’s workflow.

Customize User Experience When Files Get Cancelled

Filestack triggers the onCancel event when all uploads in the File Picker are cancelled. This event receives an object containing the file’s metadata.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onCancel: PickerUploadDoneCallback => {
                console.log(PickerUploadDoneCallback);
            }
        }
    }
});

Handling the onCancel event gives you the flexibility to customize the user experience when the file upload is interrupted, ensuring your application remains responsive and user-friendly. By providing feedback and handling the cancellation scenario, you can create a more engaging and intuitive file management workflow within your Froala-powered applications. This helps to enhance the overall user experience and ensure your users feel in control of the file upload process, even when they choose to cancel it.

Customize the File Picker Closing Experience

Filestack triggers the onClose event when the File Picker UI is exited.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onClose: () => {
                console.log('File Picker closed');
            }
        }
    }
});

Looking For Other Events?

Beyond the events mentioned, Filestack provides a range of other events such as onFileUploadCancel, onFileUploadFailed, onFileUploadFinished, onFileUploadProgress, onFileUploadStarted, onUploadDone, and onUploadStarted that you can leverage to customize the file uploading experience. Refer to the Filestack documentation for a comprehensive list of available options and their usage.

Conclusion

Filestack File Picker is a powerful tool for handling file uploads. Users appreciate its ease of use, support for various upload sources, dependability, and straightforward cloud storage integration. Filestack offers many customization options and events that allow developers to create a highly responsive and tailored file picker experience.

From validating file selections to handling cropped images and managing the overall file upload workflow, these events empower you to customize the user experience to your specific needs. Explore the full range of Filestack events and integrate them seamlessly into your application’s logic. This ensures a smooth and intuitive file management process for your users.

If you’re looking to enhance the file-uploading experience in your Froala-powered applications, try the Filestack integration today. Its robust set of customization features will help you create a seamless and user-friendly file management workflow.

 

Get your Filestack API here for free.

How to Keep Content Safe for Work (SFW) in Your WYSIWYG Editor

As users and developers of various applications, we all recognize that user-generated content is everywhere. From blog comments and social media posts to streaming platforms, people constantly share their thoughts, preferences, and ideas. While this self-expression is necessary, it creates a challenge: how do we ensure shared content stays professional and safe for work (SFW)? The solution is simple: use a WYSIWYG editor with a built-in SFW checker for uploaded images and videos. But how does it actually work? In this article, I’ll show you how to integrate SFW-checking capabilities into your application using a WYSIWYG HTML editor.

Key Takeaways

  • Enhance your application’s community experience by checking whether content is safe for work or not
  • Use Filestack within Froala Editor to easily check for and handle NSFW content
  • Dynamically manage uploaded content using the ‘filestack.uploadedToFilestack‘ event
  • Enable SFW checking by getting a Filestack API key, a Base64-encoded policy, and a signature (all from the Filestack dashboard)
  • Use Filestack Workflows for an even easier way to implement SFW checking

The Importance of SFW Content in WYSIWYG Editors

Nowadays, keeping inappropriate content out of applications is essential for protecting users, maintaining brand reputation, and fostering a safe community experience. For example, let’s say that an unmoderated social media platform inadvertently displays offensive or inappropriate content. This could prevent users from using the app further because of how uncomfortable their experience was. In turn, this might reduce engagement and revenue in your application. Additionally, this could also lead to legal issues or compliance violations, which could tarnish your company’s credibility. It could even expose vulnerable users, especially children, to trauma or other serious consequences. Such scenarios highlight the need for content moderation that prioritizes the community’s safety and well-being.

For us developers, this responsibility extends to ensuring that tools like WYSIWYG editors support flagging or filtering NSFW content. More than just compliance or risk mitigation, it’s about fostering trust and safety as well as providing users with a positive experience that keeps them engaged. Now that we know just how important content regulation is in applications, let’s see how we can implement it in our applications.

How to Use a WYSIWYG Editor to Keep Uploaded Content Safe for Work

Just over a decade ago, it would have been near impossible or really difficult to implement SFW checking. Thanks to machine learning and computer vision models being better and more accessible today, it’s now a lot easier. Still, if you want to upload media through a WYSIWYG editor, you could still find some trouble implementing it. That’s why in this guide, we’ll use an editor that has built-in SFW checking. Let’s start!

Preparing the HTML File

First, create an HTML file and insert the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>SFW Checker Using Froala and Filestack</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />
</head>

<body>
    <div class="container-fluid vh-100">
	<div class="row h-100">
            <div class="col-md-6 mx-auto my-auto">
                <div id="froala-editor"></div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="SFWModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="SFWModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="SFWModalLabel">SFW Scan Results</h1>
                </div>
                <div class="modal-body">
                    <p id="SFWResult"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
    <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
    <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
    <script src="js/index.js"></script>
</body>
</html>

Here, we create a div element with the ID “froala-editor.” This is where we’ll initialize the editor later on. Note that we also have a modal called “SFWModal” that displays the result of the scan. The last notable part here is the set of Filestack and Froala scripts, which we need in our application. Once we have the HTML file ready, let’s initialize the editor.

Setting up Froala Editor

In your JS file, initialize Froala Editor using the following code:

new FroalaEditor('#froala-editor',{
    filestackOptions: {
        filestackAPI: 'YourFilestackAPIKey',
        uploadToFilestackOnly: true,
        pickerOptions: {
            accept: ['image/*', 'video/*'],
            fromSources: ['local_file_system']
        }
    },
    toolbarButtons: {
        'moreRich': {
            'buttons': ['openFilePickerImageOnly', 'openFilePickerVideoOnly', 'openFilePicker', 'insertLink', 'insertTable', 'emoticons', 'specialCharacters', 'insertHR'],
            'buttonsVisible': 3
        },

        'moreText': {
            'buttons': ['bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'clearFormatting']
        },

        'moreParagraph': {
            'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
        },
        'moreMisc': {
            'buttons': ['undo', 'redo', 'fullscreen', 'selectAll', 'html', 'help'],
            'align': 'right',
            'buttonsVisible': 2
        }
    },
    events: {
        'filestack.uploadedToFilestack': function (response) {
            console.log("Callback is triggered for upload to Filestack ",);
            checkSFW(response.filesUploaded[0].url);
        },
        'filestack.filestackPickerOpened': function (response) {
            console.log("Callback is triggered for picker opened ",)
        },
        'filestack.filestackPickerClosed': function (response) {
            console.log("Callback is triggered for picker closed ",)
        },
        'filestack.uploadFailedToFilestack': function (response) {
            console.log(response);
        },
    },
    heightMin: 500,
    heightMax: 1000
});

In this code block, we define Froala Editor and its toolbar buttons, events, and size. We also declare the Filestack options that we need. First is your API key (create a free Filestack account to get one). The second one specifies that the plugin will automatically store uploaded content in your internally managed Filestack S3 bucket. The last option lets the uploader accept images and videos only from the client’s local file system. However, you can change this so that you can also upload via Google Drive or other sources.

Note that for the Froala events, we’ll make use of ‘filestack.uploadedToFilestack’ to determine whether content is SFW or not. Under this event, we’ll insert “checkSFW(response.filesUploaded[0].url);” to pass down the URL of the uploaded content as a parameter of our checkSFW function, which we’ll create shortly.

Generating Policy and Signature in Filestack

To use Filestack’s SFW checker, we first need to generate a policy and a signature. To do this, go to your Filestack dashboard. Under “Security,” click “Policy & Signature.” You should see some input fields that ask for an expiration date and some permissions. For this tutorial, we’ll enable all permissions. After setting both the expiration date and permissions, scroll down a bit. You’ll see your generated policy in both JSON and Base64-encoded formats and your signature in hex format. We’ll use both the Base64-encoded policy and the signature in the following section.

Checking Content Safety after Every Upload

Let’s go back to our codes. To start checking content safety, insert the following function into your JS file:

function checkSFW(fileUrl) {
    const policy = 'yourPolicyHere';
    const signature = 'yourSignatureHere';
    const sfwUrl = `https://cdn.filestackcontent.com/security=policy:${policy},signature:${signature}/sfw/${fileUrl}`;

    fetch(sfwUrl).then(response => response.json()).then(data => {
        if(data.sfw) {
            document.getElementById('SFWResult').innerHTML = 'This file is safe for work.</span>';
        }
        else {
            document.getElementById('SFWResult').innerHTML = 'This file is NOT safe for work!';
        }
        new bootstrap.Modal(document.querySelector("#SFWModal")).show();
    }).catch(error => console.error('Error checking SFW status:', error));
}

First, let’s define our policy and signature. Copy the values from your Filestack dashboard and paste them into your codes as constants. Afterwards, define the SFW URL by inserting the policy, signature, and directory/URL of the file into Filestack’s SFW checker CDN. Once these are set, we’ll make a call to the SFW checker with the prior parameters and process the fetched result. If the data is SFW, we’ll change the contents of the modal to confirm that the file is appropriate. Otherwise, we’ll flag it as NSFW. Note that in your actual application, you might want to handle NSFW content better by explaining to the user why it was flagged and by providing some actions that they can take. Finally, we’ll show the modal. We’re now ready to run the application.

Running the Application

We uploaded a photo of a flamingo using Froala WYSIWYG editor and its built-in Filestack uploader. After clicking "upload," Filestack will determine whether the photo is SFW or not.

Run the application and click on the Filestack icon. Upload an image of your choice (in this case, a flamingo) and click “Upload.” Afterwards, Filestack should return a true or false response corresponding to the content’s safety.

Result of the SFW checking

The image above shows the modal that we created earlier together with the result of the SFW scan. In this case, Filestack flagged the flamingo photo as safe for work. Now, you’re free to handle the image, whether SFW or not, based on your requirements. In this case, we’ll just leave the flamingo image inside the editor:

The flamingo photo, now flagged as safe for work, appears on the WYSIWYG editor

Another Easy Approach: Filestack Workflows

If you want an even easier way to do this, you can with Filestack Workflows. This feature allows you to set up and chain certain events or tasks. In this case, we want to use the SFW checker. After checking the content, Filestack should store it if it’s SFW and remove it otherwise.

To do this, go to “Workflows” in your Filestack dashboard and create a new workflow. Click the “+” button to see a list of tasks. Search for and choose “sfw” under the “Intelligence” tab and click “Save.” Next, add another task to your workflow and look for and select “remove” under the “Transform” tab. Add a condition and specify “Path” as “sfw” and “Condition” as “eq” (as in equals). For the value field, enter “false” since we want the workflow to remove the content if it’s NSFW. Afterwards, click “Save” and do the same for SFW results (look for the “store” task instead of the “remove” one). This time, set “Value” to “true” and click the save button.

Adding SFW checking tasks in Filestack Workflows

When you’re done configuring your workflow, click “Picker configuration” to see how the workflow will fit into your code. To learn more about setting SFW checking using Filestack Workflows, read this documentation or watch this tutorial.

Conclusion

Ensuring a safe, professional, and user-friendly environment is crucial to most applications nowadays. By integrating SFW-checking features into your WYSIWYG editor, you take a proactive step toward regulating user-uploaded content better. With tools like Froala Editor and the natively integrated Filestack, you can seamlessly filter NSFW content while promoting a positive and engaging user experience. The steps that we delved into today are just the beginning. Empower your application and its community by prioritizing safety and trust, one upload at a time.

Get your Filestack API here for free.

How to Add Image Editing Capabilities to Your WYSIWYG Editor

An editor showing the crop, filter, text, and border functionalities for images

Image editing is a powerful feature for every WYSIWYG editor. It significantly enhances the capabilities of an application and delights users who want to do more with their uploaded images. Nowadays, users expect applications to have image editing features, but implementing such features is not as trivial as it sounds. For example, in some LMS, CMS, and document management systems, users require image editing within a WYSIWYG HTML editor. Uploading images and other media might be a normal feature for editors to have, but image editing usually isn’t. That’s why in this tutorial, I’ll show you how you can implement image editing capabilities within your editor. We’ll explore image cropping, filters, adding texts, and more.

Key Takeaways

  • Use Froala’s built-in Filestack image transformations to easily add image editing
  • Customize Filestack’s options to have more control over image uploads and edits
  • Handle Froala events to perform actions whenever the user interacts with Filestack
  • Set up the WYSIWYG editor in a few seconds and with a few lines
  • Save plenty of time by integrating an editor with built-in image editing

Setting up the WYSIWYG Editor

Before we get into image editing, we first need a WYSIWYG editor. To do this, include the Froala Editor files in your application however you want (we’re going with CDN in this one). And then, we initialize the editor inside a div element with the id “froala-editor:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Image Editing with Froala and Filestack</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />
</head>

<body>
    <div class="container-fluid vh-100">
	<div class="row h-100">
            <div class="col-md-6 mx-auto my-auto">
                <div id="froala-editor"></div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    
    <!--Load Froala and Filestack files-->
    <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
    <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
    <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
    <!--Load your own JS file/s here-->
    <script src="js/index.js"></script>
</body>
</html>

On your JS file, add the following line of code:

new FroalaEditor('#froala-editor');

When you run your web application, you should then see the following screen:

The initial state of the WYSIWYG editor

Once we get our editor running, we’ll add image editing features by enabling the natively integrated Filestack plugin. We do that by specifying options for the editor:

new FroalaEditor('#froala-editor',{
    filestackOptions: {
        filestackAPI: 'YourFilestackAPIKey',
        uploadToFilestackOnly: true,
        pickerOptions: {
            accept: [
                '.pdf',
                'image/jpeg',
                'image/png',
                'image/*',
                'video/*',
                'audio/*'
            ],
            fromSources: [
                'local_file_system',
                'url',
                'facebook',
                'instagram'
            ]
        }
    },
    toolbarButtons: {
        'moreRich': {
            'buttons': ['openFilePickerImageOnly', 'openFilePickerVideoOnly', 'openFilePicker', 'insertLink', 'insertTable', 'emoticons', 'specialCharacters', 'insertHR'],
            'buttonsVisible': 3
        },
        'moreText': {
            'buttons': ['bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'clearFormatting']
        },
        'moreParagraph': {
            'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
        },
        'moreMisc': {
            'buttons': ['undo', 'redo', 'fullscreen', 'selectAll', 'html', 'help'],
            'align': 'right',
            'buttonsVisible': 2
        }
    },
    events: {
        'filestack.uploadedToFilestack': function (response) {
            console.log("Callback is triggered for upload to Filestack ",)
        },
        'filestack.filestackPickerOpened': function (response) {
            console.log("Callback is triggered for picker opened ",)
        },
        'filestack.filestackPickerClosed': function (response) {
            console.log("Callback is triggered for picker closed ",)
        },
        'filestack.uploadFailedToFilestack': function (response) {
            console.log(response);
        },
    },
    heightMin: 500,
    heightMax: 1000
});

Here, we declared some options for the editor’s toolbar buttons, size, events, and additional options for Filestack. In the filestackOptions property, we declared our Filestack API key, a boolean that determines whether files are uploaded exclusively to Filestack, and a few picker options. These options determine the allowed file types and sources. And if you haven’t already, get an API key by creating a free Filestack account. After setting both Froala and Filestack up, we’re done! You can now use an advanced WYSIWYG editor with image editing features within your application. Also, here’s how the editor should appear now:

Froala Editor with Filestack buttons

Notice how the editor now has better sizing. More importantly, we now have buttons with the Filestack icons in them. These buttons allow users to upload images, videos, and other files through Filestack. Now, to show you some of the Filestack plugin’s capabilities, let’s dive into some image editing use cases.

Use Cases for Image Editing within the WYSIWYG Editor

Cropping an Image

After uploading an image, click on it, and a Filestack icon should show up beside it. Click the icon to enter the file transformations view. Under the “Transform” tab, choose “Crop” and adjust the image to your liking. Note that you can crop and rotate the image even before you upload it. Let’s upload an image and crop it afterwards using Filestack transformations.

Cropping an uploaded photo of Matterhorn using Froala WYSIWYG editor

This is how cropping an image using Filestack should look. You’ll get to choose from the different cropping options, including free-form, circle, square, and 16:9, which we use here. When you’re done cropping, click the check button and hit “Save.”

Applying Filters

Filters have become an important part of every app that handles images. With Filestack and Froala, you can accomplish this by clicking on the Filestack icon beside an uploaded image and going to the “Filters” tab. From there, you can choose from many image filters, such as Polaroid, Sepia, Grayscale, and more. Now, let’s apply a filter to our cropped image.

Applying a filter to the Matterhorn demo image

Adding and Enhancing Text

Whether it’s for adding titles to chapter titles or prices to products or real estate listings, text is essential for image editing. Using Froala Editor, you can add text with different fonts and styling. Using the image from earlier, let’s add some text and enhance it.

Inserting some sample text to the edited Matterhorn photo

Inserting a Border

We can also easily insert a border or frame to our image using Filestack’s transformation features. Let’s go to the “Border” tab and customize a border for our image:

Adding a border to the photo within the WYSIWYG editor

After clicking “Save,” we should see our enhanced image on the editor. From there, you can check the uploaded image on your Filestack dashboard. Go to “Content Browser” and you’ll see our image, which you can download separately or on your application. For reference, here’s how the image should look after performing all these operations:

The final state of the sample image after undergoing several enhancements

Conclusion

For any modern application, image editing is a valuable tool. With tools like Froala, you can speed up the implementation of a WYSIWYG editor that has superb image editing capabilities. Such tools allow you to crop, add texts and filters, insert borders, and apply overlays to your images. By following this guide, you can now get started with implementing such features without too much effort. Now, you’re ready to offer a smooth, enjoyable image editing experience that lets users fine-tune their images without leaving the editor. Enjoy!

Get your Filestack API here for free.

Froala 4.3.1: Improved Pasting and Enhanced Content Creation

Froala Release

We’re thrilled to announce Froala Editor 4.3.1 with impressive improvements to the content pasting process, enhancements to the lists plugin, and fixes for reported customer issues.

At Froala, we’re committed to delivering the best possible user experience. That’s why we maintain an ongoing feedback loop with our users, ensuring that we’re addressing your top-requested features and pain points. With this release, we’ve laser-focused on bringing those highly anticipated improvements to life.

So, what can you expect from Froala Editor 4.3.1? Read on to discover the fantastic improvements that will elevate your content creation workflow!

content pasting

Improved Content Pasting Process

Maintaining the format of pasted text has always been a challenge for users, often leading to frustration and extra work. Many editors struggle to perform this function correctly, resulting in inconsistent and messy formatting.

Imagine pasting a complex table or a styled document into your editor, only to find the layout entirely off. You have to spend valuable time fixing it, which can be incredibly annoying and disrupt your workflow.

In the latest improvements in Froala Editor, we enhanced pasting capabilities, particularly from Microsoft Word, to ensure that the original formatting of your content is preserved seamlessly, saving you time and effort.

Froala Editor has been improved to enhance pasting capabilities, ensuring that the original formatting of your content is preserved seamlessly, saving you time and effort. Pasting from Microsoft Word, a popular text editor known for pasting issues, has been particularly problematic in the past, often resulting in lost or altered formatting and requiring manual adjustments. With the latest updates, pasting from Word is now smoother and more accurate.

Your end-users can look forward to a more seamless experience that eliminates the hassle of reformatting. With these updates, they’ll be empowered to concentrate on what truly matters: creating outstanding content that resonates

Key improvements in this release for content pasting include:

  • Preserve the font size for text pasted from Microsoft Word by prioritizing CSS font-family styles over embedded Rich Text Format (RTF) styles.
  • Maintaining list numbering order and style, even with extra white spaces.
  • Preventing the insertion of inappropriate list items when copying and pasting part of a list item.
  • Ensuring the Word Paste feature functions correctly across Android Chrome versions.
  • Preserving table formatting when pasting from Word365.
  • Maintaining nested table column widths without parent table overflow.
  • Avoiding content duplication when multiple editor instances exist on the same page.

Enhancements to The Lists Plugin

Froala Editor allows users to create and manage various types of lists within their content using the Lists plugin. This plugin supports not only basic lists like numbered (ordered) and bulleted (unordered) lists but also advanced list types such as lower Greek and upper Roman numerals.

In this release, Froala enhanced list indenting and outdenting capabilities. We have updated the code in order to account for selections spanning multiple list levels. Additionally, the editor now considers the text-indent CSS property, disabling the outdent button if the next outdent would push the text outside the editor’s boundaries.

But that’s not all! Froala has also ensured that the editor preserves the first item’s list type when indenting the list further. This means the intended list structure is always maintained, keeping your content organized and consistent.

Much More…

We have addressed various issues reported by our users to enhance the overall performance and stability of Froala Editor. These include:

  • Resolved the incorrect word replacement issue caused by the Microsoft Edge autocorrect feature.
  • Resolved the issue where inserting a table on an Android device would result in one of the table cells being automatically focused.
  • Resolved the issue where the href attribute values were being truncated when the editor was loaded with pre-existing HTML content.

These enhancements demonstrate Froala’s commitment to continuously improving the editor’s functionality and addressing user feedback to provide a superior content creation experience.

Please find the complete changelog list here.

How Can I Update?

Don’t miss out on the benefits of the latest Froala 4.3 release. Update today and experience the enhanced editing features and improvements.

If you are using a plain JavaScript library or other framework, check the get started page to know how to download the latest Froala Editor release and how to include it in your project based on your preferred method.

If you are using a plain JavaScript library or other framework, follow the table below to learn how to download the latest Froala Editor release and include it in your project based on your preferred method.

Method How to download Include in your project
CDN
<!-- Include Editor stylesheet-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />

<!-- Include Editor JavaScript file-->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/js/froala_editor.pkgd.min.js"></script>
CDN (Always the latest version)
<!-- Include Editor stylesheet-->
<link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />

<!-- Include Editor JavaScript file-->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
NPM
npm install froala-editor
<!--

Replace the {download-folder-path} in the following example with the path to the folder containing the stylesheet file e.g.

../css/froala_editor.pkgd.min.js

-->

<link href="{download-folder-path}/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />

<!--

Replace the {download-folder-path} with the path to the folder containing the JS file e.g.

../js/froala_editor.pkgd.min.js

-->

<script type="text/javascript" src="{download-folder-path}/froala_editor.pkgd.min.js"></script>
bower
bower install froala-wysiwyg-editor
NO Package Manager Download Froala WYSIWYG Editor files using the download form here.
Integrated with a Framework Select your preferred framework from 17 different popular frameworks.
Other options Check here for other options for using Froala WYSIWYG Editor in your project.

For Froala Editor Version 2 Users:

Follow this migration guide for step-by-step instructions on upgrading from version 2.

Try The Latest Froala Editor

Explore a variety of examples that demonstrate the functionality of the Froala HTML Editor.

Support and Feedback

We are dedicated to always offering the best possible experience for all our users. We believe this release, meant to enhance Typescript support, is a stepping stone towards that commitment. We encourage you to try this improved Typescript support and give us your valuable feedback. Your input is crucial for delivering continuous enhancement and meeting your evolving needs. Thank you for being a valuable part of our vibrant and growing community.
We would like to hear what you think of the latest release! Join us on our GitHub Community to chat with our product manager, developers, and other members of the Froala team.

Change Log

Get Started

  • You can download and start using Froala in less than five minutes following our get-started guide.

Technical Questions

Get your Filestack API here for free.

Customizing Filestack File Picker: the New Froala File Uploading Option – Part 1

customization

Froala, a popular rich text editor, just got even better with its latest update. Froala V4.3+ now supports the Filestack File Picker as a new option for uploading images, videos, and files.

The Filestack File Picker offers a user-friendly interface that improves the uploading file experience. By integrating Filestack, Froala users can now leverage its robust file management capabilities to simplify the entire upload process, delivering a much smoother experience for their users.

One of the advantages of Filestack File Picker is its many customization options, such as restricting file types and setting upload size limits. In this article, we’ll dive into some of the customization options available to Froala users when integrating the Filestack File Picker.

By leveraging these powerful features, you can create a truly seamless and intuitive file management workflow within your Froala-powered applications, taking the user experience to new heights.

How Can I Customize The File Picker Within the Froala Editor?

To start using Filestack File Picker for file uploading within the Froala editor, you have to include its scripts and stylesheet files within your project and configure the filestackOptions.filestackAPI option with a valid API key which you can get from Filestack DevPortal for free.

Here’s an example of what your HTML code might look like:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" name="viewport" content="width=device-width, height=device-height, initial-scale=1.0,
            maximum-scale=1.0" />
        <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet"
            type="text/css" />
              <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

    </head>
    <body>
        <div id="froala-editor"> </div>
        <script type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
         <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
  <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
        
        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                  }
                });
        </script>
        </body>
</html>

To customize the File Picker, you can add your custom configuration to the filestackOptions.pickerOptions option. In this case, the Froala initialization code would be similar to:

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        transformationsUI: true
      }
    }
  });

Customization Options

Restrict File Types

You can restrict the file types that users can upload by setting the accept option within the  filestackOptions.pickerOptions configuration. For example, to only allow image files, you can use accept: 'image/*'. You can also specify multiple file types by providing an array, such as accept: ['image/*', 'video/*', 'application/pdf']. This ensures that users can only upload the file types that are relevant to your application, enhancing the overall user experience. The formats that you can assign through this option are:

  • .pdf <- accept PDF files.
  • image/jpeg <- any MIME type commonly known by browsers
  • image/* <- accept all types of images
  • video/* <- accept all types of video files
  • audio/* <- accept all types of audio files
  • application/* <- accept all types of application files
  • text/* <- accept all types of text files
  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        accept: ['image/*', 'video/*']
      }
    }
  });

If you need to restrict other file types, you can use the acceptFn option which allows you to provide a custom function to determine which files are accepted. This gives you full control over the file type validation process.

The acceptFn has two parameters:

  • PickerFileMetadata
  • PickerAcceptFnOptions

And you have to return the Promise<string> .

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        acceptFn: (file, options) => {
           return options.mimeFromMagicBytes(file.originalFile).then((res) => { // we can check mimetype from magic bytes
             //console.log(options.mimeFromExtension(file.originalFile.name)); // or check extension from filestack extensions database
             // throw new Error('Cannot accept that file') // we can throw exception to block file upload
             // return Promise.reject('Cannot accept that file'') // or reject a promise
             return Promise.resolve();
           });
        }
      }
    }
  });

By leveraging the acceptFn, Froala users can ensure that only the appropriate files are uploaded, maintaining the integrity and consistency of the content within their Froala-powered applications. This level of customization empowers them to tailor the file upload experience to their specific needs, enhancing the overall user experience.

Restrict File Size

You can also set upload size limits using the maxSize option within the filestackOptions.pickerOptions configuration. This allows you to restrict the maximum file size that users can upload, helping to manage storage and bandwidth constraints. For example, to set a 10MB limit, you can use maxSize: 10 * 1024 * 1024. This ensures that users cannot upload files that exceed your specified size limit, improving the overall file management process.

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        maxSize: 10 * 1024 * 1024
      }
    }
  });

By setting appropriate size limits, you can ensure that the file upload process aligns with your application’s requirements and provides a seamless user experience.

Restrict Allowed Image Dimensions

You can also set accepted image dimensions using the imageDim option within the filestackOptions.pickerOptions configuration. This allows you to specify the exact width and height for uploaded JPEG, PNG, and BMP images, ensuring that they meet your application’s requirements.

Local and cropped images will be resized (upscaled or downscaled) to the specified dimensions before uploading. The original height to width ratio is maintained. To resize all images based on the width, set [width, null], e.g. [800, null]. For the height set [null, height], e.g. [null, 600].

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        imageDim: [800, 600]
      }
    }
  });

This helps maintain visual consistency and quality within your Froala-powered content.

Instead, if you prefer to give your users some freedom, you can use imageMax and imageMin options where imageMax allows you to set the maximum allowed dimensions. Images bigger than the specified dimensions will be resized to the maximum size while maintaining the original aspect ratio.

imageMin allows you to set the minimum allowed image dimensions. Images smaller than the specified size will be upscaled to the minimum size while maintaining the original aspect ratio.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        imageMax: [1800, 1600],
        imageMin: [800, 600],

      }
    }
  });

This gives users more flexibility while still ensuring the images meet your application’s requirements. By leveraging these options, you can strike a balance between maintaining visual consistency and providing users with a more open file upload experience.

Restrict Upload Number

You can also restrict the number of files that users can upload at once by setting the maxFiles option within the filestackOptions.pickerOptions configuration. This helps you manage the upload process and ensure that users don’t overwhelm your application with too many files at once. For example, to limit the number of files to 5, you can use maxFiles: 5.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         maxFiles: 5,
         
      }
    }
  });

Additionally, you can set the minimum number of files that users must upload at once by setting the minFiles option within the filestackOptions.pickerOptions configuration. This can be useful if your application requires a certain number of files to be uploaded together, such as multiple images for a product listing. For example, to require at least 3 files to be uploaded, you can use minFiles: 3.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         maxFiles: 5,
         minFiles: 3
      }
    }
  });

By setting both maxFiles and minFiles, you can strike a balance between providing flexibility and maintaining control over the file upload process, ensuring that your Froala-powered application meets your specific requirements.

By default, the upload process didn’t start until the user hit the “Upload“ button. If you want to start uploading automatically when maxFiles is hit, set the startUploadingWhenMaxFilesReached option to true.

Restrict Concurrency Upload Number

You can also restrict the number of concurrent file uploads by customizing the concurrency option within the filestackOptions.pickerOptions configuration, which is by default set to 4. This allows you to control the maximum number of files that can be uploaded simultaneously, preventing your application from being overwhelmed and ensuring a smooth upload experience. By setting an appropriate value for concurrency, you can balance the need for efficient file uploads with the available resources and bandwidth of your application.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         concurrency: 2,
      }
    }
  });

 

Restrict Video Resolution

You can also restrict the video resolution of uploaded files using the videoResolution option within the filestackOptions.pickerOptions configuration. This allows you to specify the maximum width and height for video files to one of these values “320×240”, “640×480” or “1280×720”, ensuring that they meet your application’s requirements. By default, it is "640x480". By setting appropriate limits, you can optimize storage, bandwidth, and playback performance, while maintaining the desired visual quality for your Froala-powered content.

 

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         videoResolution: "1280x720",
      }
    }
  });

 

Customize Upload Sources

You can also specify the upload sources that users can choose from by setting the fromSources option within the filestackOptions.pickerOptions configuration. This allows you to restrict the file selection to specific sources, such as local device storage, cloud storage providers, or social media platforms. For example, to only allow users to upload files from their local device and Google Drive, you can use fromSources: ['local_file_system', 'google_drive']. This helps streamline the file upload process and ensures that users can only access the file sources that are relevant to your application. Valid ones are:

  • local_file_system – Default
  • url – Default
  • imagesearch – Default
  • facebook – Default
  • instagram – Default
  • googledrive – Default
  • dropbox – Default
  • webcam – Uses device menu on mobile. Not currently supported in Safari and IE.
  • video – Uses device menu on mobile. Not currently supported in Safari and IE.
  • audio – Uses device menu on mobile. Not currently supported in Safari and IE.
  • box
  • github
  • gmail
  • googlephotos
  • onedrive
  • onedriveforbusiness
  • customsource – Configure this in your Filestack Dev Portal.
  • unsplash

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         fromSources: ['local_file_system', 'google_drive'],
      }
    }
  });

Cleaning JPEG Image EXIF

You can also configure Filestack to automatically remove EXIF data from JPEG images during the upload process. This can be useful for reducing the file size and ensuring that sensitive metadata, such as location information, is not inadvertently included in the uploaded images. To enable this feature, you can set the cleanupImageExif option within the filestackOptions.pickerOptions configuration to true.

 

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         cleanupImageExif: true,
      }
    }
  });

 

This option also offers the ability to keep image orientation by assigning it to an object and setting a keepOrientation property to true. Moreover, you can keep image color profiles by setting keepICCandAPP property to true.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         cleanupImageExif: {
           keepOrientation: true,
           keepICCandAPP: false
         },
      }
    }
  });

By doing so, you can streamline the file upload process and maintain better control over the data being stored in your Froala-powered application.

Enable Transformation UI

You can also enable the Transformation UI to allow users to perform advanced image editing, including filters and overlay text, alongside basic operations like cropping and rotating, directly in the file picker. To enable this feature, you can set the transformationsUI option within the filestackOptions.pickerOptions configuration to true.

This provides users with a more robust file editing experience, allowing them to customize their uploads before they are sent to your application.

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        transformationsUI: true
      }
    }
  });

Conclusion

In this article, we’ve explored the powerful customization options available when integrating the Filestack File Picker into your Froala-powered applications. By leveraging features like file type restrictions, upload size limits, image dimension controls, and more, you can create a truly seamless and intuitive file management workflow for your users.

These customization capabilities empower Froala users to tailor the file upload experience to their specific needs, ensuring the integrity and consistency of the content within their applications. As we continue to explore the Filestack integration in future articles, we’ll cover File Picker events and the user interface customization options.

To get started, sign up for a free Filestack account today and start enhancing your Froala-powered applications with a truly customized file upload experience. With Filestack’s robust file management capabilities and Froala’s industry-leading rich text editing features, you can take your content creation and management to new heights.

Get your Filestack API here for free.

How to transform your LMS with a React WYSIWYG HTML editor, Part 3

Editing existing content ensures that an application or its users accurately reflect any updates or modifications. This makes it a vital feature in any application, including the simple LMS that we’ve been building. In this final part of our React WYSIWYG HTML editor-powered LMS tutorial, we’ll focus on enabling content editing for a chapter. We’ll guide you through using Froala’s editing interface to save changes seamlessly, modifying our React components, and setting up the backend for saving changes in a chapter. By the end of this tutorial, you’ll have a simple and robust LMS where users can create, read, and update chapters. Plus, you’ll learn how to edit images uploaded via Filestack—all within an intuitive editing environment. Let’s get started!

Key takeaways

  • Understand how to save edited content from Froala to SQL Server
  • Learn about editing images uploaded through Filestack within the editor
  • Ensure seamless content updates in the React frontend
  • Handle potential issues properly in both the frontend and backend
  • Experiment more with Filestack and Froala to implement more functionality

Recap and objectives

This tutorial is the final one of a three-part series. In Part 1, we created our React LMS, which allowed users to load and save courses and chapters. For the latter, we used Froala to create the chapter’s contents. Moreover, to upload documents and images, we used Filestack, which is natively integrated into Froala. On the other hand, Part 2 explored how we can read or load a chapter’s contents back to the UI and the editor. We were able to display the contents accurately and as they were entered. If you missed any of the previous articles, click on the links below:

  • Part 1 (Saving content from the React WYSIWYG HTML editor to the database)
  • Part 2 (Loading content from the database back to the editor)
  • Creating a free Filestack account

In Part 3, we’ll modify our codes to allow users to update content. For simplicity, we’ll only allow updates for a chapter’s title, description, and contents. To accomplish this, we’ll edit the “details” view of a chapter and include an “Edit” button. Clicking the button should replace the text with input fields and add two new buttons: one for saving and one for canceling. Additionally, clicking the edit button should allow the user to modify content within Froala. Afterwards, we’ll send the updated contents to the backend for saving.

Setting up update operations for the React WYSIWYG HTML editor

Edit the Froala component

Let’s start off by modifying our Froala component so that it now checks when the user is in “editing” mode. We also need to ensure that we set the chapter contents every time a user changes something within the editor. Replace our initial code for FroalaComponent.jsx with:

import React, { useEffect } from 'react';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditorComponent from 'react-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

function FroalaComponent({ setChapterContent, setChapterImage, initialContent, isEditing}) {
  const config = {
    readonly: !isEditing,
    filestackOptions: {
      uploadToFilestackOnly: true,
      filestackAPI: 'yourFilestackAPIKey',
    },
    events: {
      'contentChanged': function () {
        if(isEditing){
          const updatedContent = this.html.get();
          setChapterContent(updatedContent);
        }
      },
      'filestack.uploadedToFilestack': function (response) {
        if (response && response.filesUploaded[0].url) {
          setChapterImage(response.filesUploaded[0].url); // Set the image URL in the parent state
        }
        else{
          console.error("Image upload failed, no URL found in response", response);
        }
      }
},
  };

  useEffect(() => {
    const filestackScript1 = document.createElement('script');
        filestackScript1.src = 'https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js';
        filestackScript1.async = true;
        document.body.appendChild(filestackScript1);

        const filestackScript2 = document.createElement('script');
        filestackScript2.src = 'https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js';
        filestackScript2.async = true;
        document.body.appendChild(filestackScript2);

        const filestackScript3 = document.createElement('script');
        filestackScript3.src = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js';
        filestackScript3.async = true;
        document.body.appendChild(filestackScript3);

        const filestackStylesheet = document.createElement('link');
        filestackStylesheet.rel = 'stylesheet';
        filestackStylesheet.href = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css';
        document.head.appendChild(filestackStylesheet);

    return () => {
      document.body.removeChild(filestackScript1);
      document.body.removeChild(filestackScript2);
      document.body.removeChild(filestackScript3);
      document.head.removeChild(filestackStylesheet);
    };
  }, []);

  return (
    <div className="editor">
      <FroalaEditorComponent tag='textarea' config={config} model={initialContent} onModelChange={(content) => setChapterContent(content)}/>
    </div>
  );
}

export default FroalaComponent;

Note that we added a new parameter called “isEditing” to the FroalaComponent function. This determines whether a user is in read mode or edit mode. We’ll only allow any changes if the user is editing. Lastly, we added an onModelChange property to the FroalaEditorComponent to set the chapter’s contents every time the user modifies the editor’s contents. After updating our FroalaComponent, we’ll update the “chapter details” screen.

Update the form and the React WYSIWYG HTML editor

Now, we’ll add the “Edit,” “Save,” and “Cancel” buttons to the ChapterDetails component. Replace your ChapterDetails.jsx code with:

import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import FroalaComponent from './FroalaComponent';

function ChapterDetails() {
  const { courseId, chapterId } = useParams();
  const [chapter, setChapter] = useState(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editedChapter, setEditedChapter] = useState({});
  const [chapterImage, setChapterImage] = useState('');

  const fetchChapterDetails = async () => {
    const response = await fetch(`path-to-backend/getChapterById.php?chapterId=${chapterId}`);
    const data = await response.json();
    setChapter(data);
    setEditedChapter({
      ...data,
      chapter_id: chapterId
    });
  };

  useEffect(() => {
    fetchChapterDetails();
  }, [chapterId]);

  if (!chapter) {
    return <p>Loading chapter details...</p>;
  }

  const handleSetChapterContent = (content) => {
    console.log("Updated chapter content:", content);
    setEditedChapter((prev) => ({
      ...prev,
      chapter_content: content,
    }));
  };

  const handleEditChapter = () => {
    setIsEditing(true);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditedChapter(chapter);
  };

  const handleSaveEdit = async (event) => {
    event.preventDefault();
    const response = await fetch('path-to-backend/updateChapter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(editedChapter)
    });

    if(response.ok){
      setChapter(editedChapter);
      setIsEditing(false);
    }
    else{
      console.error('Failed to save chapter.');
    }
  }

  const handleInputChange = (e) => {
    const {name, value} = e.target;
    setEditedChapter({
      ...editedChapter,
      [name]: value
    })
  }

  return (
    <div>
      <form onSubmit={handleSaveEdit}>
        <h1>Chapter Details</h1>
        <div>
          <Link to={`/chapters/${courseId}`}>
            <button>Back to Chapters</button>
          </Link>
        </div>
        {isEditing ? (
          <>
            <button type="submit">Save</button>
            <button type="button" onClick={handleCancelEdit}>Cancel</button>
          </>
        ) : (
          <button type="button" onClick={handleEditChapter}>Edit</button>
        )}

        <div>
            <div className="chapter-card">
              <h3>
                {isEditing ? (
                  <input
                    type="text"
                    name="chapter_title"
                    value={editedChapter.chapter_title}
                    onChange={handleInputChange}
                  />
                ) : (
                  chapter.chapter_title
                )}
              </h3>
              <p>
                {isEditing ? (
                  <textarea
                    name="chapter_description"
                    value={editedChapter.chapter_description}
                    onChange={handleInputChange}
                  />
                ) : (
                  chapter.chapter_description
                )}
              </p>
              <FroalaComponent 
                initialContent={isEditing ? editedChapter.chapter_content : chapter.chapter_content}
                setChapterContent={handleSetChapterContent}
                setChapterImage={setChapterImage}
                isEditing={isEditing} 
              />
              <p>This is how the Filestack URL will appear if stored separately in the database: <a href={chapter.chapter_img_url}>{chapter.chapter_img_url}</a></p>
              <p>Date Published: {chapter.date_published ? new Date(chapter.date_published.date).toLocaleDateString() : 'N/A'}</p>
            </div>
        </div>
      </form>
    </div>
  );
}

export default ChapterDetails;

This is similar to our old code, except that it now checks whether the user is editing or just viewing. We also added a few new functions for setting the editing mode and updating the chapter contents. To check whether the user is in editing mode or not, we added some conditional statements in the DOM that check the value of isEditing, which is set to false by default. Depending on its value, we either load the text or input fields for the chapter title and description. For saving the contents, we declare a new function called handleSaveEdit, which sends the data to an endpoint called updateChapter.php. Once the server returns a response, we set the modified content as the new content of the fields and the React WYSIWYG HTML editor. Now that we’ve finished the front-end part of the LMS, let’s deal with the backend.

Save the changes in the database

Create a new PHP file (updateChapter.php in our case). Afterwards, insert the following code:

<?php
    header('Access-Control-Allow-Origin: http://localhost:3000');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    header("Content-Type: application/json");
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header("HTTP/1.1 200 OK");
        exit();
    }
    include "connection.php";

    $input = json_decode(file_get_contents("php://input"), true);

    $chapter_id = $input["chapter_id"];
    $chapter_title = $input["chapter_title"];
    $chapter_description = $input["chapter_description"];
    $chapter_content = $input["chapter_content"];

    $query = "
        UPDATE chapter SET
        chapter_title = ?,
        chapter_description = ?,
        chapter_content = ?
        WHERE chapter_id = ?
    ";

    $params = array($chapter_title, $chapter_description, $chapter_content, $chapter_id);
    $result = sqlsrv_query($conn, $query, $params);

    if($result===false){
        echo json_encode(["error" => "Failed to save chapter"]);
    }
    else{
        echo 1;
    }
    sqlsrv_close($conn);
?>

The file starts by first establishing a connection to the database and then getting the contents from our React application. Afterwards, we initialize and run a query that updates the title, description, and contents of a chapter. And that’s the last step, at least in this tutorial. Next up, we’ll run and test the application.

Run the application

After running the application, we should see the same “Courses” screen that we already had before. Click “View Course” on any of the courses, and you should see the list of chapters within the course. Let’s click the “Details” button. The application will take us to the screen that we made in Part 2. However, we now have the “Edit” button. Click on it, and you’ll see the following screen:

The "editing mode" of the LMS chapter

The “Save” and “Cancel” buttons have now replaced the edit button. Also, the title and description labels now changed into editable input fields. Let’s try changing only the title and the description fields and clicking the save button. We should have something like:

The chapter title and description have been edited. The "Save" button also turned back into "Edit"

Now, let’s click “Edit” again and click on the image. We should see the Filestack transformation button. Let’s click it and apply a Polaroid filter.

Choosing an image filter for the uploaded image using Filestack

After clicking “Save” within the file picker, let’s also add line breaks and a sentence to the text in the editor. And then, let’s click the outer “Save” button on the chapter screen. We should get something similar to this screen:

The contents of the React WYSIWYG HTML editor have been changed

Finally, let’s check our database and Filestack account for updated content:

From the images above, it seems that we successfully changed the contents of our chapter_title, chapter_description, and chapter_content fields. Furthermore, we have an updated file on the Filestack dashboard. Downloading it will yield the following image:

The updated image that was saved via Froala and downloaded on the Filestack dashboard

And that’s where our 3-part series about reinforcing your React LMS’ content editing with Froala and Filestack ends. Note that this is just a tutorial on making React, Froala, and Filestack work together to form a reliable and powerful LMS. If you want to create an LMS or similar application, you should consider significantly more factors, such as security, optimization, best practices, and more. For example, you should always trim input on the back end and check them for errors or vulnerabilities. Additionally, you should parameterize queries, prevent duplicates, commit or rollback transactions, and more. You can also explore the more advanced features of Filestack, such as OCR and object recognition. To get started more easily, check out the repository for this demo.

Conclusion

By now, you’ve built a simple yet multi-featured LMS with advanced React WYSIWYG HTML editor capabilities. You’ve gone from saving content for a course to loading it back to the frontend and editing it. As you continue developing, always remember that you can implement complex functionality by doing things one step at a time and by relying on tools that are already there. Add more interactive elements, such as chat or study groups. Expand with and learn new tools. Refine the UI, UX, and security of your application. You might still have plenty to do, but hopefully with this tutorial, you’re already on your way to building something remarkable. Enjoy and good luck!

Get your Filestack API here for free.

Explore The Transformation Options within The Froala New File Uploading Tool

Image transformation UI

Tired of the same old image editing options in your content editor? Get ready to unlock a new world of creative possibilities with Froala’s latest file-uploading feature!

Froala integrated Filestack to bring you a powerful, user-friendly file uploader that goes way beyond basic image cropping and resizing. With the Filestack integration, you can now transform your uploaded images in ways you never thought possible – right from within the Froala editor.

Imagine being able to apply eye-catching filters, adjust the brightness and contrast, or even swap out the background of your images, all with just a few clicks. Sounds intriguing? In this post, we’ll dive into the various image transformation options available through the Filestack TUI and show you how to unleash your creative side while building content for your Froala-powered website or app.

By the end, you’ll be equipped with the knowledge to take your visual content to the next level and leave your readers thoroughly impressed. So, what are you waiting for? Let’s get started!

Getting Started with the Transformation UI

To use the Transformation UI within the Froala editor, you’ll need to follow a few simple steps:

  1. Get a Filestack API Key: Filestack is the service that powers the Transformation UI. Get a free Filestack API key now.
  2. Include the Required Scripts and Stylesheets: In your HTML file, you’ll need to include the Filestack JavaScript library, the Transformation UI scripts, and the Transformation UI stylesheet. This will give you access to all the powerful image editing tools.
  3. Configure the Froala Editor: When you initialize the Froala editor, you’ll need to provide your Filestack API key in the filestackOptions.filestackAPI setting.

Here’s an example of what your HTML code might look like:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" name="viewport" content="width=device-width, height=device-height, initial-scale=1.0,
            maximum-scale=1.0" />
        <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet"
            type="text/css" />
              <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

    </head>
    <body>
        <div id="froala-editor"> </div>
        <script type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
         <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
  <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
        
        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                  }
                });
        </script>
        </body>
</html>

With this setup, an “Image Transformation” button will appear when you click on an image uploaded using Filestack. Clicking this button will open the Transformation UI, allowing you to edit the image in various ways before inserting it into the Froala editor.

Transformation button

If you want the Transformation UI to be available immediately after uploading an image using the “Filestack Upload” button, you can enable the transformationsUI option within the filestackOptions.pickerOptions setting.

        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                    pickerOptions: {
                      transformationsUI: true,
                    }
                  }
                });
        </script>

Now when you click “Upload with Filestack”, you can select an image to upload. Once the image is uploaded, a thumbnail will appear, and an “Edit” button will appear on the right. Clicking the “Edit” button will open the transformation UI, allowing you to edit the image before inserting it into the editor.

Filestack upload

If you are using a front-end framework, check the following guide:

Explore Transformation UI: A Powerful Image Editing Tool

The Transformation UI is an intuitive image editing tool that appears when you click on an image uploaded using Filestack. This tool allows you to make various changes and enhancements to your images right within the Froala editor.

When you open the Transformation UI, you’ll see the image displayed in the center of the editor. At the top, you’ll find a few helpful controls:

  • Undo Button: On the left, you’ll see an “Undo” button that allows you to revert any changes you’ve made to the image.
  • Zoom Options: In the center, you’ll find zoom controls that let you adjust the size of the image within the editor.
  • Cancel and Save Buttons: On the left, you’ll see a “Cancel” button to close the editor without saving any changes, and a “Save” button to apply your edits and insert the updated image into the Froala editor.

At the bottom of the Transformation UI, you’ll find a variety of transformation options, including filters, adjustments, and overlays. Simply click on the option you want to apply it to the image. The changes will be shown in real time, so you can preview the results before finalizing your edits.

Transformation User Interface

This powerful image editing tool empowers your users to create visually stunning content with ease. By allowing them to enhance and transform their images right within the Froala editor, you’re giving them the ability to elevate the visual appeal of their content and captivate their audience.

Available Transformation Options

The Transformation UI within the Froala editor provides a range of powerful tools to enhance your images. Let’s dive into the key features:

Crop

The Crop tool allows you to select a specific area of the image and remove the unwanted parts. This is useful for focusing the viewer’s attention on the most important part of the image. You can adjust the crop box by dragging the corners or edges, and the image will update in real-time. Once you’re satisfied with the crop, simply click the “Save” button to apply the changes.

Image Crop

Froala offers several pre-defined crop options:

  • Portrait (16:9): This is ideal for social media posts, as it ensures images fit seamlessly on platforms like Instagram or Facebook.
  • Square: A square-shaped crop that you can resize and position as needed.
  • Circle: A circular crop that always maintains a perfect circle shape as you resize and position it.
  • Custom: A rectangular crop that you can freely resize and position to suit your needs.

Image crop

Resize

Resizing images is important for optimizing file size, fitting specific layouts, and ensuring consistent quality across devices. The Resize tool in the Transformation UI allows you to easily adjust the width and height of the image, while maintaining the original aspect ratio or changing it as needed. This gives you precise control over the final image size, helping you create a cohesive and visually appealing layout within the Froala editor.

Image resize

Flip and Rotate

Users often need to flip or rotate images to correct the orientation or achieve a specific visual effect. The Transformation UI provides four options for this:

  • Flip horizontally
  • Flip vertically
  • Rotate 90 degrees clockwise
  • Rotate 90 degrees counter-clockwise

Image flip and rotate

These tools empower users to optimize their images and ensure they are displayed correctly within the Froala editor.

Filters

The Transformation UI offers a variety of filters that can be applied to your images to alter their visual appeal. These filters range from subtle adjustments to dramatic effects, giving you the flexibility to find the perfect look for your content. You can experiment with different filters, adjust their intensity, and preview the changes in real time before saving the final image.

 

Enhance Presets

This feature smartly analyzes a photo and performs color correction and other enhancements to improve the overall quality of the image. You can choose from multiple presets to achieve the best results. Currently, it is available only when you open the Transformation UI from the File Picker. Here are the presets available with their purpose:

Preset Description
auto Automatically selects the best enhancement settings for a photo.
vivid Enhances depth and brightness in a photo.
beautify Ideal for portraits, this preset scans each face in the photo and adjusts corrections individually for optimal results.
beautify_plus Similar to Beautify, it applies stronger corrections with a broader range of modifications.
fix_dark It is perfect for underexposed photos or dark subjects against bright backgrounds. Turning off contrast maximizes detail in shadow areas without blowing out highlights.
fix_noise Detects and removes noise from photos while preserving details. Adjusts based on the ISO level and camera model.
fix_tint Removes abnormal tints (yellow, blue, green, etc.) caused by various lighting conditions, such as fluorescent, infrared, ultraviolet, and tungsten lights.
outdoor Enhances landscape photos by increasing color vibrancy and adjusting the contrast to reveal more detail in shadow areas.
fireworks Corrects for night skies and highlights excess colors from fireworks.

Image Adjustments

This feature allows users to adjust different image parameters to modify and enhance the visual appearance of an image. Here’s a list of different parameters you can adjust directly within the editor:

  • Blur: Softens the image, reducing detail and sharpness.
  • Brightness: Adjusts the overall lightness or darkness of the image.
  • Contrast: Alters the difference between the light and dark areas of the image.
  • Gamma: Adjusts the midtones of the image without affecting the shadows and highlights.
  • Hue: Changes the overall color tone of the image.
  • Noise: Adds or reduces random variations of brightness or color information in the image.
  • Pixelate: This creates a mosaic effect by enlarging the pixels, making the image appear blocky.
  • Saturation: Adjusts the intensity of the colors in the image.

These adjustments can be used individually or in combination to achieve the desired visual effect.

Overlay Text

The Transformation UI also allows users to overlay text on their images. This feature is useful for adding captions, titles, or other textual elements to enhance the visual communication of the content.

Users can choose from a variety of font styles, sizes, and colors, and position the text anywhere on the image. This empowers content creators to elevate their visuals and convey their message more effectively.

The text overlay tool provides a seamless way to integrate text and imagery, creating a cohesive and visually appealing final product.

Overlay Text

Overlay Image

The Transformation UI also allows users to overlay additional images on top of the main image. This can be useful for adding logos, watermarks, or other visual elements to the image. Users can resize, position, rotate, and adjust the opacity of the overlaid image to achieve the desired effect.

This feature provides a flexible way to enhance the visual impact and branding of the content within the Froala editor. The real-time preview ensures users can experiment with different overlay options and find the perfect combination.

Image Border

The Transformation UI also offers the ability to add a border around the image. Users can customize the border width, color, and style to create a polished, professional visual look.

This feature is particularly useful for framing images, separating them from the surrounding content, or adding a decorative touch. The real-time preview allows users to experiment with different border options and find the perfect balance between the image and its presentation within the Froala editor.

Elevate Your Visual Content with Froala’s Transformation UI

The Filestack integration within the Froala editor has unlocked a whole new world of creative possibilities for content creators. With the powerful Transformation UI, you now have the ability to enhance your images in ways you never thought possible – right from within your content editor.

From applying eye-catching filters and adjusting brightness and contrast, to swapping backgrounds and overlaying text and graphics, the Transformation UI puts a suite of advanced image editing tools at your fingertips. This empowers you to elevate the visual appeal of your content and leave your readers thoroughly impressed.

So what are you waiting for? Take your visual content to new heights by exploring the Transformation UI within the Froala editor. Unlock your creative potential, captivate your audience, and watch your engagement soar. Get started with the Filestack integration today and see the difference it can make for your Froala-powered website or app.

Get your Filestack API here for free.

How to transform your LMS with a React WYSIWYG HTML editor, part 2

Last time, we explored how to make a simple but powerful LMS using a React WYSIWYG HTML editor. This tool not only enhances the user experience for LMS applications but also simplifies content creation for whoever needs it. In the previous article, we built our application using React and used Froala to create the contents of a course’s chapter. Moreover, we delved into the file upload and transformation features of the natively integrated Filestack file picker. If you missed our previous discussion, check out our article on creating the React WYSIWYG HTML editor-powered LMS. In this part, we’ll dive deeper into how Froala works. Specifically, we’ll load the content that we saved in Part 1 back to the editor from SQL Server.

Key takeaways

  • Building from the code in Part 1, we added a new PHP file as well as a new component for loading the contents of a chapter.
  • We also edited FroalaComponent so that it now loads an initial content.
  • Loading previously saved content back to Froala Editor on a React application takes little time and effort.
  • Loaded content will appear exactly as they were saved, ensuring integrity and clarity within your LMS.
  • You can load Filestack-stored content together with the editor or independently from it.

Recap: Part 1 of building the React WYSIWYG HTML editor

In Part 1, we created a React application called demo-lms. We also had five components, which handled loading and saving courses, loading and saving chapters, and initializing the editor. For the FroalaEditor component, we also initialized Filestack by creating a free Filestack account and including the API key in the editor config. Finally, we created some endpoints for fetching and saving data from and to SQL Server using PHP. Now, we’ll load the contents of a chapter back to the React application and into the editor.

Understanding the data flow: From SQL Server to React

Note that in our chapter table, we have a column for a chapter’s ID, title, description, contents, publishing date, and an optional URL for a Filestack upload. To display these, we would have to write PHP code and load them via a simple SELECT query. From there, we will fetch the data from our React application with the chapter ID as the parameter and set the result as an object. That leaves us with assigning each property of the object to a DOM element. Ready to start?

Loading uploaded content into your React WYSIWYG HTML editor

Creating the API endpoint for fetching content

First, let’s create our new PHP file and name it getChapterById.php. Inside it, paste the following code:

<?php
    header('Access-Control-Allow-Origin: http://localhost:3000');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    header("Content-Type: application/json");
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header("HTTP/1.1 200 OK");
        exit();
    }
    include "connection.php";

    if (isset($_GET["chapterId"])) {
        $chapterId = $_GET["chapterId"];

        $query = "SELECT chapter_title, chapter_description, chapter_content, chapter_img_url, date_published FROM chapter WHERE chapter_id = ?";
        $params = array($chapterId);
        $stmt = sqlsrv_query($conn, $query, $params);

        if($stmt === false){
            http_response_code(500);
            echo json_encode(["error" => "Failed to query the database."]);
            exit;
        }

        $chapter = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

        if($chapter){
            echo json_encode($chapter);
        }
        else{
            http_response_code(404);
            echo json_encode(["message" => "Chapter not found"]);
        }

        sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn);
    }
    else{
        echo json_encode(["message" => "Chapter ID not provided"]);
    }
?>

This file looks a lot like the other ones we created in Part 1, except we’re now getting the chapter details from the chapter table. Don’t forget to configure your headers to prevent CORS errors. Furthermore, in a real application, you would want to have proper input and error handling, as well as more security measures than just query parameterization. After creating the PHP file, let’s move back to the front end.

Loading the content on the front end

To load the saved content back to the application, let’s first edit our current App.js and include these lines:

// other imports
import ChapterDetails from './components/ChapterDetails'


function App() {
  return (
    <Router>
      <Routes>
        ...other routes from Part 1 go here
        <Route path="/chapterDetails/:courseId/:chapterId" element={<ChapterDetails />} />
      </Routes>
    </Router>
  );
}

We’ve added an extra import for the ChapterDetails component, which we’ll create shortly, and another route to load the new component. Afterwards, we’ll want our users to navigate to the new components from the Chapters view. To do that, insert the following button to the DOM:

<Link to={`/chapterDetails/${course.course_id}/${chapter.chapter_id}`}>
     <button>Details</button>
</Link>

This button allows users to navigate to the new component with the course and chapter IDs as the parameters. The next thing we have to do is create our ChapterDetails.jsx component and add the code below:

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Link } from 'react-router-dom';
import FroalaComponent from './FroalaComponent';

function ChapterDetails() {
  const { courseId, chapterId } = useParams();
  const [chapter, setChapter] = useState(null);

  // Fetch details for the chapter
  const fetchChapterDetails = async () => {
    const response = await fetch(`http://localhost:8081/demo-lms-backend/getChapterById.php?chapterId=${chapterId}`);
    const data = await response.json();
    setChapter(data);
  };

  useEffect(() => {
    fetchChapterDetails();
  }, [chapterId]);

  if (!chapter) {
    return <p>Loading chapter details...</p>;
  }

  const handleSetChapterContent = (content) => {
    console.log("Chapter content set:", content);
  };

  return (
    <div>
      <h1>Chapter Details</h1>
      <Link to={`/chapters/${courseId}`}>
        <button>Back to Chapters</button>
      </Link>

      <div >
          <div className="chapter-card">
            <h3>{chapter.chapter_title}</h3>
            <p>{chapter.chapter_description}</p>
            <FroalaComponent initialContent={chapter.chapter_content} setChapterContent={handleSetChapterContent} />
            <p>This is how the Filestack URL will appear if stored separately in the database: <a href={chapter.chapter_img_url}>{chapter.chapter_img_url}</a></p>
            <p>Date Published: {chapter.date_published ? new Date(chapter.date_published.date).toLocaleDateString() : 'N/A'}</p>
          </div>
      </div>
    </div>
  );
}

export default ChapterDetails;

Here are a few things that we should note:

  • We’re also importing FroalaComponent here to load the editor.
  • Pass the chapterId parameter to the backend to retrieve the data. In a real LMS, you might want to pair that with the courseId if your primary key consists of both IDs.
  • We initialize our FroalaComponent with an initialContent property this time. This allows the editor to display content once initialized. Thus, we pass chapter.chapter_content as the parameter.

After creating our new component, let’s populate the React WYSIWYG HTML editor with the chapter’s contents.

Populating the React WYSIWYG HTML editor with the fetched content

To populate the editor, we need to edit FroalaComponent by adding the initialContent property that we used in the previous step. Replace:

function FroalaComponent({ setChapterContent, setChapterImage}) {
     ...
}

With:

function FroalaComponent({ setChapterContent, setChapterImage, initialContent}) {
     ...
}

Afterwards, replace

<FroalaEditorComponent tag='textarea' config={config} />

With:

<FroalaEditorComponent tag='textarea' config={config} model={initialContent} />

And we’re done! You should now see the chapter details, including its contents, when clicking the “Details” button on a chapter card. The following images demonstrate the new additions to our sample LMS:

An image showing the chapters in a course within the sample LMS

An image showing the chapter title, description, publication date, and contents. The contents are loaded accurately in the Froala Editor.

In the “Chapter Details” view, you’ll see a button for going back to the course details as well as the chapter’s title, description, contents, and publishing date. Additionally, you’ll see that you can load contents uploaded using Filestack on the editor itself or separately. Below the editor, we loaded the URL for a document (“Demo Document.pdf) after a sentence. This shows Filestack’s flexibility, giving you control over how you want to display or download your data. After clicking either the “Demo Document.pdf” link on the editor or the Filestack CDN link below, you’ll see the following:

An image that contains a PDF uploaded using Froala and Filestack.

Now, we’ve discovered how we can load contents using Filestack CDN, React, and Froala for our sample LMS. That’s another step closer to having an exceptional editing tool with file upload and transformation capabilities within your LMS!

Looking ahead: Next steps in transforming your LMS

In this second part of our LMS journey, we explored how to load saved content from SQL Server into our React WYSIWYG HTML editor. We created a new component and API endpoint and updated the old ones as well. By adding and editing a few lines of code, we were able to fetch the contents of a course chapter and accurately display them into the editor. In Part 3, we will discuss additional functionalities, including editing the content within the Froala editor. Additionally, we’ll try out the other transformation features of Filestack. See you again soon!

Get your Filestack API here for free.

Uploading Files to Dropbox in Angular Rich Text Editor with Froala

Froala filestack integration in Angular

Dropbox is a popular cloud storage service allowing users to securely store and share files. Integrating Dropbox with an Angular rich text editor, such as Froala, can enhance the user experience by enabling seamless file uploads directly from the editor. This integration can be achieved by leveraging a service like Filestack, which provides a user-friendly interface for handling file uploads and storage. By incorporating Filestack’s features, developers can streamline the file upload process and ensure that users can easily access and manage their Dropbox files within the rich text editor.

Froala’s latest version, V4.3, includes a new plugin for integrating with Filestack. This makes it easy to upload files to your Dropbox storage directly from the Froala editor. With just a few simple configuration steps, you can start uploading files without leaving the editor.

This integration saves development time and cost. Developers can focus on building the core functionality of their application, rather than spending time implementing complex file upload and storage solutions.

It also saves users time and effort by eliminating the need to switch between different applications or interfaces to manage files. Additionally, it ensures that uploaded files are securely stored in the user’s Dropbox account, providing an extra layer of data protection.

Overall, the Froala-Filestack-Dropbox integration offers a powerful and efficient way to incorporate file management into your Angular-based applications.

Let’s explore how this integration can be set up and leveraged to enhance your Angular application’s functionality. We’ll cover the necessary steps to configure Filestack, connect it to Dropbox, and seamlessly integrate it with the Froala rich text editor. By the end, you’ll have a robust file management solution that provides a seamless user experience within your Angular app.

Angular rich text editor

Step 1: Create a Filestack Account

You will need a Filestack account and obtain an API key for successful uploads. You can create a free Filestack account, which provides a limited amount of bandwidth, uploads, and transformations, as well as access to Filestack’s internal S3 storage. To upload files to Dropbox, you’ll need a paid plan. Start a free trial of a Filestack plan that fits your needs.

Step 2: Dropbox Configuration

Just four simple steps to ensure that files uploaded through the file picker will be stored in your Dropbox account.

  1. You need an existing Dropbox application or you can create a new one.
  2. Make sure to enable additional development users.

Enable additional users

  1. Generate an OAuth2 access token that will be added to the Dropbox storage section in the developer portal.

generate access

  1. Add the necessary policies and test the Storage Keys in the Developer Portal to ensure the connection between our API and your Cloud Storage is set.

Step 3: Create a new Angular project

Skip this step if you are installing the editor in an existing Angular project.

To create a new Angular project, you can use the Angular CLI. Open a terminal or command prompt, navigate to the desired directory, and run the following command:

ng new filestack-integration

This will create a new Angular project named “my-app” and guide you through the setup process, including options for routing and stylesheet format.

When prompted “Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? (y/N)“, answer with “N”.

Once the project is created, you can navigate to the project directory:

cd filestack-integration

 

Step 4: Install Froala Angular SDK

To integrate the Froala rich text editor into your Angular application, you’ll need to install the Froala Angular SDK. You can do this by running the following command in your project’s root directory:

npm install angular-froala-wysiwyg --save

This will install the necessary packages and dependencies.

Step 5: Include the Froala Stylesheets

To include the necessary Froala stylesheets, add the following lines to your `angular.json` file, within the `styles` array:

"node_modules/froala-editor/css/froala_editor.pkgd.min.css",

"node_modules/froala-editor/css/froala_style.min.css"

This will ensure that the Froala editor is properly styled within your Angular application.

Step 6: Create Editor Component

In this step, we will create a custom component to handle the Froala editor and Filestack integration. This component will provide a user-friendly interface for uploading files to Dropbox directly from the rich text editor. By encapsulating the integration logic within a dedicated component, you can easily reuse and maintain the editor functionality across your Angular application.

Create a new component using the Angular CLI:

ng generate component editor

This will create a new component called EditorComponent in your project.

Step 7: Import the Froala Editor Modules

Open the editor.component.ts file and import the necessary Froala modules.

import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

@Component({
  selector: 'app-editor',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './editor.component.html',
  styleUrl: './editor.component.css'
})
export class EditorComponent {

}

Step 8: Include Filestack Files

Open index.html and include the required Filestack files to open the file picker and Transformation UI.

<link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

<script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>

<script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>

<script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>

Step 9: Configure the Froala Component

Open the editor.component.ts file and add the required editor configuration within the EditorComponent class. To complete the Filestack integration, consider setting the following options and events:

  • filestackOptions.filestackAPI This is where you should add your Filestack API key.
  • filestackOptions.uploadToFilestackOnly (Optional) Set this option to true if you want to handle all file uploads by Filestack.
  • filestackOptions.pickerOptions (Optional) Use this option to customize the Filestack Picker.
  • filestack.filestackPickerOpened (Optional) This event is triggered when the Filestack File Picker is opened.
  • filestack.filestackPickerClosed (Optional) This event is triggered when the Filestack File Picker is closed.
  • filestack.uploadedToFilestack (Optional) This event is triggered when files are successfully uploaded to your storage.
  • filestack.uploadFailedToFilestack (Optional) This event is triggered when a file upload fails. You can use this event to run a custom function to handle the failed upload.
import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

@Component({
  selector: 'app-editor',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './editor.component.html',
  styleUrl: './editor.component.css'
})
export class EditorComponent {
  public editorContent = "Filestack is a simple file uploader & powerful APIs to upload, transform & deliver any file into your app.";
  public options: Object = {

    heightMin: 300,
    filestackOptions: {
      uploadToFilestackOnly: true,
      filestackAPI: "AvaZ2E0mxRdGPjgMAbus8z",
    },

    events: {
      'filestack.uploadedToFilestack': function () {
        console.log("Callback is triggered for uploaded to filestack ",)
      },

      'filestack.filestackPickerOpened': function () {
        console.log("Callback is triggered for picker opened ",)
      },

      'filestack.filestackPickerClosed': function () {
        console.log("Callback is triggered for picker closed ",)
      },

      'filestack.uploadFailedToFilestack': function () {
        console.log("Callback is triggered for filestack failed ",)
      },

    },
  };
}

Then add <div [froalaEditor]="options" [(froalaModel)]="editorContent"></div> in your editor.component.html file.

With the editor component set up, you can now use it in your Angular application. Simply add the <app-editor> element wherever you want the rich text editor to appear. The EditorComponent will handle the integration with Froala and Filestack, providing a seamless user experience for file uploads directly within the editor. The uploaded files will then be stored in Dropbox using the Filestack integration. This allows your users to easily incorporate multimedia content into their rich text content without leaving the editor interface.

Step 10: Displaying Froala on the main page

To display the Froala editor on the main page of your Angular application, open app.component.ts and import the EditorComponent.

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { EditorComponent } from './editor/editor.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, EditorComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'filestack-integration';
}

Then simply add the <app-editor> element to the app.component.html template.

<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content below * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced.  * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * Delete the template below * * * * * * * * * -->
<!-- * * * * * * * to get started with your project! * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->

<style>
  :host {
    --bright-blue: oklch(51.01% 0.274 263.83);
    --electric-violet: oklch(53.18% 0.28 296.97);
    --french-violet: oklch(47.66% 0.246 305.88);
    --vivid-pink: oklch(69.02% 0.277 332.77);
    --hot-red: oklch(61.42% 0.238 15.34);
    --orange-red: oklch(63.32% 0.24 31.68);

    --gray-900: oklch(19.37% 0.006 300.98);
    --gray-700: oklch(36.98% 0.014 302.71);
    --gray-400: oklch(70.9% 0.015 304.04);

    --red-to-pink-to-purple-vertical-gradient: linear-gradient(180deg,
        var(--orange-red) 0%,
        var(--vivid-pink) 50%,
        var(--electric-violet) 100%);

    --red-to-pink-to-purple-horizontal-gradient: linear-gradient(90deg,
        var(--orange-red) 0%,
        var(--vivid-pink) 50%,
        var(--electric-violet) 100%);

    --pill-accent: var(--bright-blue);

    font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
      "Segoe UI Symbol";
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

  h1 {
    font-size: 3.125rem;
    color: var(--gray-900);
    font-weight: 500;
    line-height: 100%;
    letter-spacing: -0.125rem;
    margin: 0;
    font-family: "Inter Tight", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
      "Segoe UI Symbol";
  }

  p {
    margin: 0;
    color: var(--gray-700);
  }

  main {
    width: 100%;
    min-height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    box-sizing: inherit;
    position: relative;
  }


  .content {
    display: flex;
    justify-content: space-around;
    width: 100%;
    max-width: 700px;
    margin-bottom: 3rem;
  }

  .content p {
    margin-top: 1.5rem;
  }


  @media screen and (max-width: 650px) {
    .content {
      flex-direction: column;
      width: max-content;
    }

  }
</style>

<main class="main">
  <div class="content">
    <div class="">

      <p>Congratulations! Your app is running. 🎉</p>
      <app-editor></app-editor>
    </div>

  </div>
</main>

<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content above * * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced.  * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * End of Placeholder  * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->


<router-outlet></router-outlet>

This will render the EditorComponent you created earlier, which encapsulates the Froala editor and Filestack integration. By using the custom EditorComponent, you can easily reuse the rich text editing functionality across your application without having to manage the integration details in multiple places. This promotes code reusability and maintainability as your application grows.

Step 11: Test your App

Run ng serve. This will start the development server and make your Angular application available at http://localhost:4200

Forala Filestack Integration in Angular

You can now test the Froala editor and Filestack integration within your Angular application. Verify that the editor is displayed correctly on the main page and that users can upload files directly within the editor interface. Ensure that the uploaded files are successfully stored in Dropbox using the Filestack integration.

forala angular rich text editor with Filestack integration Froala Angular WYSIWYG editor integration with Filestack Froala integration with Dropbox

Test various editing features provided by Froala, such as formatting, inserting images, and embedding multimedia content. Validate that the rich text content is properly rendered and that the user experience is seamless. Make any necessary adjustments to the integration or styling to optimize the overall functionality and appearance of the editor within your Angular application.

Elevate Your Angular App with Seamless Dropbox Integration

By integrating Froala’s Angular rich text editor with Filestack and Dropbox, you can elevate your Angular application’s functionality and provide users with a seamless content creation experience. This integration empowers your users to effortlessly upload and manage files directly within the editor, eliminating the need to switch between different applications.

The benefits of this integration are clear:

  • It saves development time and costs, while also enhancing the user experience.
  • Developers can focus on building core application features, rather than implementing complex file upload and storage solutions.
  • Users enjoy the convenience of accessing and managing their Dropbox files without leaving the familiar Froala editor interface.

Don’t settle for a disjointed content creation workflow in your Angular app. Embrace the power of the Froala-Filestack-Dropbox integration and take your application to new heights.

Get your Filestack API here for free.