How can I enable the Search Box in an Ace Editor? - javascript

Hello stackOverflow community, this is my first question here and I'm wondering how to enable the Search Box in an Ace Editor.
I have a current demo of the project here. So far the editor has Emmet and Autocomplete. The next feature I need is the search box showing when the user presses CTRL+F in the editor.
Here is the code I used to configure the editor:
let e = document.querySelector("#editor");
let editor = ace.edit(e);
let langTools = ace.require("ace/ext/language_tools");
let Emmet = require("ace/ext/emmet");
ace.config.set("basePath", "path");
ace.config.loadModule("ace/ext/searchbox", function(m) {m.Search(editor)});
editor.getSession().setMode("ace/mode/html");
editor.setOptions({
minLines: 24,
maxLines: 24,
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true,
enableEmmet: true
});
editor.session.setUseWrapMode(true);
editor.session.on("change", function () {
window.onbeforeunload = function () {
return "Changes you made might not be saved";
};
var unloadListener = function () {
return "Changes you made might not be saved";
};
window.addEventListener("beforeunload", unloadListener);
editor.execCommand("find")
});
Can someone please help me to figure out what scripts to import and how to enable it?
Thanks.

It should be built into a standard build.
editor.execCommand('find');
should display the searchBox. You can also use
editor.searchBox.show();
editor.searchBox.hide();
to show it manually (ie to implement your own key bindings). Ace has built in key bindings and there are advantages to using them (as well as disadvantages, such as they only work when you are focused on the editor). You should disable the internal "find" command if you're going to implement your own.

Related

Open a CEP dialog from a CEP extension in After Effects

I have a CEP extension in After Effects and I want it so that when a user clicks a button, a settings dialog opens up in a new floating dialog box. Seems like it would be such basic functionality but somehow I'm not seeing anywhere in the (admittedly sparse) documentation how to open up a dialog box. I've seen some other people say that you can make a hidden extension which opens the dialog, but I've seen no example of that and it is unclear how that would work to me.
You can look up documentation for ScriptUI. Heres a link to the pdf: https://adobeindd.com/view/publications/a0207571-ff5b-4bbf-a540-07079bd21d75/92ra/publication-web-resources/pdf/scriptui-2-16-j.pdf
You can create a dialog either in a function in the jsx, or give it its own jsx page and //#include it onclick.
I know this is kind of a generic answer, but incase anyone else is having trouble this will give you a good jumping off point.
So in order to provide the functionality you need, you'll have to initialize a dialog box first, then add a button, then force it to open a specific settings dialog. I recommend something like this:
var dialog = new Window("dialog");
dialog.text = "After Effects Dialog Script";
//Contents
var newMsg = dialog.add("group", undefined, {name: "newMsg"});
newMsg.orientation = "column";
var newMsgText = newMsg.add("statictext", [0, 0, 400, 40], "", {name: "newMsgText", multiline: true});
newMsgText.text = "Would you like to open a settings dialog?";
//Button UI
var buttonPanel = dialog.add("group", undefined, {name: "buttonPanel"});
buttonPanel.orientation = "row";
buttonPanel.alignChildren = ["center", "bottom"];
var enter = buttonPanel.add("button", undefined, undefined, {name: "ok"});
enter.text = "Continue";
enter.value = true;
var cancel = buttonPanel.add("button", undefined, undefined, {name: "cancel"});
cancel.text = "Cancel";
cancel.value = false;
//Runs the dialog code
dialog.show();
//Grabs answer to yes or no question
var dialogInput = dialog.show();
if(dialogInput == true){
app.openDlg (prompt, filter, multiSelect); //Essentially
}
else {
alert("The action was canceled.");
}
You will have to find the direct path to the CEP dialog you wish to open. I'm unfamiliar with them and their integrations to After Effects, so I can't help you much beyond getting the script set up. However I have a few comments on resources that may be of assistance here too.
That ScriptUI resource by Peter Kahrel is fantastic. I've been working with it for the last few weeks. I wanted to add on to what Jake L said by dropping in a few more great examples of Extendscript Support because you kinda have to dig for the documentation, but it's definitely there.
https://extendscript.docsforadobe.dev/
I just stumbled upon the Extendscript Library recently, but it details a lot of functions, dives deep into events and event handlers, and even explains how you can set up an environment for extendscript via vscode.
I also like to check out NTProductions on youtube for assistance. I'm working in Indesign, but a lot of the extendscript functions work between the various adobe programs and you can even troubleshoot basic functions in the Adobe ExtendScript Toolkit.
And if you already have an Adobe CC account, don't forget to download the Scripting SDK from adobe APIs and Services. You'll have to sign in to get there, but it's a pretty useful local documentation.
https://developer.adobe.com/console/servicesandapis/id#
EDIT (again): I also found these after posting and will commit to adding more as I find them. Extendscript documentation must become more available! :-)
https://docsforadobe.dev/
http://yearbook.github.io/esdocs/#/

Insert text into an existing / external draftjs textfield

I'm working on an application which needs to insert text into a contenteditable="true" div (a Draftjs based textfield to be precise).
Now I am aware that Draft.js uses react and that it should be used that way, but in this case, the application already exists and this is a third party electron app that works with it.
I'm working on in-line notification replying on macOS, so I need that reply text to be pasted inside the draftJS field, however, when I do so using:
document.querySelector('div[contenteditable="true"]').focus();
document.execCommand('insertText', false, 'message');
It throws an error:
I was able to make it work using:
const event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, 'message', 0, locale);
but this API is deprecated and doesn't work properly if the message contains an emoji.
Is there any way to do this that doesn't cause an error?
I found out that the new API that is supposed to replace initTextEvent is just new Event() (see docs), but I can't find out if it supports textInput events.
To play around with it you can just go to https://draftjs.org/ and play with it in chrome dev tools.
I would really appreciate some help here as I don't know what to do to make it work anymore. Also, I know people are a fan of jquery, but I'd prefer a native js solution (although any solution is welcome).
edit:
Please note:
I'm not using react, the input field I want to modify (draftjs) is using react and I want to input text into it using native js.
edit 2:
For anyone else coming across this issue, I wanted to insert text into the Facebook messenger text field (which uses Draftjs).
I managed to find a working workaround.
It does use the deprecated API (event.initTextEvent), but it's the only way that I've found that works, even with emoji. Please do post an answer if you have a better solution to this.
It works like this:
async function sendReply(message: string): Promise<void> {
const inputField = document.querySelector('[contenteditable="true"]') as HTMLElement;
if (inputField) {
const previousMessage = inputField.textContent;
// Send message
inputField.focus();
await insertMessageText(message, inputField);
(await elementReady('._30yy._38lh._39bl')).click();
// Restore (possible) previous message
if (previousMessage) {
insertMessageText(previousMessage, inputField);
}
}
}
function insertMessageText(text: string, inputField: HTMLElement): void {
// Workaround: insert placeholder value to get execCommand working
if (!inputField.textContent) {
const event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, '_', 0, '');
inputField.dispatchEvent(event);
}
document.execCommand('selectAll', false, undefined);
document.execCommand('insertText', false, text);
}
This is typescript code, so you might want to change it up to use js.
It works by inserting a placeholder value inside the textField using event.initTextEvent, and then replacing that text with:
document.execCommand('selectAll', false, undefined);
document.execCommand('insertText', false, 'text');
tested in Chrome: Version 71.0.3578.98
Although the question was asked a long ago and #JoniVR found a workaround, this may help someone else.
I was also having a similar problem while working on an extension. I also tried the method document.execCommand('insertText', false, text). It worked on LinkedIn but not on Facebook. It was inserting text in the wrong node. Although document.execCommand API works in some places, it's obsolete now.
For Facebook and any other sites using drafjs editor, We need to dispatch a paste event using dataTransfer and clipBoardEvent APIs to make draftjs think that the text is pasted and process accordingly.
const dataTransfer = new DataTransfer();
function dispatchPaste(target, text) {
// this may be 'text/html' if it's required
dataTransfer.setData('text/plain', text);
target.dispatchEvent(
new ClipboardEvent('paste', {
clipboardData: dataTransfer,
// need these for the event to reach Draft paste handler
bubbles: true,
cancelable: true
})
);
// clear DataTransfer Data
dataTransfer.clearData();
}
Check this link in case more info needed.

bindRows is not a function

I am trying to bind data from NWGW to an existing javascript table for Input value help using getTable().bindRows.
Development tool is WebIDE, All connections are checked. All oData services are OK and providing Live Data, metadata OK.
But I keep getting
Uncaught TypeError: oValueHelpDialog.getTable(...).bindRows is not a
function.
This only happens if the app is running on a small screen device (phone or if I choose phone layout in Chrome Dev Tool).
I don't know if it is because it can get the odata to bind to the table? Does phone handle UI5 differently?
I would appreciate any help. Thanks
-------Update-------
Thank to a nice guy in Answer.SAP. Here is the sample project
Step to reproduce the error:
Import the project to Web IDE
Execute the index.html
Open Chrome Dev Tool
Choose device: iPhone 6/7/8 or whatever phone
Refresh (F5) the app
Click on Value Help Dialog again > lead to a blank table
-------Update END-------
Fragment view
var oValueHelpDialog = new sap.ui.comp.valuehelpdialog.ValueHelpDialog({
title : oController.getStrTextSite(),
supportMultiselect : false,
supportRanges : false,
supportRangesOnly : false,
key : oController.getStrWERKS(),
descriptionKey : oController.getStrNAME1(),
ok: function(oControlEvent) {
oController.setDefaultSiteFromHelp(oControlEvent);
oValueHelpDialog.close();
},
cancel: function(oControlEvent) {
oValueHelpDialog.close();
},
afterClose: function() {
oValueHelpDialog.destroy();
}
});
...
return oValueHelpDialog;
}
Controller
onValueHelpForDefaultSite : function(oEvent) {
var oValueHelpDialog = this.getFragmentForValueHelp();
oValueHelpDialog.open();
...
oValueHelpDialog.getTable().bindRows(
this.getEntitySet(
"ODATA_10_DEFAULT_SITE_SET",
"ODATA_10"
)
);
}
Turns out that in mobile, function bindRows() does not exist so we have to replace it with function bindItems()

Copy to clipboard with Javascript in Firefox

I really need a way to copy some text to the OS clipboard in Firefox.
Know it is easy in IE and not possible in Chrome and Opera unless flash is used. Because of different reasons I am unable to use the flash solution!
Had it working in the past but now the netscape.security.PrivilegeManager.enablePrivilege is protected as far as I can figure out (since ver. 17).
It looks as if it is still possible according to this article:
https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Believe it is still necessary to enable the possibility in the user.js file like this
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.sites", "http://");
user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess");
But how shall I do it? Have made some test without great success and think there is no guide on the web that explain how it shall be done in a generic way. E.g. a simple guide about how to enable javascript access to the clipboard. Hopefully also a guide that can be used by the novice user. Like to do it and post it here but need a working solution first.
According to the web there are 2 solutions for copy to clipboard;
document.execCommand("copy", false, null)
and
var gClipboardHelper = Components.classes["#mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
gClipboardHelper.copyString("Put me on the clipboard, please.");
Both generate a failure with my first try.
The solution below need the user to press CTRL+C and I need a solution where the text shall copy based on the press of a button (many on a single page).
https://stackoverflow.com/questions/4344325/copy-to-clipboard-on-firefox-and-google-chrome/11346026#11346026
My old solution was like this:
var clip = Components.classes['#mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if(clip)
{
var trans = Components.classes['#mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if(trans)
{
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if(str)
{
var clipid=Components.interfaces.nsIClipboard;
if(clipid)
{
str.data = cliptext;
trans.addDataFlavor('text/unicode');
trans.setTransferData("text/unicode", str, cliptext.length*2);
clip.setData(trans, null, clipid.kGlobalClipboard); // No return value
return 0;
}
}
}
}
Components.classes is undefined in unprivileged code (not add-on etc) so I do not believe any solution with this will work any more. One option is to make an add-on that will execute in privileged code area and send the text that shall be copied to this add-on for it to handle the copy to the OS clipboard (nice new possible project).
This only leave document.execCommand("copy", false, null) in the field as a stand alone solution.
Tried this code and it does not copy anything to the OS clipboard - but do not generate any errors btw.
var pre = document.getElementById('pcryptcopytext');
if(!pre)
{
pre = document.createElement("pre");
pre.setAttribute('id', 'pcryptcopytext');
pre.setAttribute('style', 'opacity: 0; position: absolute; top: -10000px; right: 0;');
document.body.appendChild(pre);
}
pre.innerHTML = cliptext;
pre.contentEditable = true;
//pre.unselectable = "off";
//pre.focus();
if (document.createRange)
{
var rng = document.createRange();
rng.selectNodeContents(pre);
document.execCommand("copy", false, null);
document.body.removeChild(pre);
}
So, anybody got a working solution?
Looks like this is not supported any more, and there is no replacement :(
https://support.mozilla.org/en-US/questions/977068#answer-500083
Maybe making some noise in a Firefox bug will help us get a (safe) solution.
Solved by creating a Firefox Add-on that exposes the clipboard object: https://github.com/myplaceonline/myplaceonline_ffclipboard
Example:
if (window.ffclipboard) {
window.ffclipboard.setText("clipboard text");
}
You can use firefox navigator object
navigator.clipboard.writeText("text you want to copy").then(() => {
// on success
}, (e) => {
// on error
});
document.execCommand("copy");

Autocompletion for Ace Editor

OK, so here's the deal:
I'm using Ace Editor
The app the editor is integrated in, is written Objective-C/Cocoa
I need AutoCompletion (for a given set of keywords)
Now, here's the catch :
I know AutoCompletion is not yet natively supported
I know of some attempts by others (e.g. Codiad IDE, Gherkin, Alloy-UI), some making use of Jquery UI Autocomplete - but I still cannot figure out how this could be adapted to an existing Ace setup
I'm still not sure if I should go for a JS-oriented solution or just use Objective-C/Cocoa for that
Any help would be more than appreciated.
AutoCompletion can be achieved in ace editor..
Code :
var editor = ace.edit('editor');
editor.setTheme("ace/theme/eclipse");
editor.getSession().setMode("ace/mode/java");
editor.setShowInvisibles(true);
editor.setDisplayIndentGuides(true);
editor.getSession().setUseWrapMode(true);
var jsonUrl = "JSON/Components/proce.json";
//the url where the json file with the suggestions is present
var langTools = ace.require("ace/ext/language_tools");
editor.setOptions({enableBasicAutocompletion: true});
var rhymeCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
if (prefix.length === 0) { callback(null, []); return }
$.getJSON(jsonUrl, function(wordList) {
callback(null, wordList.map(function(ea) {
return {name: ea.word, value: ea.word, meta: "optional text"}
}));
})
}
}
langTools.addCompleter(rhymeCompleter);
Json file format :
[ {"word":"hello"},
{"word":"good morning"},
{"word":"suggestions"},
{"word":"auto suggest"},
{"word":"try this"}]
Reference/Demo :
http://plnkr.co/edit/6MVntVmXYUbjR0DI82Cr?p=preview
To add Live Auto Completion in Ace nowadays:
In your HTML include the ace/ext-language_tools.js.
The . call does not work well yet, so you may have to enter ctrl-space or alt-space for that, but standard syntax stuff such as writting function, will now show.
Then:
var editor = ace.edit("editor");
ace.require("ace/ext/language_tools");
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
The hard part of autocompletion is figuring out the keywords the rest is easy to do.
you need a popup, and listView to display completions, it might
be better to use Cocoa based popup.
some filtering function, simple startsWith check will do, but you can use nicer flex match
like sublime
trivial call to editor.session.replace to insert
selected completion
For 2-3 you should comment at https://github.com/ajaxorg/ace/issues/110 about your specific usecase since there is a work to get native support for AutoCompletion.

Categories

Resources