How can I use register instead of formats with Quilljs 2.0.*? - editor

In quill 1.x, we can use formats to configure the required format:
var quill = new Quill('#editor-container', {
modules: {
toolbar: false
},
placeholder: 'Compose an epic...',
formats: ['bold', 'italic', 'link', 'strike', 'script', 'underline'],
theme: 'snow' // or 'bubble'
});
but, quill 2.0 removed formats
upgrading-to-2-0.md: formats removed - registry is now strictly more powerful and safer.
How can I use register instead of formats?

According to this issue, the formats problem of quill 2 is still open and seems like no one is following up.
According to this issue, there is no way to unregister specific registry. The only way is to override them but there is error when I tried to provide a new Registry to the option where ScrollBlot is null and cannot be initialised successfully.
To be able to disable the formatting, the only way you can do is to extends the formatting class and register it again to override the default behaviour.
To disable Bold
const Bold = Quill.import('formats/bold');
// extends format class (Bold) to override its methods
class CustomBold extends Bold {
// override: return false to avoid formatting again
static formats() { return false; }
// override: empty content to avoid bolt name replacement
optimize(context) { }
}
// remove all tag names (strong, b)
CustomBold.tagName = [];
// register the new custom bold formatting
Quill.register({ 'formats/bold': CustomBold })
A full version with all formatting
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.quilljs.com/2.0.0-dev.4/quill.snow.css" rel="stylesheet">
<style>
#editor-container {
width: 100%;
max-width: 1000px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="editor-container">
<div id="editor">
<p>
He has since been seeking advice from specialists, including Serbian doctor Zdenko Milinkovic, who said
Djokovic is suffering
from a "bruised bone due to excessive playing".
</p>
</div>
</div>
<script src="https://cdn.quilljs.com/2.0.0-dev.4/quill.js"></script>
<script>
const Bold = Quill.import('formats/bold');
const Italic = Quill.import('formats/italic');
const Link = Quill.import('formats/link');
const Script = Quill.import('formats/script');
const Strike = Quill.import('formats/strike');
const Underline = Quill.import('formats/underline');
// Bold
// extends format class (Bold) to override its methods
class CustomBold extends Bold {
// override: return false to avoid formatting again
static formats() { return false; }
// override: empty content to avoid bolt name replacement
optimize(context) { }
}
// remove all tag names (strong, b)
CustomBold.tagName = [];
// Italic
class CustomItalic extends Italic {
static formats() { return false; }
optimize(context) { }
}
CustomItalic.tagName = [];
// Link
class CustomLink extends Link {
static formats() { return false; }
optimize(context) { }
}
CustomLink.tagName = [];
// Script
class CustomScript extends Script {
static formats() { return false; }
optimize(context) { }
}
CustomScript.tagName = [];
// Strike
class CustomStrike extends Strike {
static formats() { return false; }
optimize(context) { }
}
CustomStrike.tagName = [];
// Underline
class CustomUnderline extends Underline {
static formats() { return false; }
optimize(context) { }
}
CustomUnderline.tagName = [];
// register the new custom formats to disable formatting
// comment/remove any of the formats below to enable specific formatting again
Quill.register({
'formats/bold': CustomBold, // comment this, you will get back the bold functionality
'formats/italic': CustomItalic,
'formats/link': CustomLink,
'formats/script': CustomScript,
'formats/strike': CustomStrike,
'formats/underline': CustomUnderline,
})
const quill = new Quill('#editor-container', {
modules: {
toolbar: false
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
</script>
</body>
</html>

Related

Vaadin 8: how to include a JavaScript File to returned web page and execute it

For instance:
I have a html file and a JavaScript file. If two file open directly with browser. It can be work.
If put these file to Vaadin Frame and use #JavaScript annotation running, it only shows a static html.
Only need communication between JavaScript and html page, no need with server.
here my code
Html(example.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Js Test Uses</title>
<script type="text/javascript" src="mylibrary.js"></script>
</head>
<body>
<div id="foo"></div>
<script type="text/javascript">
window.foo = new mylibrary.MyComponent(document.getElementById("foo"));
window.foo.click = function () {
alert("Value is " + this.getValue());
}
</script>
</body>
</html>
mylibrary.js
var mylibrary = mylibrary || {};
mylibrary.MyComponent = function (element) {
element.innerHTML = "<div class='caption'>Hello, kitty!</div>"
+ "<div class='textinput'>Enter a value: "
+ "<input type='text' name='value'/>"
+ "<input type='button' value='Click'/>"
+ "</div>";
element.style.border="thin solid red";
element.style.display="inline-block";
this.getValue = function() {
return element.getElementsByTagName("input")[0].value;
};
this.setValue = function (value) {
element.getElementsByTagName("input")[0].value = value;
};
this.click = function () {
alert("Error: Must implement click() method");
};
var button = element.getElementsByTagName("input")[1];
var self = this;
button.onclick = function () {
self.click();
};
};
Vaadin (MyUI.java):
#Theme("mytheme")
#JavaScript("mylibrary.js")
public class MyUI extends UI {
private static final long serialVersionUID = -6891373465168098637L;
#Override
protected void init(VaadinRequest vaadinRequest) {
CustomLayout layout = null;
try {
layout = new CustomLayout(MyUI.class.getResourceAsStream("examples.html"));
} catch (IOException e) {
e.printStackTrace();
}
setContent(layout);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
private static final long serialVersionUID = -9170703857949837824L;
}
}
this is my project package explorer image, is a initial project.
this is my project source(zip)
I am afraid it is not possible the way you want. See for example this answer.
Annotation #JavaScript has a bit different purpose. It enables you to call script from Vaadin server side code.
For using #JavaScript see this answer. Pay attention especially to the path the script is included.
So basically #JavaScript allows you to do things like
com.vaadin.ui.JavaScript.getCurrent().execute("hello()");
where hello() is a function declared in a javascript you include with #JavaScript

How to handle HTML form in JavaFX application

Can some one please help to how can I capture onclick event of HTML button inside JavaFX?
onClick of that button javascript alert should display, I can display HTML page on applet window but onclick event is not working
HTML:
<html lang="en">
<head>
<title>WebView</title>
<link rel="stylesheet" type="text/css" href="help.css">
<script>
function buttonClick() {
alert("Button Clicked");
}
</script>
</head>
<body>
<button onclick="buttonClick()">Submit</button>
</body>
</html>
Bellow is my JavaFX code:
public class WebViewSample extends Application {
private Scene scene;
#Override
public void start(Stage stage) {
// create scene
stage.setTitle("WebView");
scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
stage.setScene(scene);
// apply CSS style
//scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
// show stage
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Browser extends Region {
private HBox toolBar;
private static String[] imageFiles = new String[]{
"help.png"
};
private static String[] captions = new String[]{
"Help"
};
private static String[] urls = new String[]{
WebViewSample.class.getResource("help.html").toExternalForm()
};
final Hyperlink[] hpls = new Hyperlink[captions.length];
final Image[] images = new Image[imageFiles.length];
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
final ComboBox comboBox = new ComboBox();
public Browser() {
//apply the styles
getStyleClass().add("browser");
for (int i = 0; i < captions.length; i++) {
// create hyperlinks
Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
Image image = images[i] =
new Image(getClass().getResourceAsStream(imageFiles[i]));
hpl.setGraphic(new ImageView(image));
final String url = urls[i];
hpl.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
webEngine.executeScript("url");
}
});
}
comboBox.setPrefWidth(60);
// create the toolbar
toolBar = new HBox();
toolBar.setAlignment(Pos.CENTER);
toolBar.getStyleClass().add("browser-toolbar");
toolBar.getChildren().add(comboBox);
toolBar.getChildren().addAll(hpls);
toolBar.getChildren().add(createSpacer());
//add components
getChildren().add(toolBar);
getChildren().add(browser);
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
double tbHeight = toolBar.prefHeight(w);
layoutInArea(browser,0,0,w,h-tbHeight,0,HPos.CENTER,VPos.CENTER);
layoutInArea(toolBar,0,h-tbHeight,w,tbHeight,0,HPos.CENTER,VPos.CENTER);
}
#Override
protected double computePrefWidth(double height) {
return 750;
}
#Override
protected double computePrefHeight(double width) {
return 600;
}
}
The reason why you are not seeing anything is that you have not defined an onAlert handler for the webEngine. Try the simplest thing:
// in the constructor of `Browser`
webEngine.setOnAlert((WebEvent<String> event) -> {
System.out.println("ALERT!!!! " + event.getData());
});
This will be printing the alert in the std out. This also means that the event is actually captured.
If you want to call Java code from this event, you will have to read this (EDIT 2017/08/06: the link is gone now; this is the closest I could find). In short:
Make an object containing the code you want to call, e.g.:
public class Bridge {
public void doSomething() {
...
}
}
Place it in the page context:
JSObject jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("bridge", new Bridge());
Call it from the JS event handler:
function buttonClick() {
bridge.doSomething();
}
Use JSObject.removeMember() once you no longer need the bridge to remove it
Pay attention to security!

extendTag in Dart custom element

from this link in javascript, customs element extending button is made as:
var MegaButton = document.registerElement('mega-button', {
prototype: Object.create(HTMLButtonElement.prototype),
extends: 'button'
});
<button is="mega-button">
I tried making the same using dart, by this code:
class MegaButton extends ButtonElement {
static final tag = 'mega-button';
factory MegaButton()=>new Element.tag('button', tag);
MegaButton.created() : super.created() {
var shadow = this.createShadowRoot();
shadow.text='save';
}
}
document.registerElement(MegaButton.tag, MegaButton);
in the html file
<button is="mega-button"></button>
<mega-button>click me</mega-button>
but got this error:
Exception: Unsupported operation: Class must provide extendsTag if base native class is not HTMLElement
any help pls. thanks
document.registerElement should look like:
document.registerElement(MegaButton.tag, MegaButton, extendsTag: 'button');
=> new Element.tag('button', tag);
see also Custom Polymer element extending AElement in Dart
The below code worked perfectly with me:
class SaveBtn extends HtmlElement {
static final tag = 'save-button';
factory SaveBtn()=>new Element.tag(tag);
SaveBtn.created() : super.created() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
// Create a standard element and set it's attributes.
var btn = new ButtonElement()
..style.height= '20px'
..style.width= '50px'
..style.color= '#FF8F66'
..style.border='1px solid #BCC1C8'
..style.background='#F1F4FB'
..style.borderRadius='5px'
..style.fontFamily='openSansItalic'
..style.fontSize='12px'
..style.padding='0px 6px'
..style.marginLeft='0.1em'
..style.borderBeforeStyle='solid'
..style.borderWidth='1px'
..style.borderColor='transparent'
..style.marginBottom='2px'
..style.borderBottom='1px solid #D1DBE9';
btn.text= this.getAttribute('data-name');
btn.onMouseDown.listen((e){
btn..style.color="#333"
..style.background='#FF8F66';
});
btn.onMouseUp.listen((e){
btn..style.color="#FF8F66"
..style.background='#F1F4FB'
..style.outline='none'; // remove the focus outline/glur
});
btn.onMouseEnter.listen((e)=> btn..style.boxShadow='0px 0px 5px #888888');
btn.onMouseLeave.listen((e)=> btn..style.boxShadow='0px 0px 0px');
if(btn.disabled==true){
btn..style.color="gray";
}
shadow.nodes.add(btn);
Element launchElement(){
return (shadow);
}
}
}
the custom element registration:
document.registerElement(SaveBtn.tag, SaveBtn);
and in the html file, I used:
<save-button data-name='save orders'></save-button>

Drag and drop files in mvc

I want to upload file using drag and drop. I have written code as below but every time I attempt to upload a file, it is showing upload failed. Can anyone tell me where I am wrong? I want to drag items from outer source and have it uploaded into my folder but I am not able to do it.
For controller :-
public ActionResult File()
{
return View();
}
/// <summary>
/// The max file size in bytes
/// </summary>
protected int maxRequestLength
{
get
{
HttpRuntimeSection section =
ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section != null)
return section.MaxRequestLength * 1024; // Default Value
else
return 4096 * 1024; // Default Value
}
}
/// <summary>
/// Checks if a file is sent to the server
/// and saves it to the Uploads folder.
/// </summary>
[HttpPost]
private void handleFileUpload()
{
if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
{
string path = Server.MapPath(string.Format("~/Uploads/{0}", Request.Headers["X-File-Name"]));
Stream inputStream = Request.InputStream;
FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
inputStream.CopyTo(fileStream);
fileStream.Close();
}
}
and for view it is :-
<!DOCTYPE html>
<html>
<head runat="server">
<title>Drag n' Drop File Upload</title>
<link href="/Style.css" rel="Stylesheet" />
<style>
body
{
font: 12px Arial;
}
#dropZone
{
border-radius: 5px;
border: 2px solid #ccc;
background-color: #eee;
width: 250px;
padding: 50px 0;
text-align: center;
font-size: 18px;
color: #555;
margin: 50px auto;
}
#dropZone.hover
{
border-color: #aaa;
background-color: #ddd;
}
#dropZone.error
{
border-color: #f00;
background-color: #faa;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
var dropZone;
// Initializes the dropZone
$(document).ready(function () {
dropZone = $('#dropZone');
dropZone.removeClass('error');
// Check if window.FileReader exists to make
// sure the browser supports file uploads
if (typeof(window.FileReader) == 'undefined') {
dropZone.text('Browser Not Supported!');
dropZone.addClass('error');
return;
}
// Add a nice drag effect
dropZone[0].ondragover = function () {
dropZone.addClass('hover');
return false;
};
// Remove the drag effect when stopping our drag
dropZone[0].ondragend = function () {
dropZone.removeClass('hover');
return false;
};
// The drop event handles the file sending
dropZone[0].ondrop = function(event) {
// Stop the browser from opening the file in the window
event.preventDefault();
dropZone.removeClass('hover');
// Get the file and the file reader
var file = event.dataTransfer.files[0];
#* if(file.size > #maxRequestLength {
dropZone.text('File Too Large!');
dropZone.addClass('error');
return false;*#
// // Validate file size
// if(file.size > <%=maxRequestLength%>) {
// dropZone.text('File Too Large!');
// dropZone.addClass('error');
// return false;
//}
// Send the file
var xhr = new XMLHttpRequest();
// xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = stateChange;
xhr.open('POST', 'Home/handleFileUpload', true);
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
};
});
// Show the upload progress
function uploadProgress(event) {
var percent = parseInt(event.loaded / event.total * 100);
$('#dropZone').text('Uploading: ' + percent + '%');
}
// Show upload complete or upload failed depending on result
function stateChange(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200) {
$('#dropZone').text('Upload Complete!');
}
else {
dropZone.text('Upload Failed!');
dropZone.addClass('error');
}
}
}
//window.onload = fun;
//function fun() {
// $.post("Home/handleFileUpload", {}, function (response) {
// alert("hi");
// })
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dropZone">
Drop File Here to Upload.
</div>
</form>
</body>
</html>
Your HandleFileUpload action is private! In ASP.NET MVC controller actions need to be public. Also I would recommend you wrapping IDisposable resources in using statements to avoid leaking handles:
[HttpPost]
public ActionResult HandleFileUpload()
{
if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
{
string path = Server.MapPath(string.Format("~/Uploads/{0}", Request.Headers["X-File-Name"]));
using (var fileStream = new FileStream(path, FileMode.OpenOrCreate))
{
Request.InputStream.CopyTo(fileStream);
}
return Json(new { success = true });
}
return Json(new { success = false });
}
First I have tried the solution suggested by Darin Dimitrov and it did not work, but then I debug it, realized that it has server error 500, then I inspect the code realize that I don't have upload folder...so causing the issue.
so just create the folder you will be fine

Calling function defined in library from dart webcomponent

The web application has following code in app.dart
library app;
import 'dart:html';
var _loginClass;
void main() {
_loginClass = 'hide_login'; //set style to hide login web component by setting display:none
}
void showLogin(e) {
_loginClass = 'show_login';
print("span clicked");
}
void hideLogin(e) {
_loginClass = 'hide_login';
}
calling hideLogin(e) function from App.dart hides the web component. but calling it from web component does not work.
css is defined as follows:
.hide_login {
display: none;
}
.show_login {
display = block;
}
It's weird that you have "display: none;" and "display = block;". The second is not valid syntax.
If that's not the right answer, try adding:
import 'package:web_components/web_components.dart';
And then call dispatch(); after setting _loginClass.
It would probably be more dartish to use
<template instantiate="bool expression">
This makes showing and hiding a custom element like a login component incredibly easy
example:
login.html
<html>
<body>
<element name="x-login" constructor="LoginComponent" extends="div">
<template instantiate="if showLogin">
...
<button on-click="validateLogin()">Login</button>
</template>
</element>
</body>
</html>
LoginComponent.dart
import "package:web_ui/web_ui.dart";
class LoginComponent extends WebComponent {
bool showLogin = true;
bool validateLogin() {
...
showLogin = false;
}
}
Check out http://www.dartlang.org/articles/dart-web-components/ for further details

Resources