GWT, access RichTextArea by non-GWT (or "regular") javascript - google-app-engine

I am writing a pretty simple CMS on GAE, and I want my users to be able to upload images.
I have written the part that does the actual uploading and showing the images, and here's what I'd like to do:
Show the usual form for new posts (with a widget that contains a rich text area and a format bar for it) and the list of images the user has ever uploaded (done). Then i want an image to appear in the text area when the user clicks that image.
I generate the list of images on the server, and i can't find a way to call any methods on the Rich Text Area from non-GWT javascript. And I don't really want to generate the list of images by means of AJAX, because it seems quite cumbersome and, hopefully, with the advent of HTML5 it is going to be much simpler.
Well, the question is, how can i access a RichTextArea in a widget from a normal javascript on a page, or is there another way of inserting an image into it (i.e. another is there a way to generate a list of images so that they would be in a kind of widget, but without the use of AJAX).
Thank you.

To answer your general question of getting access to your GWT code from hand written Javascript, you can use the general built in method or Ray Cromwell's gwt-exporter project. This way, you can expose the specific methods of the RichTextArea instance you're trying to access from external Javascript.
As for your other question, generating a list of Images should only require getting the urls for the images and creating a bunch of Image objects with the given URLs. Then display this list in a PopupPanel or some other widget.

Here is how i finally solved the problem (thanks to Arthur's reply above):
public class NewSection implements EntryPoint {
private static RichTextAreaWithFormatBar rta;
private Button pseudoSubmit;
#Override
public void onModuleLoad() {
invokeExternal("hello");
rta = new RichTextAreaWithFormatBar();
pseudoSubmit = new Button(">>>");
<...>
}
<some other code here>
public static void addImage(String a) {
rta.textarea().setHTML(
rta.textarea().getHTML() + "<br /><img src=\"/cms/i/"+ a +"\" alt=\"\"><br />");
}
native void invokeExternal(String int1) /*-{
$wnd.externalJsFunction(function(int1) {
#ur.g05.smc.client.NewSection::addImage(Ljava/lang/String;)(int1);
});
}-*/;
}
And here is the "hand-written" javascript in my templates:
(first the FreeMaker code for creating the image list in that same template):
<#list images as i>
<td><img src="/cms/i/${i.keyString()}.t" alt='' onclick='addImage("${i.keyString()}.p");'/><br /><p>${i.fullWidth()}·${i.fullHeight()}</p><p>${i.previewWidth()}·${i.previewHeight()}</p><p>${i.thumbWidth()}·${i.thumbHeight()}</p></td>
</#list>
And the script itself:
<script language="javascript">
var callBackFunction;
function externalJsFunction(func) {
callBackFunction = func;
}
function addImage(imgid) {
callBackFunction(imgid);
}
</script>
What in fact happens is:
First we create a list of images, adding an "onClick" listener to each of them with the url of each corresponding image as the argument. Image urls are formed from their Keys in the datastore, plus ".t" for thumbnails, ".p" for previews and nothing for full-size images.
Each image than calls the "addImage" function. But the addImage function has to know about the textarea, which it doesn't. To that end we create the "callBackFunction" variable, and the "externalJsFunction", that sets the value of that "callBackFunction" variable. And it sets it to whatever it gets as the argument.
Now, we can call that externalJsFunction from our Widget code and pass the function that adds an image to the textarea. However, i couldn't make it work while the richtextarea was not static.
That's basically it.
And thanks for replies and votes :)

Related

How are Javascript widgets made without iFrames?

I have a chat widget that I want to embed it other people's websites. It looks just like Intercom and all the other chat popups. I want to make the chat popup stick to the bottom-right hand corner of the screen regardless of where you scroll. However, when I import the chat app as an iframe and give it position: fixed; bottom: 0px; right: 15px;, the iframe does not go to where I expect it to go.
I realize that iframes are suboptimal for embedded JS widgets, and all the best embedded apps are importing .js files from file storage. After searching online for hours I have yet to find an explanation/tutorial on how to make those JS files that hook onto a and render the widget. How do you even make one of those pure javascript apps, and what are they called? (Not web components I assume, because there have been widgets for a long time).
Sorry if this question is kinda noob. I never knew this was a thing until I tried implementing it myself. Can anyone point me in the right direction on how to get started making JS web widgets? Thank you! (Maybe a ReactJS to VanillaJS converter would be super cool)
A pure Javascript App is called a SPA - Single Page Application - and they have full control over the document (page). But since you ask about embeding a widget, I don't think that is what this question is about (there are tons of info. on the web on SPAs).
I was going to suggest that going forward you do this using Web Components - there are polyfills available today that make this work on nearly all browsers - but since your question mentioned that you wanted to know how it is done without it, I detail below one of my approaches.
When creating a pure JS widget you need to ensure that you are aware that a) you do NOT have control over the global space and b) that it needs to play nice with the the rest of the page. Also, since you are not using Web Components (and are looking for a pure javascript (no libs)), then you also have to initialize the widget "manually" and then insert it to the page at the desired location - as oposed to a declaritive approach where you have an assigned HTML tag name for your widget that you just add to the document and magic happens :)
Let me break it down this way:
Widget Factory
Here is a simple Javascript Widget factory - the create() returns an HTML element with your widget:
const Widget = Object.create({
create(chatId) {
const wdg = document.createElement("div")
wdg.classList.add("chat-box");
wdg.innerHTML = `<h1>Chat: ${ chatId }</h1>`;
// Load your chat data into UI
return wdg;
}
});
To create a new widget (HTML Element) using the above you would:
const myWidgetInstance = Widget.create("chat-12345");
and to insert this widget into the page at a given location (ex. inside of a DIV element with id "chat_box", you would:
document.getElementById("chat_box").appendChild(myWidgetInstance);
So this is the basics of creating a Widget using the native (web) platform :)
Creating a reusable/embeddable Component
One of the key goals when you deliver a reusable and embeddable component is to ensure you don't rely on the global space. So your delivery approach (more like your build process) would package everything together in a JavaScript IIFD which would also create a private scope for all your code.
The other important aspect of these type of singleton reusable/embeddable components is that your styles for the Element needs to ensure they don't "leak" out and impact the remainder of the page (needs to play nice with others). I am not going into detail on this area here. (FYI: this also the area where Web Component really come in handy)
Here is an example of a Chat component that you could add to a page anywhere you would like it to appear. The component is delivered as a <script> tag with all code inside:
<script>(function() {
const Widget = Object.create({
create(chatId) {
const wdg = document.createElement("div");
wdg.classList.add("chat-box");
wdg.innerHTML = `<h1>Chat: ${ chatId }</h1>`;
// Load your chat data into UI
return wdg;
}
});
const myWidgetInstance = Widget.create("chat-12345");
const id = `chat-${ Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) }`;
document.write(`<div id="${ id }"></div>`);
document.getElementById(id).appendChild(myWidgetInstance);
})();</script>
So you could use this in multiple places just by droping in this script tag in the desired locations:
<body>
<div>
<h1>Chat 1</h1>
<script>/* script tag show above */</script>
</div>
...
<div>
<h1>Chat 2</h1>
<script>/* script tag show above */</script>
</div>
</body>
This is just a sample approach of how it could be done. You would have to add more in order to support passing options to each widget (ex. the chat id), defining styles as well other possible improvements that would make the runtime more efficient.
Another approach
You could add your "script" once and wait for the rest of the page to load, then search the document for a "known" set of elements (ex. any element having a CSS Class of chat-box) and then initialize a widget inside of them (jQuery made this approach popular).
Example:
Note how data attributes can be used in DOM elements to store more data specific to your widget.
<div class="chat-box" data-chatid="123"></div>
<script>(function() {
const Widget = Object.create({
create(chatId) {
const wdg = document.createElement("div");
wdg.classList.add("chat-box");
wdg.innerHTML = `<h1>Chat: ${ chatId }</h1>`;
// Load your chat data into UI
return wdg;
}
});
const initWhenReady = () => {
removeEventListener("DOMContentLoaded", initWhenReady);
Array.prototype.forEach.call(document.querySelectorAll(".chat-box"), ele => {
const myWidgetInstance = Widget.create(ele.dataset.chatid);
ele.appendChild(myWidgetInstance);
});
};
addEventListener('DOMContentLoaded', initWhenReady);
})();</script>
Hope this helps.
The best way to create Javascript widget without third-party library is to create Custom Elements.
The following link : Custom Elements v1 is a good introduction to this technology.
See a minimal example below:
class Chat extends HTMLElement {
connectedCallback () {
this.innerHTML = "<textarea>Hello</textarea>"
}
}
customElements.define( "chat-widget", Chat )
<chat-widget>
</chat-widget>

Node Webkit / Angular / Change Model

Sorry for a not very specific question by someone new to node webkit, new to Angular, new to about everything in web development:
My app is based on a JSON file that I load at the init of my node webkit app and which is at the center of a bunch of calculations.
In the app, one can open a file dialog to create a new JSON file. Now, of course, I would like the app to recalculate everything based on the new JSON. It works when I press the "refresh" button of node webkit, but I couldn't get it running by using either
require('nw.gui').Window.open('index.html');
nor
require('nw.gui').Window.get().reload(3);.
I am also wondering if handling this on the node level is the good way to do it. Shouldn't it rather be done by Angular? But I couldn't really connect to the content of my controller from an "outside" javascript.
Grateful for any hint...
Having logic on the page loading is always tricky and as you mentioned - requires page reloading what is not very elegant and modern applications avoid this.
In your case, I suggest that if your JSON file is not very big - store it in variable and modify it as needed. The elegant way will be to create Angular service, which can act as a "model".
angular.service('JsonService', function() {
var json = {
// content
};
return {
getJson: function () {
return json;
},
setJson: function (newJson) {
json = newJson;
}
};
});
Then, whenever you need to update JSON invoke setJson(newJson) method and modify your controllers to use the service getJson() method.
You can also add the loading/saving to file functions to this service. The loading function can be invoked in your main controller connected to your dashboard page. Then before the first page will be visible, the JSON file will be already loaded and you preserve desired behavior.

CakePHP - render whole page as HTML to attach to email

I have successfully created a report accessed at /controller/report
I now want to create a separate controller method to create this report as an HTML file and email it to designated useds. I have done this but have hit one snag. When the HTML file is rendered, it is only the view element from the /report method - the layout (including the CSS) is not rendered.
Here's the basic structure:
public function email_report() {
$render = $this->requestAction('/controller/report');
//$render is then used by fwrite to create a .HTML file, which is then attached to an email
}
public function report() {
//yada yada
//render in report layout rather than default
$this->render('report', 'reports');
}
So the problem is that $render only contains the view stuff, not the stuff from my "reports" layout. What do I need to do to get the layout in my HTML file as well?
I could put all of the HTML in the view but I would like to create other reports using the same layout in future and would like to avoid repetition.
use the following instead. Note the extra array argument passed to the function
bare indicates whether or not to include layout. setting it to 0 i.e false forces it to include layout. Including return sets requested to 1. requested indicates whether request is from requestAction or not.
Visit http://book.cakephp.org/2.0/en/controllers/request-response.html and http://book.cakephp.org/2.0/en/controllers.html for reference
$this->requestAction('/controller/report', array('return', 'bare' =>
0));

Add button to existing standardController page SalesForce

I want to add a button to an existing SalesForce object page that already has a standardController and page built by salesforce.
I have a utility class that I want to call a function by a button on my object.
Currently, I only have seen ways of doing this by a WebService, which I included the code snippets below. I am thinking there has to be another way, due to the fact I want to reuse this code in other places that do not require a webservice, and I want to avoid writing two procedures for same thing. I know I could use a wrapper I guess, but want to see if there is another way of adding a button that is more in line with the new salesforce way of visualpages, and not s-controls/web services.
So, when I add a button on the salesforce page by going to setup-->create-->objects then scroll down to add a button, it requires that the button be an scontrol or javascript. I found this technique
Apex code:
global class class1{
WebService static Integer method1(String iTitle){
Your logic here
}
}
Custom button code:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")}
var result = sforce.apex.execute("class1", "method1",{iTitle : noteTitle});

Backbone Marionette modules as Widgets similar to Twitter Flight

I'm reading up in choosing the correct client-side framework to segment/modularize my frontend code in Widgets.
Basically what I have/want is:
a complex website with multiple pagetypes, so no single-page application.
all pages are able to render a complete page WITHOUT the use of javascript. IOW: javascript is used as enrichment only.
Lots of pages have a very dynamic way in which widgets can be shown on screen. To overcome complexity at the server-side I've modularized my code into widgets (composite pattern), where each widget is responsible for it's own:
server-side controller code
server-side templating (using hogan/mustache)
routing endpoints, should it need to be called from the client
structural css (css converning the structure of the widget as opposed to the look&feel)
a server-side RegionManager ultimately decides which widgets are rendered and where they are rendered on screen. Endresults is that the RegionManager spits out the entire html (server-generated) as the composite of the rendering of all of it's widgets.
Now, some of these widgets DO have client-side logic and need rerendering on the client. Take a searchpage for instance, which needs to be able to update through ajax. (I've described this process, which uses DRY templating on client and server, here)
What I ultimately want is that, given I already use the composite pattern on the server, to extend this to the client somehow so that a Widget (1 particular logic block on the screen) contains all mentioned server-side code, plus all needed client-side code.
I hope this makes sense.
Would Marionette be suited to be used as a client side framework in this scenario? I'm asking since I'm not 100% sure if the concept of a Marionette Module is what I describe as being a Widget in above scenario. (I'm mentioning Twitter Flight in my question, since I believe this would be a fit, but it currently is so new that I'm hesitant to go with it at the moment_
I think basically what I'm asking is if anybody has some experience doing something along these lines.
I think just using Backbone.js is perfect for this type of application you are describing. You have probably already read this, but most of the backbone literature is focused around your views having associated server generated JSON models and collections, then using the View's render function to generate (on the client) the HTML UI that represents the model/collection.
However it doesn't have to be used this way. In fact there is nothing stopping you attaching views to existing elements that contain content already, which gives you all of the benefits of Backbone's modularity, events system and so on. I often use views that have no model or collection, purely because I like the conformity of style. I have also used an approach like I describe below in the cases where I have had to work with older, existing applications that have not yet got, or never will have a nice REST API, but they do provide content in HTML.
Firstly, lets assume the following HTML represents one of your widgets:
<div id="widget">
<div class="widget-title"></div>
<div class="widget-body">
<!-- assume lots more html is in here -->
Do something!
</div>
</div>
In this case, you could use backbone with a single Widget Model. This would be a very simple model, like this:
App.WidgetModel = Backbone.Model.extend({
intialize: function () {
this.url = this.options.url;
}
});
Take note of the fact the Widget receives a URL as a parameter to its constructor/initialize function. This widget model would represent many of your widgets (and of course you could adopt this general approach with more complicated models and pluck different data from the rendered HTML). So next for your views. As you probably know, normally you pass most views a model or collection when you instantiate them. However in this case, you could create the Widget model in your View's initialize Function and pass it a URL from the pre-rendered HTML as follows:
App.WidgetView = App.View.ComboboxView = Backbone.View.extend({
initialize: function () {
this.model = new App.WidgetModel({}, { url: this.$("a").attr("href") });
}
// rest of the view code
});
So instantiating the view would be something like:
new App.WidgetView({el: $("#widget")})'
By doing all of the above you can do pretty much everything else that backbone offers you and its modular and encapsulated nicely, which is what you are after.
The end result of this whole approach is:
You have rendered the Widget UI as pure HTML which (I assume) is functional without JavaScript.
You attach a View to the existing HTML.
You pass into the View as options, content by extracted (such as a URL) from the rendered HTML with jQuery.
The View is responsible for instantiating the Model passing on the relevant options the model needs (such as a URL).
This means all dynamic server side content is intially contained in the rendered HTML and your View is a modular JavaScript component that can do stuff to it, which I think is the end result you're after.
So you mentioned that you would like to have AJAX functionality for your widgets and that fine with this approach too. Using this approach, you can now use the standard Backbone fetch and save functions on the Widget model to get new content. In this example it is from the URL retrieved from the rendered HTML. When you get the response, you can use the view's, render function, or other finer grained functions to update the HTML on the page as required.
A few points:
The only thing to look out for is that you'll need to change the content type of the fetch and save functions to "text/html" if that's what the server is providing. For example:
this.model.fetch({
type: "POST",
contentType: "text/html"
});
Lastly, the model I have proposed is instantiated with no content. However if your ajax calls are a content type of "text/html", you may need to play around with you model so it can store this content in its attributes collection properly. See this answer for more information.

Resources