Parsys (targerparsys) inside targetparsys - aem

We have a target area (target and targetparsys) with component which is a container (parsys) with some components. The problem is that when this container is situated in target area, parsys of container becomes a targetparsys inside of which there isn't a possibility to edit inside components. Does this issue has the solution?
I've tried to overlay the logic of creating the overlay in overlayManager.js. It has solved a little bit the problem, but there isn't a proper work of reordering components inside of it.

I overlayed the following file - /cq/gui/components/authoring/editors/clientlibs/core/js/overlayManager.js by changing and adding the following code:
self.create = function (editable) {
if (!editable.overlay) {
var parent = ns.editables.getParent(editable);
// going up recursively until we reach the root container
if (parent && !parent.overlay) {
self.create(parent);
}
// we check again because a child overlay might also be created by the parent constructor
if (!editable.overlay) {
editable.overlay = new overlayConstructor(editable, parent ? parent.overlay.dom : container);
}
// get children sorted by depth of their paths
var sortedChildren = getSortedChildren(editable, true);
//and going down recursively until we reach the deepest editable
sortedChildren.forEach(function (child) {
self.create(child);
});
}
};
/**
* Returns the sorted {Array} of child {#link Granite.author.Editable}s by depth of their paths for the given {#link Granite.author.Editable}
*
* #param {Granite.author.Editable} editable - {#link Granite.author.Editable} for which to find child editables to be sorted by depth of their paths
* #param {Boolean} all - All the children or only the direct descendant
*
* WARNING! Not OTB function! See the description on {self.create = function(editable)}
*/
function getSortedChildren(editable, all){
var children = ns.editables.getChildren(editable, all);
//key - editable, value - number of slashes
var childrenMap = new Map();
//going through all children
for (let i = 0; i < children.length; i++){
var path = children[i].path;
var numberOfSlashes = 1;
var isFirstSlashChecked = false;
//searching slashes
for (let j = 0; j < path.length; j++){
var letter = path[j];
var SLASH = '/';
if (letter == SLASH){
if (isFirstSlashChecked){
childrenMap.set(children[i], ++numberOfSlashes);
} else {
childrenMap.set(children[i], numberOfSlashes);
isFirstSlashChecked = true;
}
}
}
//if there are not slashes in editable path
if (!isFirstSlashChecked){
childrenMap.set(children[i], 0);
}
}
//sort map by depth (number of slashes)
var sortedChildrenMapByPaths = new Map([...childrenMap.entries()].sort((a, b) => a[1] - b[1]));
//return sorted editables
return Array.from(sortedChildrenMapByPaths.keys());
}
And also added checking null statement here:
function repositionOverlay(editable) {
var parent;
// if there is no overlay in place, don't bother we ignore it (most likely timing issue)
if (editable.overlay) {
parent = ns.editables.getParent(editable);
//the place which was overlaid
// don't rely on order of editables in the store...
if (parent && parent.overlay != null && !parent.overlay.currentPos) {
repositionOverlay(parent);
}
editable.overlay.position(editable, parent);
}
}

Related

Getting undefined when selecting html element in Javascript

I have a number of tv display clones loaded onto my page. After the clone is made, it will create a new TV object at the end of the loop definition, but for some reason, when it tries to access the index based canvas element from the page, it returns undefined. I tested that when hardcoding cnvs[0] from inside the constructor, it will return the canvas element. Indexing cnvs1 will return undefined; however, I see the tv has already been cloned before this line is executed. Shouldn't there then be a second canvas element of class ".static" that can be selected? In addition to the code, I attached a screenshot of my debugger screen in Chrome to see what the scope reads following "this.cnv = cnvs1", which should dynamically be cnvs[this.index]. Thanks in advance!
const container = document.getElementsByTagName("main")[0];
const template = document.getElementsByClassName("tv-set")
const cnvs = $(".static");
/**TBD**/
class TV {
constructor (id = "tv-0", name = "Blank Slate") {
this.id = id;
this.name = name;
console.log("NEW TV CREATED: ", this);
console.log("ID: ", this.id);
this.gifArr = gifCarousel_dict[this.name];
console.log("Media selection for this tv: ", this.gifArr);
// this.cnv = $(this.id).find('.static')[0];
// this.cnv = document.querySelector("[data-name=" + CSS.escape(this.id) + "]");
this.index = getSecondPart(id);
// this.cnv = $(".static")[this.index + 1];
this.cnv = cnvs[1];
console.log(this.cnv);
this.cnv.setAttribute("c", this.cnv.getContext("2d"));
this.cnv.setAttribute("cw", this.cnv.offsetWidth);
this.cnv.setAttribute("ch", this.cnv.offsetHeight);
this.staticScrn = this.cnv.getAttribute("c").createImageData(this.cnv.setAttribute("ch"), this.cnv.setAttribute("cw"));
console.log("This canvas element: ", this.cnv);
//Static display
this.isStatic = true;
}
showStatic() {
console.log(`Printing the tv name from the prototype fxn: ${this.name}`);
// this.isStatic = true;
c.clearRect(0, 0, cw, ch);
for (var i = 0; i < staticScrn.data.length; i += 4) {
let shade = 127 + Math.round(Math.random() * 128);
staticScrn.data[0 + i] = shade;
staticScrn.data[1 + i] = shade;
staticScrn.data[2 + i] = shade;
staticScrn.data[3 + i] = 255;
}
c.putImageData(staticScrn, 0, 0);
staticTO = setTimeout(runStatic, 1e3 / staticFPS);
}
}
for (let i = 0; i < phases.length; i++) {
const clone = template[i].cloneNode(true);
clone.setAttribute("id", "tv-" + (i + 1))
console.log("clone id: ", clone.getAttribute("id"))
clone.setAttribute("data-channel", 0)
clone.setAttribute("name", phases[i])
// clone.style.backgroundColor = phases[i].channels[0]
container.appendChild(clone)
var tvName = 'tvPhase' + clone.getAttribute("name");
//Instantiate TV object
window['tvPhase' + clone.getAttribute("name")] = new TV(clone.getAttribute("id"), clone.getAttribute("name"));
console.log("New Tv Created: ", tvName)
}
As I was about to post this question, I caught my bug...but I figured perhaps someone could learn from my stupid mistake! Turns out, it was because of line const cnvs = $(".static"); Setting this constant prior to the cloning operation means it will contain only the first canvas element and cannot be changed even after clones are created since it's a constant (face palm). The solution, of course, is to just define this.cnv = $(".static")[this.index]; directly or set the global cnvs as a var/let cnvs, still wrapping my head around when to use which.

How to select which layer to show on a map?

If I had an array of layers added to my map, i.e.:
for (i = 0; i < myoptionsArray.length; i++) {
lyr = L.tileLayer.wms(url, {optionsArray[i]});
layer.push(lyr);
lyr.addTo(mymap);
}
how can I select programmatically which layer[i] to show? I can't find any available function in Leaflet docs...
Add your layer to a featureGroup when you create it. A great idea is to add a name to your layer so it will be simpler to get it after :
var group = new L.featureGroup();
for (i = 0; i < myoptionsArray.length; i++) {
lyr = L.tileLayer.wms(url, {optionsArray[i]});
layer.push(lyr);
layer.name = 'My_layer ...';
lyr.addTo(group);
}
mymap.addLayer(group);
In this example, for me, each iteration provide a layer. You add it to your group and wait the end of the loop to add it to the map.
To show or hide you will need this function :
function showHideTile(tileToShowOrHide)
{
group.eachLayer(function(layer) {
layer.eachLayer(function(yourLayer) {
//Do your test here
if (yourLayer == tileToShowOrHide) {
//To add the layer to your map
map.addLayer(yourLayer);
} else {
//To remove the layer
map.removeLayer(yourLayer);
}
//You can also send an array to this function
//With the layer name and what you want to do
//Ex : tile1 hide
})
})
}
Not the best way but it will give you something to start with.
I did this way.
1- load the layers into the group:
var group = new L.featureGroup();
for (i = 0; i < myoptionsArray.length; i++) {
lyr = L.tileLayer.wms(url, {optionsArray[i]});
layer.push(lyr);
lyr.addTo(group);
}
mymap.addLayer(group);
2 - Then I added a function to show the layer I need:
function showLayer(i) {
layer[i].bringToFront();
}

How to remove L.rectangle(boxes[i])

I few days ago I implement a routingControl = L.Routing.control({...}) which works perfect for my needs. However I need for one of my customer also the RouteBoxer which I was also able to implement it. Now following my code I wants to remove the boxes from my map in order to draw new ones. However after 2 days trying to find a solution I've given up.
wideroad is a param that comes from a dropdown list 10,20,30 km etc.
function routeBoxer(wideroad) {
this.route = [];
this.waypoints = []; //Array for drawBoxes
this.wideroad = parseInt(wideroad); //Distance in km
this.routeArray = routingControl.getWaypoints();
for (var i=0; i<routeArray.length; i++) {
waypoints.push(routeArray[i].latLng.lng + ',' + routeArray[i].latLng.lat);
}
this.route = loadRoute(waypoints, this.drawRoute);
}; //End routeBoxer()
drawroute = function (route) {
route = new L.Polyline(L.PolylineUtil.decode(route)); // OSRM polyline decoding
boxes = L.RouteBoxer.box(route, this.wideroad);
var bounds = new L.LatLngBounds([]);
for (var i = 0; i < boxes.length; i++) {
**L.rectangle(boxes[i], {color: "#ff7800", weight: 1}).addTo(this.map);**
bounds.extend(boxes[i]);
}
console.log('drawRoute:',boxes);
this.map.fitBounds(bounds);
return route;
}; //End drawRoute()
loadRoute = function (waypoints) {
var url = '//router.project-osrm.org/route/v1/driving/';
var _this = this;
url += waypoints.join(';');
var jqxhr = $.ajax({
url: url,
data: {
overview: 'full',
steps: false,
//compression: false,
alternatives: false
},
dataType: 'json'
})
.done(function(data) {
_this.drawRoute(data.routes[0].geometry);
//console.log("loadRoute.done:",data);
})
.fail(function(data) {
//console.log("loadRoute.fail:",data);
});
}; //End loadRoute()
Well, my problem is now how to remove previously drawn boxes in order to draw new ones because of changing the wideroad using a dropdown list. Most of this code I got from the leaflet-routeboxer application.
Thanks in advance for your help...
You have to keep a reference to the rectangles so you can manipulate them (remove them) later. Note that neither Leaflet nor Leaflet-routeboxer will do this for you.
e.g.:
if (this._currentlyDisplayedRectangles) {
for (var i = 0; i < this._currentlyDisplayedRectangles.length; i++) {
this._currentlyDisplayedRectangles[i].remove();
}
} else {
this._currentlyDisplayedRectangles = [];
}
for (var i = 0; i < boxes.length; i++) {
var displayedRectangle = L.rectangle(boxes[i], {color: "#ff7800", weight: 1}).addTo(this.map);
bounds.extend(boxes[i]);
this._currentlyDisplayedRectangles.push(displayedRectangle);
}
If you don't store a reference to the L.rectangle() instance, you obviously won't be able to manipulate it later. This applies to other Leaflet layers as well - not storing explicit references to Leaflet layers is a usual pattern in Leaflet examples.

How to define cycles with observables

I'm trying to set up the update loop of a simple game, built with observables in mind. The top-level components are a model, which takes input commands, and produces updates; and a view, which displays the received updates, and produces input. In isolation, both work fine, the problematic part is putting the two together, since both depend on the other.
With the components being simplified to the following:
var view = function (updates) {
return Rx.Observable.fromArray([1,2,3]);
};
var model = function (inputs) {
return inputs.map(function (i) { return i * 10; });
};
The way I've hooked things together is this:
var inputBuffer = new Rx.Subject();
var updates = model(inputBuffer);
var inputs = view(updates);
updates.subscribe(
function (i) { console.log(i); },
function (e) { console.log("Error: " + e); },
function () { console.log("Completed"); }
);
inputs.subscribe(inputBuffer);
That is, I add a subject as a placeholder for the input stream, and attach the model to that. Then, after the view is constructed, I pass on the actual inputs to the placeholder subject, thus closing the loop.
I can't help but feel this is not the proper way to do things, however. Using a subject for this seems to be overkill. Is there a way to do the same thing with publish() or defer() or something along those lines?
UPDATE: Here's a less abstract example to illustrate what I'm having problems with. Below you see the code for a simple "game", where the player needs to click on a target to hit it. The target can either appear on the left or on the right, and whenever it is hit, it switches to the other side. Seems simple enough, but I still have the feeling I'm missing something...
//-- Helper methods and whatnot
// Variables to easily represent the two states of the target
var left = 'left';
var right = 'right';
// Transition from one side to the other
var flip = function (side) {
if (side === left) {
return right;
} else {
return left;
}
};
// Creates a predicate used for hit testing in the view
var nearby = function (target, radius) {
return function (position) {
var min = target - radius;
var max = target + radius;
return position >= min && position <= max;
};
};
// Same as Observable.prototype.scan, but it also yields the initial value immediately.
var initScan = function (values, init, updater) {
var initValue = Rx.Observable.return(init);
var restValues = values.scan(init, updater);
return initValue.concat(restValues);
};
//-- Part 1: From input to state --
var process = function (inputs) {
// Determine new state based on current state and input
var update = function(current, input) {
// Input value ignored here because there's only one possible state transition
return flip(current);
};
return initScan(inputs, left, update);
};
//-- Part 2: From display to inputs --
var display = function (states) {
// Simulate clicks from the user at various positions (only one dimension, for simplicity)
var clicks = Rx.Observable.interval(800)
.map(function (v) {return (v * 5) % 30; })
.do(function (v) { console.log("Shooting at: " + v)})
.publish();
clicks.connect();
// Display position of target depending on the model
var targetPos = states.map(function (state) {
return state === left ? 5 : 25;
});
// Determine which clicks are hits based on displayed position
return targetPos.flatMapLatest(function (target) {
return clicks
.filter(nearby(target, 10))
.map(function (pos) { return "HIT! (# "+ pos +")"; })
.do(console.log);
});
};
//-- Part 3: Putting the loop together
/**
* Creates the following feedback loop:
* - Commands are passed to the process function to generate updates.
* - Updates are passed to the display function to generates further commands.
* - (this closes the loop)
*/
var feedback = function (process, display) {
var inputBuffer = new Rx.Subject(),
updates = process(inputBuffer),
inputs = display(updates);
inputs.subscribe(inputBuffer);
};
feedback(process, display);
I think I understand what you are trying to achieve here:
How can I get a sequence of input events going in one direction that feed into a model
But have a sequence of output events going in the other direction that feed from the model to the view
I believe the answer here is that you probably want to flip your design. Assuming an MVVM style design, instead of having the Model know about the input sequence, it becomes agnostic. This means that you now have a model that has a InputRecieved/OnInput/ExecuteCommand method that the View will call with the input values. This should now be a lot easier for you to deal with a "Commands in one direction" and "Events in the other direction" pattern. A sort of tip-of-the-hat to CQRS here.
We use that style extensively on Views+Models in WPF/Silverlight/JS for the last 4 years.
Maybe something like this;
var model = function()
{
var self = this;
self.output = //Create observable sequence here
self.filter = function(input) {
//peform some command with input here
};
}
var viewModel = function (model) {
var self = this;
self.filterText = ko.observable('');
self.items = ko.observableArray();
self.filterText.subscribe(function(newFilterText) {
model.filter(newFilterText);
});
model.output.subscribe(item=>items.push(item));
};
update
Thanks for posting a full sample. It looks good. I like your new initScan operator, seems an obvious omission from Rx.
I took your code an restructured it the way I probably would have written it. I hope it help. The main things I did was encapsulted the logic into the model (flip, nearby etc) and have the view take the model as a parameter. Then I did also have to add some members to the model instead of it just being an observable sequence. This did however allow me to remove some extra logic from the view and put it in the model too (Hit logic)
//-- Helper methods and whatnot
// Same as Observable.prototype.scan, but it also yields the initial value immediately.
var initScan = function (values, init, updater) {
var initValue = Rx.Observable.return(init);
var restValues = values.scan(init, updater);
return initValue.concat(restValues);
};
//-- Part 1: From input to state --
var process = function () {
var self = this;
var shots = new Rx.Subject();
// Variables to easily represent the two states of the target
var left = 'left';
var right = 'right';
// Transition from one side to the other
var flip = function (side) {
if (side === left) {
return right;
} else {
return left;
}
};
// Determine new state based on current state and input
var update = function(current, input) {
// Input value ignored here because there's only one possible state transition
return flip(current);
};
// Creates a predicate used for hit testing in the view
var isNearby = function (target, radius) {
return function (position) {
var min = target - radius;
var max = target + radius;
return position >= min && position <= max;
};
};
self.shoot = function(input) {
shots.onNext(input);
};
self.positions = initScan(shots, left, update).map(function (state) {
return state === left ? 5 : 25;
});
self.hits = self.positions.flatMapLatest(function (target) {
return shots.filter(isNearby(target, 10));
});
};
//-- Part 2: From display to inputs --
var display = function (model) {
// Simulate clicks from the user at various positions (only one dimension, for simplicity)
var clicks = Rx.Observable.interval(800)
.map(function (v) {return (v * 5) % 30; })
.do(function (v) { console.log("Shooting at: " + v)})
.publish();
clicks.connect();
model.hits.subscribe(function(pos)=>{console.log("HIT! (# "+ pos +")");});
// Determine which clicks are hits based on displayed position
model.positions(function (target) {
return clicks
.subscribe(pos=>{
console.log("Shooting at " + pos + ")");
model.shoot(pos)
});
});
};
//-- Part 3: Putting the loop together
/**
* Creates the following feedback loop:
* - Commands are passed to the process function to generate updates.
* - Updates are passed to the display function to generates further commands.
* - (this closes the loop)
*/
var feedback = function (process, display) {
var model = process();
var view = display(model);
};
feedback(process, display);
I presume that because you do not "assign" the inputs after the model is created, you are aiming for a non-mutative approach to instantiating your model and view. However, your model and your view seem to depend on one another. To resolve this issue, you can use a third party to facilitate the relationship between the two objects. In this case, you can simply use a function for dependency injection...
var log = console.log.bind(console),
logError = console.log.bind(console, 'Error:'),
logCompleted = console.log.bind(console, 'Completed.'),
model(
function (updates) {
return view(updates);
}
)
.subscribe(
log,
logError,
logCompleted
);
By providing the model a factory to create a view, you give the model the ability to fully instantiate itself by instantiating it's view, but without knowing how the view is instantiated.
As per my comment on the question itself, here's the same sort of code you're writing done with a scheduler in Windows. I would expect a similar interface in RxJS.
var scheduler = new EventLoopScheduler();
var subscription = scheduler.Schedule(
new int[] { 1, 2, 3 },
TimeSpan.FromSeconds(1.0),
(xs, a) => a(
xs
.Do(x => Console.WriteLine(x))
.Select(x => x * 10)
.ToArray(),
TimeSpan.FromSeconds(1.0)));
The output I get, with three new numbers every second, is:
1
2
3
10
20
30
100
200
300
1000
2000
3000
10000
20000
30000

Dynamically Generated Telerik MVC3 Grid - Add Checkboxes

I have a grid that is dynamically generated based on search criteria. I render the grid in a partial view using Ajax. That all works fine.
I now need to add a checkbox column as the first column.
Also, how do I get filtering, sorting paging etc. to work now since it is in a partial view.
When i click on a header to sort I get a Page not found error and the filter Icon doesnt do anything.
And one more thing. When I try to add a GridCommandColumnSettings to the grid I get the error
"Invalid initializer member declarator"
Code is below for the gridcolumnsettings
public GridColumnSettings[] NewColumns(DataTable fullDT)
{
GridColumnSettings[] newColumns = new GridColumnSettings[fullDT.Columns.Count];
for (int i = 0; i < fullDT.Columns.Count; i++)
{
// set the visibility property for the DeliveryID
bool boolDeliveryID;
if (fullDT.Columns[i].ColumnName == "DeliveryID")
boolDeliveryID = false;
else
boolDeliveryID = true;
newColumns[i] = new GridColumnSettings
{
new GridCommandColumnSettings
{
Commands =
{
new GridEditActionCommand(),
new GridDeleteActionCommand()
},
Width = "200px",
Title = "Commands"
},
Member = fullDT.Columns[i].ColumnName,
Title = fullDT.Columns[i].ColumnName,
Visible = boolDeliveryID,
Filterable = true,
Sortable = true
};
}
return newColumns;
}
Any suggestions would be appreciated.
Thanks
I edited my post to add my partial for the Grid
Here is my partial for the grid
#(Html.Telerik().Grid<System.Data.DataRow>(Model.Data.Rows.Cast<System.Data.DataRow>())
.Name("Grid")
.Columns(columns =>
{
columns.LoadSettings(Model.Columns as IEnumerable<GridColumnSettings>);
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_DeliveryManagerCustomBinding", "Deliveries"))
.EnableCustomBinding(true)
.Resizable(resize => resize.Columns(true))
)
I don't add columns this way when I use the Telerik Grid control, but looking at what you're doing I would hazard a guess to say you will need to do something like the following:
increase the size of the newColumns array by 1 (because we're going to add in the checkbox column):
GridColumnSettings[] newColumns = new GridColumnSettings[fullDT.Columns.Count + 1];
if you want it at the beginning you will need to do the following before your for-loop:
GridColumnSettings s = new GridColumnSettings() {
ClientTemplate("<input type=\"checkbox\" name=\"checkeditems\" value=\"some value\" />")
Title("title goes in here")
};
Then you will add it into your array:
newColumns[0] = s;
and then increase the start index for your for-loop to 1:
for (int i = 1; i < fullDT.Columns.Count; i++)
the checkbox column will go at the beginning