Hi, I am using the jodit Editor in React and able to do many editing in the texts but not able to paste any content in this edtor - copy-paste

const JoditEditor = dynamic(() => import('jodit-react'), { ssr: false }); const editor = useRef(null); <JoditEditor ref={editor} value={description} onBlur= {newContent => {}} onChange= {newContent => {}} />
I am using this code as basic functionality,
I am trying to get paste functionality/configuration in Jodit editor using in Nextjs.

Related

Cropping JS libraries do not work in Election

I am trying to add a simple image cropping functionality in my Electron app. I want something like this.
I have tried react-image-crop and react-cropper, but both did not work.
With the latter library, I simply did:
import React, { useState } from 'react';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
const ImageCrop = () => {
const [upImg, setUpImg] = useState();
const onSelectFile = e => {
if (e.target.files && e.target.files.length > 0) {
const reader = new FileReader();
reader.addEventListener('load', () => setUpImg(reader.result));
reader.readAsDataURL(e.target.files[0]);
}
};
return (
<>
<div>
<input type="file" accept="image/*" onChange={onSelectFile} />
</div>
<Cropper src={upImg} />
</>
);
};
export default ImageCrop;
The result looks like the following and I was not able to select the area.
With the former library, it only displays an orange frame around the image and does not allow cropping it.
I imagine some JS functionality is somehow not working in Electron, but I do not know what exactly is going on here. Any help would be appreciated to explain it and make it work.
#kyleawayan is right.
You just have to manually include the CSS file into your HTML.
I was using an index.html file with Electron, so I had to add:
<link rel="stylesheet" href="./node_modules/cropperjs/dist/cropper.min.css" />
to the <head> of my HTML.

how to use AppState in a functional component and hooks? Necessary or am I using useEffect incorrectly?

I want to be able to run a function when a user goes into the app. I thought useEffect would already do something like this, say if I choose to change my phone's Clipboard (copy different texts from another app). But its not rerendering the component.
const [clipped, setClipboard] = useState();
const [appView, setAppView] = useState(AppState.currentState);
const getFromClipboard = useCallback(() => {
Clipboard.getString().then(content => {
console.log('content:', content)
setClipboard(content);
});
}, [clipped]);
useEffect(() => {
getFromClipboard();
}, [getFromClipboard, clipped, appView]);
I would assume that every time I copy a new text from a different app, into my clipboard, and then I go back to this app, because the state changed in clipped, it will rerender the useEffect? Unfortunately, its not calling the console log after first initial load of the component.
I stumbled across AppState, and thought I might be able to give this a shot, but not sure how to set this up with useEffect?
You can set an event listener for app state change it will trigger when the app is closed, moved to background or foreground, You can check the documentation for more details link:
useEffect(() => {
AppState.addEventListener('change', handleChange);
return () => {
AppState.removeEventListener('change', handleChange);
}
}, []);
const handleChange = (newState) => {
if (newState === "active") {
getFromClipboard();
}
}

Electron ES6 module import

Electron 3.0.0-beta.1
Node 10.2.0
Chromium 66.0.3359.181
The problem I'm having is importing a module. I created the following protocol:
protocol.registerFileProtocol('client', (request, callback) => {
var url = request.url.substr(8);
callback({path: path.join(__dirname, url)});
});
The output of the protocol is the correct path
"/Users/adviner/Projects/Client/src/ClientsApp/app.js"
I have the following module app.js with the following code:
export function square() {
return 'hello';
}
in my index.html I import the module like so:
<script type="module" >
import square from 'client://app.js';
console.log(square());
</script>
But I keep getting the error:
app.js/:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
I'm done searches but can't seem to find a solution. Can anyone suggest a way I can make this work?
Thanks
This is a tricky question and i will refer to Electron#12011 and this GitHub Gist for a deeper explaination but the core learning is that the corresponding HTML spec, disallows import via file:// (For XSS reasons) and a protocol must have the mime types defined.
The file protocol you use client:// has to set the correct mime-types when serving the files. Currently i would guess they are not set when you define the protocol via protocol.registerBufferProtocol thus you recive a The server responded with a non-JavaScript MIME type of "", the gist above has a code sample on how to do it.
Edit: I just want to emphasize the other answers here do only cover the absolute minimum basics implementation with no consideration of exceptions, security, or future changes. I highly recommend taking the time and read trough the gist I linked.
To confirm: this is there for security reasons.
However, in the event that you just need to get it deployed:
Change "target": "es2015" to "target": "es5" in your tsconfig.json file
Quick Solution:
const { protocol } = require( 'electron' )
const nfs = require( 'fs' )
const npjoin = require( 'path' ).join
const es6Path = npjoin( __dirname, 'www' )
// <= v4.x
// protocol.registerStandardSchemes( [ 'es6' ] )
// >= v5.x
protocol.registerSchemesAsPrivileged([
{ scheme: 'es6', privileges: { standard: true } }
])
app.on( 'ready', () => {
protocol.registerBufferProtocol( 'es6', ( req, cb ) => {
nfs.readFile(
npjoin( es6Path, req.url.replace( 'es6://', '' ) ),
(e, b) => { cb( { mimeType: 'text/javascript', data: b } ) }
)
})
})
<script type="module" src="es6://main.js"></script>
Based on flcoder solution for older Electron version.
Electron 5.0
const { protocol } = require('electron')
const nfs = require('fs')
const npjoin = require('path').join
const es6Path = npjoin(__dirname, 'www')
protocol.registerSchemesAsPrivileged([{ scheme: 'es6', privileges: { standard: true, secure: true } }])
app.on('ready', async () => {
protocol.registerBufferProtocol('es6', (req, cb) => {
nfs.readFile(
npjoin(es6Path, req.url.replace('es6://', '')),
(e, b) => { cb({ mimeType: 'text/javascript', data: b }) }
)
})
await createWindow()
})
Attention! The path always seems to be transformed to lowercase
<script type="module" src="es6://path/main.js"></script>
Sorry Viziionary, not enough reputation to answer the comment.
I've now done it like this:
https://gist.github.com/jogibear9988/3349784b875c7d487bf4f43e3e071612
my problem was, I also wanted to support modules which are imported via none relative path's, so I don't need to transpile my code.

(React Native) Load local HTML file into WebView

I try to load the local .html file into WebView in React Native:
// load local .html file
const PolicyHTML = require('./Policy.html');
// PolicyHTML is just a number of `1`
console.log('PolicyHTML:', PolicyHTML);
// will cause an error: JSON value '1' of type NSNumber cannot be converted to NSString
<WebView html={PolicyHTML} />
The .html file should be read as a string, not as a resource representative.
How can I load the .html file into WebView in React Native?
By the way, what is the type of those resource representatives from require()? Is it number?
try it:
const PolicyHTML = require('./Policy.html');
<WebView
source={PolicyHTML}
style={{flex: 1}}
/>
I come across this post searching for loading static html.
If your html code is retrieved using, for example, an API, you can render WebView in this way:
<WebView
originWhitelist={['*']}
source={{ html: html, baseUrl: '' }}
/>
Notice that originWhitelistis required as explained in the documentation:
Note that static html will require setting of originWhitelist for
example to ["*"].
<View style={{flex: 1}}>
<WebView
style={{flex: 1}}
source={require("./resources/index.html")}
/>
</View>
To make WebView, the parent has to has a dimension or flex:1. We could set the WebView to flex: 1 too so that it fills up the parent.
If you need to serve local assets as well, then:
put all assets together with index.html into android/app/src/main/assets/www (You can copy them there with gradle task)
Then:
var uri = Platform.OS == "android" ?
"file:///android_asset/www/index.html" :
"./web/www/index.html"
return <WebView source={{ uri }} />
** For iOS didn't tested, please add instruction, how assets should be stored
With Expo tools and generally using Expo:
import { WebView } from "react-native-webview";
import { readAsStringAsync } from "expo-file-system";
import { useAssets } from "expo-asset";
export const MusicSheet = () => {
const [index, indexLoadingError] = useAssets(
require("../assets/musicsheetview/index.html")
);
const [html, setHtml] = useState("");
if (index) {
readAsStringAsync(index[0].localUri).then((data) => {
setHtml(data);
});
}
return (
<View style={styles.container}>
<WebView
onLoad={() => {}}
source={{ html }}
onMessage={(event) => {}}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
height: 100,
display: "flex",
},
});
Try this :
Add your .html file in your project.
Write such lines of code in the file where you want to use WebView Component
const OurStoryHTML = require ('./OurStory.html')
<WebView
source={OurStoryHTML}
style={{flex: 1, marginTop : 44}}
/>
It may help you.
If you're working with assets, project directories is different on the device's directory once the project is build and you can't simply reference them via string url.
Expo
If using expo, you have to require every asset then use useAssets on the require to cache them to the local storage of the device.
useAssets will return an object that contains a localUri
(this is the uri of the image that has been cached)
you can then use the localUri and put it as the src of the image
import { useAssets } from 'expo-asset';
/* . . . */
const IndexHTML = require('./assets/index.html');
const myImage = require('./assets/splash.png');
// url link after image is cached to the device
const [imgSrc, setImgSrc] = useState('');
const [image, imerr] = useAssets(myImage);
const [html, error] = useAssets(IndexHTML);
const webViewProps = {
javaScriptEnabled: true,
androidLayerType: 'hardware',
originWhitelist: ['*'],
allowFileAccess: true,
domStorageEnabled: true,
mixedContentMode: 'always',
allowUniversalAccessFromFileURLs: true,
onLoad: () => {
console.log(image[0].localUri);
setImgSrc(image[0].localUri);
},
source: {
html: '<img src="' + imgSrc + '"/>',
},
};
return <WebView {...webViewProps} />
const webViewProps = {
...
source: IndexHTML,
};
Note: for the expo apporach, files referenced in IndexHTML will not be found
The trick is to turn your html into a string literal to utilize template strings.
Then you have to manually require each of those assets to concatenate localUrl
require() has limited types supported and you need to add a metro.config.js in your root folder.
it will give errors if you require() a .js file since it reads it as a module rather, the workaround approach would be to bundle your assets
const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
config.resolver.assetExts.push(
// Adds support for asset file types
'css', 'ppt', 'obj'
);
module.exports = config;
Moreover, expo can hot reload changes done with the cached assets.
React Native
If you have the android folder in your directory, navigate to
android > app > build.gradle
then add
android {
/* link assets to the local storage of device */
sourceSets {
main { assets.srcDirs = ['src/main/assets', '../../source/assets/'] }
// [do not touch, 'relative to your asset'] }
}
. . .
finally, the relative folder you linked in gradle can be accessed through
file:///android_asset/
for ex. file:///android_asset/index.html -> /asset/index.html
return <WebView source={{uri: `file:///android_asset/index.html`}} />
For IOS, here's how
On the other hand, you have to rebuild vanilla react to see the changes in the assets.. which takes about 20 minutes or so
Alternative
A quick solution would be to integrate a static server, but this is a recent fork of the react-native-static-server that only works in vanilla react native.

jquery mobile footer does not render properly with dynamic content

Folks
I am using backbonejs (0.9) with latest jquery mobile (1.3). I am using WebSql for storing local data. When the home page loads, I do a query from the local database and use jquery Deferred to render the content after the query is successful. Unfortunately, the jquery mobile footer does not get "enhanced".
My Haml template for the view is simple and looks as follows:
%div{'data-role' => 'header'}
%div{'data-role' => 'navbar', 'data-iconpos' => 'top'}
%ul
%li
%a.ui-btn-active.ui-state-persist{'href' =>''}ATAB
%li
%a{'href' =>'#btab'}BTAB
%div{'data-role' => 'content'}
%div{'data-role' => 'footer', 'data-position' => 'fixed'}
%a{'data-icon' => 'plus', 'href' => '#a_link'}A link
My Backbonejs view looks as follows (I use coffeescript). Router already has templates cached in router.templates and txnsLoadedPromise gets "resolved" once the db records from websql are loaded:
window.HomeView = class HomeView extends Backbone.View
initialize: (options) ->
#template = Handlebars.compile(router.templates['/home/home'])
render: () ->
txnsLoadedPromise.then(
#renderDynamic
)
return this
renderDynamic: () =>
if (transactions.length > 0)
#generate content dynamically here and put in result
result = {}
$(#el).html(#template(result))
$('[data-role="header"]').trigger('create')
$('[data-role="footer"]').trigger('create')
This is how my view looks:
I have tried to use "refresh" instead of create in the trigger call for footer but it does not work. Strangely enough, the header refresh works properly. Also, if I remove the dynamic nature of the page (meaning render the view directly instead of when the promise is resolved, then it works fine (which is expected.)
Just for completeness, Following is my router code (portions of it that are relevant)
window.MyRouter = class MyRouter extends Backbone.Router
routes:
"": "home"
initialize: (options) ->
#code for preloading view templates
templates: {}
home: () ->
PageUtil.changePage new HomeView({templateKey: '/home/home'})
And the changePage method in PageUtil class:
window.PageUtil = class PageUtil
#changePage: (view, overrideOptions={}, role='page') ->
defaultOptions={transition: 'slide', reverse: false}
options = $.extend(defaultOptions, overrideOptions)
view.render();
$('body').append($(view.el));
if window.curentView
console.log 'removing view: ', currentView
window.currentView.remove()
window.currentView = view
$.mobile.changePage(view.$el, options);
Any ideas?
There's a problem in your code.
First trigger('create') will work only on content part, use trigger('pagecreate') to enhance header + content + footer.
Read more about it in my other ARTICLE. Or find it HERE.
There you will find a working example of dynamically added footer content.
If you are adding dynamic navbar element then even trigger('pagecreate') wont help you.
But there's a working solution:
$('#index').live('pagebeforeshow',function(e,data){
navbarHandler.addNewNavBarElement('navbar-test','el4','Page Four');
});
var navbarHandler = {
addNewNavBarElement:function(navBarID, newElementID, newElementText) {
var navbar = $("#" + navBarID);
var li = $("<li></li>");
var a = $("<a></a>");
a.attr("id", newElementID).text(newElementText);
li.append(a);
navbar = navbarHandler.clearNavBarStyle(navbar);
navbar.navbar("destroy");
li.appendTo($("#" + navBarID + " ul"));
navbar.navbar();
},
clearNavBarStyle:function(navbar){
navbar.find("*").andSelf().each(function(){
$(this).removeClass(function(i, cn){
var matches = cn.match (/ui-[\w\-]+/g) || [];
return (matches.join (' '));
});
if ($(this).attr("class") == "") {
$(this).removeAttr("class");
}
});
return navbar;
}
}

Resources