draft-js-export-html not includes video when export - reactjs

Currently, I'm using draft js editor, add plugin draft-js-video-plugin to insert video into editor and use draft-js-export-html to export html but the htmk result not includes video tag or anythings else.
Console log stateToHTML(this.state.editorState.getCurrentContent())
<p><br></p>
<figure> </figure>
<p><br></p>
I found same issue with export image here and they've resolved but not for video.
I've read their source code on github and seem now they only support text, link and image.
So how can I get result HTML includes video from draft js? Please help me, thank you guys.

Credit to rafaelespinoza https://github.com/sstur/draft-js-utils/issues/59#issuecomment-314527096
I'm able to fix it using `entityStyleFn like below:
entityStyleFn: (entity) => {
const entityType = entity.get('type').toLowerCase();
if (entityType === 'draft-js-video-plugin-video') {
const data = entity.getData();
return {
element: 'video',
attributes: {
src: data.src,
},
};
}
return null;
},

Related

Export image node to markdown with Lexical

I create a new node: 'ImageNode', similar to this: https://lexical.dev/docs/concepts/nodes#extending-decoratornode
This is working, but I need to export markdown content, for this, I'm using $convertToMarkdownString.
My problem is images inserted in the editor, aren't being exported as markdown. My console log show just basic transforms.
How can I export the image node to markdown?
I need to create a new transform to markdown?
Thanks!
(Copy-pasting from discussions) ImagePlugin (just like the toolbar) is part of the playground only, so the transformer is not exposed to NPM. We expect to make ImagePlugin as part an individual #lexical/image package in the future but only once we it's generic enough to cater most use cases and guarantee no major breaking cases in the immediate future.
For now, you may want to copy-paste this bit from the playground:
export const IMAGE: TextMatchTransformer = {
export: (node, exportChildren, exportFormat) => {
if (!$isImageNode(node)) {
return null;
}
return `![${node.getAltText()}](${node.getSrc()})`;
},
importRegExp: /!(?:\[([^[]*)\])(?:\(([^(]+)\))/,
regExp: /!(?:\[([^[]*)\])(?:\(([^(]+)\))$/,
replace: (textNode, match) => {
const [, altText, src] = match;
const imageNode = $createImageNode(src, altText, 800);
textNode.replace(imageNode);
},
trigger: ')',
type: 'text-match',
};

Unable to display pokemon image from pokeapi.co

I am having an issue where I can't seem to be able to display the pokemon images on my react front end, this is the api: https://pokeapi.co/
import React, { Component } from 'react';
class Card extends Component {
state = {
name: "",
imageUrl: "",
pokemonIndex: "",
}
componentDidMount() {
const {name, url} = this.props;
const pokemonIndex = url.split('/')[url.split('/').length - 2];
const imageUrl = `http://pokeapi.co/media/sprites/pokemon/${pokemonIndex}.png`
this.setState({name, imageUrl, pokemonIndex})
}
render() {
return (
<div className="card" >
<img src= {this.state.imageUrl}/>
<h3> {this.state.name} </h3>
</div>
);
}
}
export default Card;
I have also attached a screenshot of the front end.
Looking at the documentation and JSON file from API, I think I found your problem. You are using the wrong img link. The correct format is: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png
For exemple:
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png" />
#erick-silva answer is not complete and prone to error.
The correct way to fetch an image for a specific pokemon is:
Fetch from PokeAPI the info for that pokemon, say bulbasaur. -> GET https://pokeapi.co/api/v2/pokemon/bulbasaur
Parse the returned JSON for the property .sprites, select the version we'd like to use and the variety for the sprite, say Pokemon Crystal front: .sprites.versions["generation-ii"].crystal.front_default
Use the provided link and load the image: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-ii/crystal/1.png
Using this method will ensure that you will always fetch the correct image in case the ids change or the name of the image isn't the id of the pokemon.
For pokeapi the correct URI format is as follows.
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/imageName.png
Currently pokemon images are not loaded as there are deleted from it's github repo.
You can find the real location of the images inside sprites folder in PokeAPI GitHub.
To get the image, there is a workaround,
https://unpkg.com/pokeapi-sprites#2.0.2/sprites/pokemon/other/dream-world/1.svg
here 1.svg should be replaced by the pokemon's id
You can find more info here

Playing a sound on keypress using React

I am not experienced in React so please excuse if this question will seem silly.
I have been trying to play a sound when a key is pressed on the keyboard.
I wanted to use the following solution:
https://www.npmjs.com/package/react-sampler/v/1.0.2
The problem is that when I try to play my sample i get an error:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
import React from 'react';
import './App.css';
import Sampler from 'react-sampler';
var samples = [{
file: "samples/sample1.wav",
key: 'h', // First sample
startAt: 0.2 // delay in sec
},{
file: 'samples/sample2.wav',
key: 'o', // Second sample
startAt: 0.05
}];
var ReactSamplerExample = () => ({
handleSampleLaunch: function(sample){
var elm = document.querySelector('[data-key='+sample.key+']');
elm.classList.add('active');
setTimeout(() => { elm.classList.remove('active')}, 150);
},
render: function() {
return (
<div>
<ul className="keys">
<li data-key="h">
<span className="key"></span><span className="sample">Sample 1</span></li>
<li data-key="o">
<span className="key"></span><span className="sample">Sample 2</span></li>
</ul>
<Sampler samples={samples} onLaunchSample={this.handleSampleLaunch} disabled={false} />
</div>
);
}
});
I checked the path to the files and they seem to be ok (all files are located in the same directory as the samples folder).
I'm not sure how to solve this. If there is a better tool or a simple audio API anyone can recommend or should switch to I would gladly take some advice.
Thanks in advance!
You are using react sampler for that. I like to use native html component with some customization for this situation.
Here my sample for you, hope i can help you with this sample:
Codesandbox Audio Play

How to call and use embedded assets from Contentful Rich Text fields using Gatsby?

I am using Gatsby as the starter for my react app. To handle content I am using Contentful.
In my Contentful Content Model, I've created the following content types:
Short Text
Short Text
Media
Rich Text
Rich Text
Using Gatsby's gatsby-source-contenful and #contentful/gatsby-transformer-contentful-richtext plugins, I've successfully rendered my all of these content types, except in my Rich Text types I'm not able to render the Embedded Assets within it.
I've tried installing #contentful/rich-text-types via npm and using the constants MARK and INLINES based on the example in Gatsby's documentation found here
const { MARKS, INLINES } = require('#contentful/rich-text-types')
{
resolve: `#contentful/gatsby-transformer-contentful-richtext`,
options: {
renderOptions: {
/*
* Defines custom html string for each node type like heading, embedded entries etc..
*/
renderNode: {
// Example
[INLINES.ASSET_HYPERLINK]: node => {
return `<img class='custom-asset' src="${
node.data.target.fields.file['en-US'].url
}"/>`
},
[INLINES.EMBEDDED_ENTRY]: node => {
return `<div class='custom-entry' />${
node.data.target.fields.name['en-US']
}</div>`
},
},
/*
* Defines custom html string for each mark type like bold, italic etc..
*/
renderMark: {
// Example
[MARKS.BOLD]: text => `<strong>${text}<strong>`,
},
},
},
},
Ideally, I'd like for Gatbsy to automatically render image assets within the Rich Text types as <img src="[ASSET URL]" alt="[ASSET DESCRIPTION]">
Try this:
const { BLOCKS } = require('#contentful/rich-text-types')
...
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: node => {
// console.log(node)
let { description, title, file } = node.data.target.fields
// console.log(file["en-US"].url)
return <img src={file["en-US"].url} />
},
},
This seems to work for me, although the image seems to be full-size, and load rather slowly. Needs additional work, but this does seem to work (at least in development)
EDIT:
It seems like the fields property on my node.data.target stopped appearing when I send my graphql query... and this stopped working... super bizarre
EDIT 2:
if you delete the .cache folder (project-root/.cache), the above issue gets fixed. https://github.com/gatsbyjs/gatsby/issues/10592

Unable to display images after uploading them in react component

I want to upload multiples images then display them in browser. I wrote this code mentioned by this link.
I got the name of images displayed in place of images:
Image1.png
Image2.png
How can I fix that and if someone knows another npm module which upload and display images as a gallery I will be grateful if mentioned it to me.
Adding the property withPreview to the <ImageUploader /> gives you a preview of all "uploaded" images.
const UploadImage = props => {
const { onDrop } = props;
return (
<ImageUploader
withIcon
buttonText="Upload Image"
onChange={onDrop}
imgExtension={[".jpg", ".gif", ".png", ".gif"]}
maxFileSize={5242880}
withPreview
/>
);
};
You can see this change implemented here.
This library looks like it can achieve what you want right out the box. See the documentation for the library for more details.

Resources