Stripo plugin HTML editor - html-editor

I am using stripo HTML editor and i have completed my installation process, but now i just want to save the whole form in form of html in my react code not in any external file. I could not find any solutuon online or anything in their documentation regarding this. I also want to add preview and export option in the header as well as the whole header in their demo.
Here's my code till now.
This is my result of my existing code
What i want is given below
This is the result i want. I want to access all the possible header options given. Also a button by which i can get the html of the above image that i have posted
Below is my code
import "./App.css";
var notifications = {
autoCloseTimeout: 4000,
container: ".notification-zone",
error: function (text, id, params) {
this.showNotification(
this.getErrorNotification.bind(this),
text,
id,
params
);
},
warn: function (text, id, params) {
this.showNotification(
this.getWarningNotification.bind(this),
text,
id,
params
);
},
info: function (text, id, params) {
this.showNotification(
this.getInfoNotification.bind(this),
text,
id,
params
);
},
success: function (text, id, params) {
this.showNotification(
this.getSuccessNotification.bind(this),
text,
id,
params
);
},
loader: function (text, id, params) {
this.showNotification(
this.getLoaderNotification.bind(this),
text,
id,
params
);
},
hide: function (id) {
// var toast = `$('#' + id, this.container);
// toast.effect('fade', 600, function () {
// toast.remove()
// })`;
},
showNotification: function (notificationGetter, text, id, params) {
params = Object.assign({ autoClose: true, closeable: true }, params || {});
if (!id || !`$('#' + id).length`) {
var toast = notificationGetter(text, id, !params.closeable);
this.container.append(toast);
toast.effect("slide", { direction: "down" }, 300);
if (params.autoClose) {
setTimeout(function () {
toast.effect("fade", 600, function () {
toast.remove();
});
}, this.autoCloseTimeout);
}
}
},
getErrorNotification: function (text, id, nonclosable) {
return this.getNotificationTemplate("alert-danger", text, id, nonclosable);
},
getWarningNotification: function (text, id, nonclosable) {
return this.getNotificationTemplate("alert-warning", text, id, nonclosable);
},
getInfoNotification: function (text, id, nonclosable) {
return this.getNotificationTemplate("alert-info", text, id, nonclosable);
},
getSuccessNotification: function (text, id, nonclosable) {
return this.getNotificationTemplate("alert-success", text, id, nonclosable);
},
getLoaderNotification: function (text, id) {
var notification = `$('\
<div class="alert alert-info" role="alert">\
<div style="width:auto; margin-right: 15px; float: left !important;">\
<div style="width:20px;height:20px;border-radius:50%;box-shadow:1px 1px 0px #31708f;\
animation:cssload-spin 690ms infinite linear"></div>\
</div>' + text + '\
</div>')`;
id && notification.attr("id", id);
return notification;
},
getNotificationTemplate: function (classes, text, id, nonclosable) {
var notification = `$('\
<div class="alert alert-dismissible ' + classes + (nonclosable ? ' nonclosable' : '') + '" role="alert">\
' + (nonclosable ? '' :
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">\
<span aria-hidden="true">×</span>\
</button>') +
text +
'</div>')`;
id && notification.attr("id", id);
return notification;
},
};
export default function App() {
function request(method, url, data, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
callback(req.responseText);
} else if (req.readyState === 4 && req.status !== 200) {
console.error(
"Can not complete request. Please check you entered a valid PLUGIN_ID and SECRET_KEY values"
);
}
};
req.open(method, url, true);
if (method !== "GET") {
req.setRequestHeader("content-type", "application/json");
}
req.send(data);
}
function loadDemoTemplate(callback) {
request(
"GET",
"https://raw.githubusercontent.com/ardas/stripo-plugin/master/Public-Templates/Basic-Templates/Trigger%20newsletter%20mockup/Trigger%20newsletter%20mockup.html",
null,
function (html) {
request(
"GET",
"https://raw.githubusercontent.com/ardas/stripo-plugin/master/Public-Templates/Basic-Templates/Trigger%20newsletter%20mockup/Trigger%20newsletter%20mockup.css",
null,
function (css) {
callback({ html: html, css: css });
}
);
}
);
}
useEffect(() => {
function initPlugin(template) {
const apiRequestData = {
emailId: "rhuzaifa2468#gmail.com",
};
const script = document.createElement("script");
script.id = "stripoScript";
script.type = "text/javascript";
script.src = "https://plugins.stripo.email/static/latest/stripo.js";
script.onload = function () {
window.Stripo.init({
settingsId: "stripoSettingsContainer",
previewId: "stripoPreviewContainer",
codeEditorButtonId: "codeEditor",
undoButtonId: "undoButton",
redoButtonId: "redoButton",
locale: "en",
html: template.html,
css: template.css,
notifications: {
info: notifications.info.bind(notifications),
error: notifications.error.bind(notifications),
warn: notifications.warn.bind(notifications),
loader: notifications.loader.bind(notifications),
hide: notifications.hide.bind(notifications),
success: notifications.success.bind(notifications),
},
apiRequestData: apiRequestData,
userFullName: "Plugin Demo User",
versionHistory: {
changeHistoryLinkId: "changeHistoryLink",
onInitialized: function (lastChangeIndoText) {
"#changeHistoryContainer".show();
},
},
getAuthToken: function (callback) {
request(
"POST",
"https://plugins.stripo.email/api/v1/auth",
JSON.stringify({
pluginId: "53c40f7b8d8c4b249b55b39ea9cda545",
secretKey: "e37d5bedd3c64055b3d18b3ff40c4e84",
}),
function (data) {
callback(JSON.parse(data).token);
}
);
},
});
};
document.body.appendChild(script);
}
loadDemoTemplate(initPlugin);
}, []);
return (
<div className="App">
<span id="changeHistoryContainer" style={{ display: "none" }}>
Last change: <a id="changeHistoryLink"></a>
</span>
<button id="undoButton" className="control-button">
Undo
</button>
<button id="redoButton" className="control-button">
Redo
</button>
<button id="codeEditor" className="control-button">
Code editor
</button>
<div id="stripoSettingsContainer"></div>
<div id="stripoPreviewContainer"></div>
</div>
);
}``
`

Related

Problem not displaying success message for each registration with Ajax

I want to do this after the user registers, shows a successful message and the text boxes are empty again and ready for the next registration, but the registration success message is only displayed for the first registration, but I want to Display each registration
public IActionResult submitSingelControlItem(int Projectid,String calender, String ProjectName,String ProjectManagementName, String ajaxControlItem,String ajaxFraindName,int SingelControlState)
{
Hesabrsee hesabrsee = new Hesabrsee();
hesabrsee.ControlDate = ConvertDateTime.ConvertShamsiToMiladi(calender);
hesabrsee.SabtDate = DateTime.Now;
hesabrsee.Projectid = Projectid;
hesabrsee.ProjectName = ProjectName;
hesabrsee.ProjectManagementName = ProjectManagementName;
hesabrsee.FaraindName = ajaxFraindName;
hesabrsee.Deiscreption = ajaxControlItem;
hesabrsee.ControlState = SingelControlState;
_context.Add(hesabrsee);
_context.SaveChanges();
return Json(new { status = "ok" });
}
<script>
$("#btn").on('click', function () {
var ajaxFraindName = $("#ajaxFraindName").val();
var ajaxControlItem = $("#ajaxControlItem").val();
var calender = $("#calender").val();
var SingelControlState = $("#SingelControlState").val();
if (ajaxFraindName == '' || ajaxControlItem == '' || calender == '' || SingelControlState == '') {
alert("لطفا ورودی ها را پر کنید");
}
else {
$.ajax({
type: "Post",
url: '#Url.Action("submitSingelControlItem", "Hasabrsee")',
data: {
'ajaxControlItem': $("#ajaxControlItem").val(),
'ajaxFraindName': $("#ajaxFraindName").val(),
'Projectid': $("#Projectid").val(),
'ProjectName': $("#ProjectName").val(),
'ProjectManagementName': $("#ProjectManagementName").val(),
'calender': $("#calender").val(),
'SingelControlState': $("#SingelControlState").val(),
}
}).done(function (res) {
if (res.status == 'ok') {
$("#ohsnap").removeClass('d-none').removeClass('alert-danger').addClass('alert-success').html('مورد کنترلی با موفقیت ثبت شد');
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
}
setTimeout(function () {
$('#ohsnap').fadeOut('fast');
}, 2000)
});
}
});
</script>
<div id="ohsnap" class="col-md-4 col-xs-12 alert d-none" style="text-align:center;"></div>
Of course, it displays the message only once because you are removing the class from the $("#ohsnap") div and then you are not restoring it.
Try using Toastr to display the popup alert. It is easier to do.
From the Toastr documentation:
Download the CSS and JS files and add them to your project.
Reference the css <link href="toastr.css" rel="stylesheet"/>
Reference the script <script src="toastr.js"></script>
in your .done() function call toastr;
.done(function (res) {
if (res.status == 'ok') {
toastr.success('title-here', 'مورد کنترلی با موفقیت ثبت شد', {
timeOut: 2000,
closeButton: true,
});
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
});

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

How to pass object from kendo grid to kendo window in MVC

How can I pass the Object of the selected row from the grid to window on button click event of the grid
.
<script>
function editItem(e) {
e.preventDefault();
var selectedObj= this.dataItem($(e.currentTarget).closest("tr"));
//selectedObj is object selected by user
var myWin = $("#windowstatus").kendoWindow({
width: "450px",
height: "250px",
title: "Some Title",
content: {
url: "../SomeURL", //controller name
data: { selectedObj } //passing obj to mvc controller
}
});
myWin.data("kendoWindow").open();
return false;
}
</script>
My ActionResult
public class XXX: Controller
{
public ActionResult Index(MyClass obj)
{
// Do Something
}
}
I cant recive the object in mvc controller and always be null
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
if (selectedItem != null && selectedItem != "" && selectedItem != undefined)
{
var wOptions =
{
content: "/xx/XxController/Index/" + selectedItem.Id//
If you have the parameter,
iframe: true,
modal: true,
width: "50%",
height: "90%",
close: function () {
this.destroy();
$('body').addClass('non-overflow');
},
open: function () {
this.center();
}
};
var windowParent = windowParent == undefined ? "list-splitter" : windowParent;
$("#" + windowParent).append("<div id='printWindow'> </div>")
$("#printWindow").kendoWindow(wOptions);
}
The following code block also calls the window js method
window: function (url, params, windowParent) {
var wOptions = {
content: url + "/?frameFilter=" + params,
iframe: true,
modal: true,
width: "90%",
height: "90%",
close: function () {
this.destroy();
$('body').addClass('non-overflow');
},
open: function () {
this.center();
}
};
windowParent = windowParent == undefined ? "pop-splitter" : windowParent;
$("#" + windowParent).append("<div id='popupWindow'> </div>")
$("#popupWindow").kendoWindow(wOptions);
},
I hope it helps

knockout validation for array of objects

I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}

Jquery dialog & Ajax posting wrong(?) result in ASP.NET MVC3 (razor)

What i want to do:
at page load to automatically pop up a jquery dialog fill in some data, post that to an action and close the dialog (regardless if the action succeeds or not).
in the View in which the pop up should occur i have the following:
<script type="text/javascript">
$(function () {
$('#PopUpDialog').dialog(
{
modal: true,
open: function ()
{
$(this).load('#Url.Action("Subscription", "PopUp")');
},
closeOnEscape: false
}
);
$('.ui-dialog-titlebar').hide();
$('#closeId').live('click',function () {
$('#PopUpDialog').dialog('close');
return false;
}
);
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize()
})
return fase;
}
);
});
</script>
the Subscription view has the following:
#using (Html.BeginForm( new { id = "SubscriptionForm" }))
{
#Html.ActionLink(Deals.Views.PopUp.SubscriptionResources.AlreadySubscribed, "", null, new { id = "closeId" })
<br />
<br />
#Deals.Views.PopUp.SubscriptionResources.FillEmail
#Html.TextBoxFor(m => Model.Email)
<input type="submit" id="subscribeId" value="#Deals.Views.PopUp.SubscriptionResources.IWantToSubscribe" />
<br />
}
which works fine.
The POST action is defined as follows:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Subscription(FormCollection formValues)
//public void Subscription(FormCollection formValues)
{
Deals.ViewModels.PopUpSubscriptionVM VM = new ViewModels.PopUpSubscriptionVM();
TryUpdateModel(VM);
if (!String.IsNullOrEmpty(VM.Email))
{
//do the update to the dbms
}
return Json(new { success = true });
}
The problem is that after posting back i get an empty screen with the success message, which i don't want!
What am i doing wrong?
You can handle the success and error callbacks:
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize(),
success: function (result) {
//Do Whatever you want to do here
},
error: function (x, e) {
//Do Whatever you want to do here
}
})
return fase;
}
To see what i am doing wrong i set up a small project (ASP.NET MVC 3) with the following ingredients:
<script type="text/javascript">
$(function () {
// Does not cache the ajax requests to the controller e.g. IE7/9 is doing that...
$.ajaxSetup({ cache: false });
var $loading = $('<img src="#Url.Content("~/images/ajax-Loader.gif")" alt="loading" class="ui-loading-icon">');
var $url = '#Url.Action("Subscription", "PopUp")';
var $title = 'Some title';
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
, closeOnEscape: false
, title: $title
, width: 500
, modal: true
, minHeight: 200
, show: 'fade'
, hide: 'fade'
});
$dialog.dialog("option", "buttons", {
"Cancel": function () {
$(this).dialog("close");
$(this).empty();
},
"Submit": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#SubscriptionForm").serialize(),
success: function (response) {
//$(target).html(response);
dlg.dialog('close');
dlg.empty();
});
}
});
$dialog.dialog('open');
})
</script>
The controllers' actions:
public ActionResult Subscription()
{
Thread.Sleep(2000); //just for testing
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
return View(VM);
}
//POST
[AcceptVerbs(HttpVerbs.Post)]
//[OutputCache(CacheProfile = "ZeroCacheProfile")]
public ActionResult Subscription(FormCollection formValues)
{
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
TryUpdateModel(VM);
return Json(new { success = true });
}
...and the according View:
#model TestModalAjax.ViewModels.PopUpVM
#{
Layout = null;
ViewBag.Title = "Subscription";
}
<h2>Subscription</h2>
#* ----- NOTICE THE FOLLOWING!!! WITHOUT THIS DATA GETS NOT POSTED BACK!!!! ---- *#
#using (Html.BeginForm("Subscription","PopUp",FormMethod.Post, new { id="SubscriptionForm"}))
{
<h1> Give me your name</h1>
#Html.TextBoxFor(M => Model.Name)
}
...so it seems everything works as expected!

Resources