I have a web page where the user creates simple drawings using various blocks, e.g. shapes representing furniture are drag and dropped onto a building floor plan. It uses Interact.js.
The blocks themselves can be dragged/moved, resized, added, inserted, deleted, merged, split, recoloured, font etc by the user - JavaScript acting on HTML and CSS.
I plan to save changes locally (for offline if needed) and back to the server for sharing with others who have access to this project. Undo/redo is nice to have too.
How to save modified diagrams (html & CSS)?
Option 1:
document.getElementById('foo').innerHTML for the HTML.
For CSS you'd have to recursively traverse the whole DOM and match selectors on each element to the rules defined in each CSS file.
As described in the answer above, this will (most of the times) work for classes:
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
(classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
}
}
But this is a bad, error-prone solution.
Option 2:
What you need to do is have a data model that you edit, think of JSON looking like this:
[
{type: 'circle', color: 'blue', x: 10, y: 15, children: [
{type: 'line', color: 'red', x: 100, y: 0, children: []}
]},
{type: 'square', color: 'greed', x: 100, y: 15, children: []}
]
Based on this you'd write a recursive function like this:
var foo = document.getElementById('foo'); // this is where you "draw" stuff
function draw(elements) {
var i;
for(i in elements) {
drawElement(elements[i]);
if(elements[i].children.length > 0) {
draw(elements[i].children);
}
}
}
function drawElement(element) {
var domElement = document.createElement("div");
domElement.className = 'element ' + element.type + ' ' + element.color;
domElement.style.left = element.x + 'px';
domElement.style.top = element.y + 'px';
foo.appendChild(domElement);
}
Now you need to define some CSS:
#foo {
position: relative;
}
#foo .element {
position: absolute;
}
#foo .element.square {
...
}
#foo .element.blue {
background-color: blue;
}
Next, the "interactive" part. Whenever your user adds something to the "canvas" instead of directly manipulating the DOM you only add stuff to that JSON tree and then delete the old DOM and run draw again.
You can go with option 1 but that will be a lot harder. Read the comments in the answer I attached, you'll see there are a lot of browser inconsistencies and limitations.
Option 3:
Working with a <canvas>, not the DOM is more manageable. Try looking into Fabric.js for example, it already handles "saving" and "initializing" from JSON and allows users to "draw" stuff to it.
With jQuery you can use .html() method to retrive inner html of your container. But for css I think you should manually examine all properties of all objects you want to save to get similar approach.
So, for both, if you can modify the code that handles drawing operations, I think the simplest way would be catalog all actions that user can do and store it in a variable that enable you to reproduce all the process another time.
For example:
[
["drawBox", 200, 200, 400, 400, "#ff0000", "#0000ff"],
...
]
This approach will be also useful if you want to impement undo/redo functionalities in the future.
You should store that 'state' in db.
you can use HTML5 SessionState to save rendered Page Content
also you can store that in local storage of browser and sync local storage with db.
Related
I am using blessed and I am trying to add a prompt to my application. It works fine, but I can't read its text. I have prepared a minimal example, that illustrates, what I see.
I would like to know how I can style the text in the inputs. The style-Attributes as mentioned in the docs seem to have no effect.
Here's what I see (there is text in the input and on the two buttons, but it is black on black).
Here's code that reproduces the error on Debian 9 with standard terminal and standard theme:
var blessed = require('blessed');
var screen = blessed.screen({});
var prompt = blessed.prompt({
left: 'center',
top: 'center',
height: 'shrink',
width: 'shrink',
border: 'line',
});
screen.append(prompt);
screen.key(['q', 'C-c'], function quit() {
return process.exit(0);
});
screen.render();
prompt.input('Search:', 'test', function() {});
Disclaimer: I'm not very familiar with the blessed codebase, so there might be a more native way of doing this. If there isn't, then it sounds like this feature should be requested / implemented.
Observation 1 - Your terminal's color settings are contributing to the problem
Based on the screenshot you gave, your terminal's default colors have a black foreground against a white background. If you invert this in your terminal settings, you should be able to see the expected behavior.
But! Your application should no matter what the user's settings are, so that isn't a good solution...
Observation 2 - The Prompt constructor hardcodes it's children with a black background
When in doubt, go to the source! Here is part of prompt.js as of 2017-09-30:
// ...
function Prompt(options) {
// ...
Box.call(this, options);
this._.input = new Textbox({
// ...
bg: 'black'
});
this._.okay = new Button({
// ...
bg: 'black',
hoverBg: 'blue',
});
this._.cancel = new Button({
// ...
bg: 'black',
hoverBg: 'blue',
});
}
// ...
So, it seems like the only way to fix your issue is to overwrite these children's style properties after the Prompt has been created.
Solution 1 - Overwrite child style properties after creation
After you create the prompt, you can overwrite the style of each child. It's probably most straightforward to just make the foreground white (as it should be)...
Also, for maintainability's sake, this hack really should be in it's own function.
function createBlessedPrompt(options) {
var prompt = blessed.prompt(options);
// NOTE - Not sure if blessed has some sortof `children()` selector.
// If not, we probably should create one.
// Nevertheless, temporarily hardcoding the children here...
//
var promptChildren = [prompt._.input, prompt._.okay, prompt._.cancel];
promptChildren.forEach(x => {
Object.assign(x.style, {
fg: 'white',
bg: 'black'
});
});
return prompt;
}
Solution 2 - Submit a bug fix to the blessed repository
This really seems like an issue with blessed itself. If you can think of a way that Prompt should properly handle this case, you should totally help your fellow coder and write an issue / pull request that fixes this.
Good luck!
I tried this sample on Win 10 and Ubuntu 16. The only change I made to your code is screen definition has been moved before the promt definition (without it I got 'No active screen' error), and also I added styles according to the documentation. My repro:
1) run npm install blessed inside an empty folder
2) create index.js in that folder with the following code
var blessed = require('blessed');
var screen = blessed.screen({});
var prompt = blessed.prompt({
left: 'center',
top: 'center',
height: 'shrink',
width: 'shrink',
border: 'line',
style: {
fg: 'blue',
bg: 'black',
bold: true,
border: {
fg: 'blue',
bg: 'red'
}
}
});
screen.append(prompt);
screen.key(['q', 'C-c'], function quit() {
return process.exit(0);
});
screen.render();
prompt.input('Search:', 'test', function() {});
3) run node index
4) got
Is that want you wanted?
I would like to add category icons to a Wordpress page, each icon animated with snap.svg.
I added the div and inside an svg in the loop that prints the page (index.php). All divs are appearing with the right size of the svg, but blank.
The svg has a class that is targeted by the js file.
The js file is loaded and works fine by itself, but the animation appears only in the first div of that class, printed on each other as many times it is counted by the loop (how many posts there are on the actual page from that category).
I added "each()" and the beginning of the js, but is not allocating the animations on their proper places. I also tried to add double "each()" for the svg location and adding the snap object to svg too, but that was not working either.
I tried to add unique id to each svg with the post-id, but i could not pass the id from inside the loop to the js file. I went through many possible solutions I found here and else, but none were adaptable, because my php and js is too poor.
If you know how should I solve this, please answer me. Thank you!
// This is the js code (a little trimmed, because the path is long with many randoms, but everything else is there):
jQuery(document).ready(function(){
jQuery(".d-icon").each(function() {
var dicon = Snap(".d-icon");
var dfirepath = dicon.path("M250 377 C"+ ......+ z").attr({ id: "dfirepath", class: "dfire", fill: "none", });
function animpath(){ dfirepath.animate({ 'd':"M250 377 C"+(Math.floor(Math.random() * 20 + 271))+ .....+ z" }, 200, mina.linear);};
function setIntervalX(callback, delay, repetitions, complete) { var x = 0; var intervalID = window.setInterval(function () { callback(); if (++x === repetitions) { window.clearInterval(intervalID); complete();} }, delay); }
var dman = dicon.path("m136 ..... 0z").attr({ id: "dman", class:"dman", fill: "#222", transform: "r70", });
var dslip = dicon.path("m307 ..... 0z").attr({ id: "dslip", class:"dslip", fill: "#196ff1", transform:"s0 0"});
var dani1 = function() { dslip.animate({ transform: "s1 1"}, 500, dani2); }
var dani2 = function() { dman.animate({ transform: 'r0 ' + dman.getBBox().cx + ' ' + dman.getBBox(0).cy, opacity:"1" }, 500, dani3 ); }
var dani3 = function() { dslip.animate({ transform: "s0 0"}, 300); dman.animate({ transform: "s0 0"}, 300, dani4); }
var dani4 = function() { dfirepath.animate({fill: "#d62a2a"}, 30, dani5); }
var dani5 = function() { setIntervalX(animpath, 200, 10, dani6); }
var dani6 = function() { dfirepath.animate({fill: "#fff"}, 30); dman.animate({ transform: "s1 1"}, 100); }
dani1(); }); });
I guess your error is here:
var dicon = Snap(".d-icon");
You are passing a query selector to the Snap constructor, this means Snap always tries to get the first DOM element with that class, hence why you're getting the animations at the wrong place.
You can either correct that in two ways:
Declare width and height inside the constructor, for example var dicon = Snap(800, 600);
Since you are using jQuery you can access to the current element inside .each() with the $(this) keyword. Since you are using jQuery instead of the dollar you could use jQuery(this).
Please keep in mind this is a jQuery object and probably Snap will require a DOM object. In jQuery you can access the dom object by appending a [0] after the this keyword. If var dicon = Snap( jQuery(this) ); does not work you can try with var dicon = Snap( jQuery(this)[0] );
Additionally, you have several .attr({id : '...', in your code. I assume you are trying to associate to the paths an ID which are not unique. These should be relatively safe since they sit inside a SVG element and I don't see you are using those ID for future selection.
But if you have to select those at a later time I would suggest to append to these a numerical value so you wont have colliding ID names.
I have worked with JointJS now for a while, managing to create elements with HTML in them.
However, I am stuck with another problem, is it possible to place HTML code, like
href, img etc, on a JointJS link and how do I do this?
For example, if I have this link, how do I modify it to contain HTML:
var link = new joint.dia.Link({
source: { id: sourceId },
target: { id: targetId },
attrs: {
'.connection': { 'stroke-width': 3, stroke: '#000000' }
}
});
Thank you!
JointJS doesn't have a direct support for HTML in links. However, it is possible to do with a little bit of JointJS trickery:
// Update position of our HTML whenever source/target or vertices of our link change:
link.on('change:source change:target change:vertices', function() { updateHTMLPosition(link, $html) });
// Update position of our HTML whenever a position of an element in the graph changes:
graph.on('change:position', function() { updateHTMLPosition(link, $html) });
var $html = $('<ul><li>one</li><li>two</li></ul>');
$html.css({ position: 'absolute' }).appendTo(paper.el);
// Function for updating position of our HTML list.
function updateHTMLPosition(link, $html) {
var linkView = paper.findViewByModel(link);
var connectionEl = linkView.$('.connection')[0];
var connectionLength = connectionEl.getTotalLength();
// Position our HTML to the middle of the link.
var position = connectionEl.getPointAtLength(connectionLength/2);
$html.css({ left: position.x, top: position.y });
}
Bit of an old question, but thought I'd add some more ideas. You can add extra svg markup to the label in a link if you like by extending the link object and then setting attributes where needed. For example:
joint.shapes.custom.Link = joint.dia.Link.extend({
labelMarkup: '<g class="label"><rect /><text /></g>'
});
This code overrides the markup for the label, so you can add extra elements in there. You can also update attributes on these elements by:
link.attr('text/text', "new text");
However hyperlinks won't work (at least I haven't got them working in Chrome) and I believe this is because Jointjs listens for all events in the model. So what you should do is use inbuilt events in Jointjs to listen for connection clicks:
paper.on('cell:pointerclick', function(cellView, evt, x, y){
console.log(cellView);
});
I'm trying to use the CHAP links library timeline (http://almende.github.io/chap-links-library/timeline.html).
Example17 is using JSON, but it's in the html file itself. I'd like to use an external JSON file sitting on the web server instead.
Here's my example.json:
{"timeline":[
{
"start":"2013,7,26",
"end":"2013,7,26",
"content": "Bleah1"
},
{
"start":"2013,7,26",
"end":"2013,8,2",
"content": "Bleah2"
},
{
"start":"2013,7,26",
"end":"2013,8,2",
"content": "Bleah3"
},
{
"start":"2013,7,26",
"end":"2013,8,2",
"content": "Bleah4"
}
]}
I added this:
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
And here's the modified function:
// Called when the Visualization API is loaded.
function drawVisualization() {
// Create a JSON data table
$.getJSON('example.json', function(jsondata) {
data = jsondata.timeline;
});
// specify options
var options = {
'width': '100%',
'height': '300px',
'editable': true, // enable dragging and editing events
'style': 'box'
};
// Instantiate our timeline object.
timeline = new links.Timeline(document.getElementById('mytimeline'));
function onRangeChanged(properties) {
document.getElementById('info').innerHTML += 'rangechanged ' +
properties.start + ' - ' + properties.end + '<br>';
}
// attach an event listener using the links events handler
links.events.addListener(timeline, 'rangechanged', onRangeChanged);
// Draw our timeline with the created data and options
timeline.draw(data, options);
}
Anyone who can tell me what I'm doing wrong gets a cookie! :-)
Update: I should specify that it's rendering the timeline div correctly, I'm just getting no data showing up.
Your start and end dates need to be parsed as Date objects for use in the timeline
I stumbled on this post as I was implementing similar functionality.
In version 2.6.1 of timeline.js, around line 3439 where the function links.Timeline.Item is declared, you'll notice a comment relating to implementing parseJSONDate.
/* TODO: use parseJSONDate as soon as it is tested and working (in two directions)
this.start = links.Timeline.parseJSONDate(data.start);
this.end = links.Timeline.parseJSONDate(data.end);
*/
I enabled the suggested code and it all works!* (go to the parseJSONDate function to see which formats are accepted)
*(works insofar as dates appear on the timeline.. I'm not using therefore not testing any selection/removal features, images, or anything like that..)
I'm using the Raphaël Javascript lib (awesome stuff for SVG rendering, by the way) and am currently trying to update the source of an image as the mouse goes over it.
The thing is I can't find anything about it (it's probably not even possible, considering I've read a huge part of the Raphaël's source without finding anything related to that).
Does someone knows a way to do this ?
Maybe it can be done without directly using the Raphaël's API, but as the generated DOM elements doesn't have IDs I don't know how to manually change their properties.
I'm actually doing CoffeeScript, but it's really easy to understand. CoffeeScript is Javascript after all.
This is what I'm doing right know, and I would like the MouseOver and MouseOut methods to change the source of the "bg" attribute.
class Avatar
constructor: (father, pic, posx, posy) ->
#bg = father.container.image "pics/avatar-bg.png", posx, posy, 112, 112
#avatar = father.container.image pic, posx + 10, posy + 10, 92, 92
mouseOver = => #MouseOver()
mouseOut = => #MouseOut()
#bg.mouseover mouseOver
#bg.mouseout mouseOut
MouseOver: ->
#bg.src = "pics/avatar-bg-hovered.png"
alert "Hover"
MouseOut: ->
#bg.src = "pics/avatar-bg.png"
alert "Unhovered"
class Slider
constructor: ->
#container = Raphael "raphael", 320, 200
#sliderTab = new Array()
AddAvatar: (pic) ->
#sliderTab.push new Avatar this, pic, 10, 10
window.onload = ->
avatar = new Slider()
avatar.AddAvatar "pics/daAvatar.png"
This actually works, except for the "#bg.src" part : I wrote it knowing that it wouldn't work, but well...
var paper = Raphael("placeholder", 800, 600);
var c = paper.image("apple.png", 100, 100, 600, 400);
c.node.href.baseVal = "cherry.png"
I hope, you get the idea.
This works for me (and across all browsers):
targetImg.attr({src: "http://newlocation/image.png"})
I was using rmflow's answer until I started testing in IE8 and below which returned undefined for image.node.href.baseVal. IE8 and below did see image.node.src though so I wrote functions getImgSrc, setImgSrc so I can target all browsers.
function getImgSrc(targetImg) {
if (targetImg.node.src) {
return targetImg.node.src;
} else {
return targetImg.node.href.baseVal;
}
}
function setImgSrc(targetImg, newSrc) {
if (targetImg.node.src) {
targetImg.node.src = newSrc;
} else {
targetImg.node.href.baseVal = newSrc;
}
}