Personalized customizable elements in Draft.js (extension)

For instance, I am interested in enabling users to incorporate a dynamic slideshow of images into their page using Draft.js. This would allow them to select a predefined slideshow from my app and have it automatically update on their page if the images are changed externally. It would be great to also have a visual representation of the slideshow in the editor. Is this functionality achievable in Draft.js or am I expecting too much?

Answer №1

Whenever I pose a question, the solution always seems to reveal itself shortly after. In Draft.js, there exists a feature called "decorators", which is thoroughly explained in this documentation:

The concept behind decorators involves creating a set of functions or components. The 'strategy' function defines the strategy, while the 'component' represents the actual component to be used.

const compositeDecorator = new CompositeDecorator([
  {
    strategy: handleStrategy,
    component: HandleSpan,
  },
  {
    strategy: hashtagStrategy,
    component: HashtagSpan, 
  },
]);

In defining strategies, regex can prove to be quite handy. With regex, users have the flexibility to create custom syntaxes or utilize those from template engines for widget embedding purposes. The sample strategies provided in the documentation serve as a helpful starting point:

// Note: these regex examples are not ideal and should not be directly copied!
const HANDLE_REGEX = /\@[\w]+/g;
const HASHTAG_REGEX = /\#[\w\u0590-\u05ff]+/g;

function handleStrategy(contentBlock, callback, contentState) {
  findWithRegex(HANDLE_REGEX, contentBlock, callback);
}

function hashtagStrategy(contentBlock, callback, contentState) {
  findWithRegex(HASHTAG_REGEX, contentBlock, callback);
}

function findWithRegex(regex, contentBlock, callback) {
  const text = contentBlock.getText();
  let matchArr, start;
  while ((matchArr = regex.exec(text)) !== null) {
    start = matchArr.index;
    callback(start, start + matchArr[0].length);
  }
}

Lastly, we have the components themselves:

const HandleSpan = (props) => {
  return <span {...props} style={styles.handle}>{props.children}</span>;
};

const HashtagSpan = (props) => {
  return <span {...props} style={styles.hashtag}>{props.children}</span>;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Navigating JSON/API data within a Vue.js component template: step-by-step guide

I've successfully implemented a code snippet that renders a list of songs here: https://jsfiddle.net/jeremypbeasley/guraav4r/8/ var apiURL = "https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit= ...

How to launch a new window for a popup

How can I make IE8 open new windows as pop-ups without changing browser settings? I want to use JavaScript's window.open() function. Firefox opens new windows correctly, but IE8 opens them in tabs instead of pop-up windows. Any suggestions on how to a ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Is there a framework available to animate Pseudo CSS elements?

Recently, I was working on developing a bar chart that utilized pseudo CSS elements (::before, ::after). While I successfully created bars that look visually appealing, I encountered a challenge when attempting to animate the height changes. Whenever I us ...

Here are steps to prevent swiping fancybox slides using mouse movement

Currently utilizing fancybox 3, I am looking to disable the swipe function for fancybox slides triggered by mouse movement. My preference is to only have the control buttons (next/prev) available. Is there a way to achieve this? Thank you. ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

The POST request to the localhost API endpoint resulted in a 404 Not Found error

Whenever I try to send a POST request to "/api/auth/signup" in my JavaScript application, I keep getting a 404 Not Found error. My goal is to create a MERN application for a Modern Real Estate Marketplace. This is the code snippet causing the is ...

Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working ju ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Every attempt to connect with the webservice via an ajax call has ended in failure

I am encountering an issue with a webservice call that I am making using jQuery's AJAX method. Despite receiving JSON data from the webservice when accessed directly through the browser, my site always triggers the error function rather than the succe ...

Utilizing AngularJS Directive to trigger a designated function upon change in an input file

My current project involves creating a scavenger hunt editor with various types of questions stored in an array. Each question can be of a different type, all displayed using ng-repeat. To achieve this, I utilize a JavaScript object representing a Questio ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

send JSON data to a Spring MVC endpoint

Here is the controller signature I have tried using @RequestBody: @RequestMapping(value = "/Lame", method = RequestMethod.POST) public @ResponseBody boolean getLame(@RequestParam String strToMatchA, @RequestParam String strToMatchB) {} This is the json I ...

Ways to distinguish if Dynamics XRM javascript is being triggered from the unified interface (UCI) or the traditional web-client interface

Is there an official way to determine if code is being called from the UCI or the legacy web-client? I see the function Xrm.Internal.isUci(), but since it's labeled as Internal, it may not be recommended for use. However, I still need a method to diff ...

The rating system does not accurately incorporate the values provided by the API

Incorporated the star rating package into my ReactJS code to showcase the star value retrieved from a mock API. import { Rating } from "react-simple-star-rating"; However, when attempting to make it read-only, it does become static but fails to ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...

Using jQuery to populate an array with selected table items

Issue Description: I am working on an HTML page with two add buttons and two tables. Currently, when the add button is clicked, rows are appended to their respective tables. However, in the backend, I need to gather all row elements when a specific "button ...