Javascript - Access object from memory-cache - javascript

I'm working on an app for image editing. Each time an edit is made, the new version shows up in the network tab as a png.
I'm trying to add an "undo" feature which, to me, would mean using the previous version of the image.
So if the current version is the last image, I want the undo function to load the second to last. Is this possible?
I've been searching for ways to do this but haven't really seen anything that suggests it is.
Any advice would be much appreciated.
Thanks!
Update
I've been looking into this:
https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/keys

So if the current version is the last image, I want the undo function to load the second to last. Is this possible?
Yes in general this is possible. That said the current approach isn't something I'd recommend doing as cache is persistence storage. You could store every edit as a base64 string and then when you want to undo call array.pop() and render the last element in that array. But this will quickly run into a problem that we could be storing a lot of long base64 strings as storage in the users web browser.
Instead there is a better way to do this is have a single baseImage and anything the users does instead keep track of the operations they did, and then simply do this in memory. Let's take an example such as Paint:
We could define this as a blank white baseImage. Followed by an array of three operations: operations = [DrawRect, DrawLine, DrawCircle] each of these could be thought of as an object that knows how to draw itself base on some points. An undo here would remove DrawCircle from the end then starting with the blank white image perform the [DrawRect, DrawLine] operations we saved in the array to end up with:
Some operations can be costly and eventually add up. We don't want to be starting from scratch and performing hundreds or thousands of operations the user did every time we undo. This is why many editors only have a set number of undo's you can do. What's happening here is we are changing our baseImage with our pervious operations and starting from there instead.
This can be considered a sort of buffer that we only hold so many operations. A simple way would be after say 20 operations when an undo is performed have it draw the first item and save that as the new baseImage. Although now this would be happening every operations after we pass 20. If the process for changing baseImage is an expensive one this could be staggered to say every 10 operations we remove the first 10 and save the image on the 10th operation instead. That way it makes it so we have at least 10 undo's available and we are also only changing baseImage every 10th operation.
I do want to point out for the most part this is me thinking out loud as I don't have any vast development experience in creating image editing or drawing software. Rather this is just an approach/concepts I'd take if I where to make one. Hopefully these points can help you make an undo feature that isn't too space/memory or computationally expensive.

Related

How could I improve performance when repeatedly updating an SVG DOM in React JS?

Last year I tried to learn a bit React JS for making the project you can find here. I apologize for my rather vague / imprecise description below, but I'm by no means versed in this.
Basically, there is a single <svg> tag, which will contain a number of paths etc. as created by the user. The problem I have is that things become very slow the more paths are present. To my current understanding, this is due to the fact that the entire SVG DOM gets updated repeatedly upon user interactions that involve dragging the mouse or using the mouse wheel.
This holds true, particularly, for two user interactions:
a) Panning - all paths are being moved at the same time; I think one might circumvent this issue by taking a snapshot image first and moving that around instead. However, that's not a solution for the other user interaction, which is:
b) Expanding/collapsing paths - here, all paths are being modified in terms of coordinates of some of their points. That is, every path must be modified in a different way, but all of them must be modified at once, and this must happen repeatedly because it's a user interaction controlled with the mouse wheel where changes happen gradually and the user requires immediate visual feedback on these changes as they happen.
Particularly for b), I see no alternative that would involve a single transformation or something.
After extensive research last year, I came to the conclusion that choosing SVG to display and modify a lot of things dynamically on screen was a wrong decision in the first place, but I realized too late, so I gave up and have never touched it since. I'm pretty certain that there isn't any way to deal with the low performance that builds upon what I already have; I have no intention to start this project from scratch with a completely different approach. Also, the reason why I chose SVG was that it's easy to manipulate.
In summary, I'd basically like to get confirmation that there is no feasible way to rescue this project.

How games delete an object in the database but animate it out at the same time

I am wondering about how async actions like animations work when you do actions like delete an item, and so came up with this sort of thought process and would like feedback to see if it makes sense from an industry best practice perspective.
There are two layers:
The reactive layer.
The rendering layer.
The reactive layer occurs instantly and can be done with traditional event dispatching.
This is where you create and delete data and it all happens instantaneously.
The state machine gets notified of these instant reactive changes.
Then the state machine "transitions". This process occurs over a period of time, assuming there are some async things that occur (animations, network requests, etc.). This is what people mean when they say "action queue".
Then the rendering layer pics up stuff off the action queue and renders it. This way there is sort of a delayed reaction to the underlying instant reactive layer.
My question is if the reactive layer needs to handle async as well. For example, deleting something.
Say an item is deleted, and you want to animate it out. There are a few ways to do this:
Queue up a delete action, then animate it out first. When animation is complete, then do the actual delete. If animation is interrupted (cancel the delete), then the delete is never performed.
Delete the item instantly (reactive layer). The animation layer keeps a reference to the item around, so can still do its animation even though from the global place it is deleted. If the animation is cancelled, then you would have to do an "undo" sort of thing which is more complex.
If (1) is the way to go, then there is no reactive layer, and everything is implemented with a sort of action queue in mind. This makes it harder to make reusable code because everything is tied to the action-queue idea.
If (2) is the way to go, then there are two copies of the data, the global copy, and the local copy, which is kept in sync asynchronously. This makes it easier to have reusable code but makes it more complicated to reason about.
Wondering if any of this makes sense, and if any of these approaches is better practice in the industry (or if there is an alternative I didn't address that makes more sense).
Put another way, there are two main ways to do it:
Eager: Delete it now, okay everyone we've deleted it, time to come back inside. And wait for everything to trinkle back in to call it "done".
Cautious: Announce "we are going to delete it", then wait til everything is done and comes back inside to actually do the delete.
Wondering how games and apps and such handle this sort of thing.
Update
After thinking about it a different way, maybe it would be more like the swaying of kelp in the ocean:
https://www.youtube.com/watch?v=gIeLCzR8EgA
By that I mean, there is a base layer that is immediate (does the create/delete), then there are some intermediate layers with copies of all the transactions that occurred (create/delete), that the rendering layer uses to animate create/delete. So the original data is always in sync, but the rendering layer uses a sort of older version of the data with a chain of all the changes taking place.
reactive layer -> transaction layer -> rendering layer.
Another option is flagging as delete, then only after animations are complete actually do the delete, but that seems hacky.
Update
Another version:
Reactive version
Always has the latest data. (a)
Rendering version
Has the last data (b), plus a chain of changes leading to (a).
As rendering completes, it applies the changes to (b), so eventually it is like (a).
from my experiece as Unity Game Developer the right decision is in the middle, as for the physics in game engine are approximated because the sensation of a things semi-perfect is pretty like a perfect one.
The explanation is because the more realistic and real-life like is your goal the more you need resources, not only CPU and GPU but cash too.
after this strange preamble I quote for the flag options, the method applicated is not much different than a normal Garbade Collector, you mark a no more usefull item and when the Garbage collector come he free the ram space used by this object, so this new space can be reused.
The same process is done by a lot of engine, and the destroy operation appens before the rendering calculations.
The final goal is always to reach a good in-between solution.
There is the possibility to force the instant destruction in every moment of the engine computation process, but this solution is always deprecated.
With the animation the way u typically use is to Destroy (setting flag to be destructed) at the end of the animation or in the last few frames.
At least you can use some tricks to make the fade more enjoyable (like particles).
The real problem is when you have to destroy object over the net (multiplayer games), in this case you have to establish what is the more attendible machine and pick that to calculate physics and interaction, this machine is always the server or the at least the host(depending on the game type).
I know that the question was marked as javascript question, but i couldn't resist to answer.
I enclose also a page from the unity documentation about the Destruct function were explain how they menage to remove item from a game enviroment:
https://docs.unity3d.com/ScriptReference/Object.Destroy.html
Have a nice day! and good coding.

Huge Data in Listbox(Table)

I want to show a listbox(Table) with nearly 20 Million rows.
How can I do so, with lower memory usage and not letting my server die(stop responding) while doing so.
Even you have any Theoretical idea please do share(I will try to implement).
Need solution very urgently.
I know I cannot load all the rows at once. I need to ask new rows from server every time I scroll. I have tried it but my scroll is not smooth enough.
Thanks & Regards,
Aman
Why not just retrieve the first 100 entries and then once the client scrolls to the bottom you append another 100 entries and so on.
Maybe you could wait for ZK's new feature.
Reference
http://books.zkoss.org/wiki/Small_Talks/2012/March/Handling_a_Trillion_Data_Using_ZK
You could use http://books.zkoss.org/wiki/ZK Developer's Reference/MVC/View/Renderer/Listbox Renderer.
public void render(Listitem listitem, Object data, int index)
To start, you can implement render in way so that you get element to render from datasource at hand by index from render method. You can use standard cache (if Hibernate is in place) or custom-written one if otherwise (look also at EhCache).
#Erik solution is really fast to implement. To add you could make a button, so that user would be aware that loading more records would cost some time and would think if one really needs to load more. Scrolling can make you Listbox just hang up for a moment.
And always make an upper constraint on maximal number of records you will show at one time - don't pollute your server's memory.
Make paging for the table values and retrieve specific number of records on demand.
Use can use dataTable pluging to make pagination for data records.
Notice that you can retrieve data in synchronous and asynchronous way using this library

How would I go about recording changes in a large text field?

Let's say I want a user to write a story in 20 minutes. After the user is done I want to play back the story writing process so I can see how the user went about doing it. How would I do this? I don't want to watch every second of it, obviously, but I'd like to see a snapshot of whenever a "large change" was made. The "large change" should be defined by me. It could be X amount of character additions or subtractions.
I thought of somehow trying to continuously monitor the textbox for changes and then store the text as a string in an array every time there is a "large change". Then to replay this, I will play the string array with a 1 second delay.
Anyone think of a better way to do this or know a library that would help?
Thanks!
Let's take for granted that you have the capacity to persist this state and just look at the challenge of detecting and displaying the diffs. The most challenging aspect of you problem is going to be defining and subsequently detecting what you call a "large change". If we set that aside for a moment I think there are two ways you can go about this:
1) Operational transform - (http://en.wikipedia.org/wiki/Operational_transformation)
This is what Google Docs(etherpad) uses to synchronize real-time collaborative edits across multiple browsers. With OT you can practically recreate a video of the changes made to a document. You can see this in action on thinklinkr.com revision history (full disclosure - I am one of the founders).
2) Diff-match-path - (http://code.google.com/p/google-diff-match-patch/)
This is actually a set of three algorithms that can be used to effeciently create and resolve differences between text documents. I think this might be a better match for you given your requirement about chunking diffs.

What kind of algorithm does an HTML SELECT element uses to show results as you type?

I'm trying to replicate an HTML SELECT element (drop-down-list or combobox) in Flash (AS3).
In most browsers, when you have one in focus and you type something, the combobox will try to find the value within its options and show the closest one. I was wondering what kind of algorithm is used for that.
I don't think its Levenshtein or similar since it only works with the beginning of the string.
I'm thinking that it works by keeping a buffer of what has been written, and tries to find a string starting with that... if it doesn't find anything, it clears the buffer, and searches a string beginning with the last character pressed.
I already prototyped this, and it works quite ok, with one caveat... In HTML, when you repeatedly press the same key, it will rotate between all options starting with that character. I think I could fix this, but was wondering if someone has already done it, to compare the algorithms... its turning into quite a complex code to test and debug, and I'm not sure I'm covering all the possibilities...
The reaction of form widgets to keyboard interaction is not standardised and different browsers don't agree. This is always an issue when creating ersatz form controls from script.
In HTML, when you repeatedly press the same key, it will rotate between all options starting with that character.
This feature comes from Windows and is quite unintuitive. The exact rule isn't that exactly, is quite obscure, and gives different results in IE and Opera versus the other browsers.
IMO this behaviour is highly undesirable. Since no average user is going to be able to predict how the rule works, I personally would leave it out and simply select the first option to match the typed leftstring. This is easier for you to code and easier for the user to understand.
Just did some tests on firefox, and I noticed (this is not official information, just pure speculation):
Key pressed event:
Esc (firefox only): clear buffer
Arrow up/down: move up/down on the list, clear buffer
Page up/down: move up/down by 20 on the list, clear buffer
Home: move to the top of the list, clear buffer
End: move to the end of the list, clear buffer
Other:
Empty buffer?
Yes: add key to buffer
buffer.length == 1 AND key is same as last key pressed?
Yes: go on next item starting with key.
No: add key to buffer and search next item starting with buffer.
1.5 seconds passed event: clear buffer
This will need a timer of course.
I don't know what algorithm is used in the browsers but one that comes to mind that would do what you want is sequence alignment or a longest common subsequence algorithm. It would allow you to match any part of the string to any other part of the string (with possible gaps between the matched sub strings). It's not massively quick though.
http://en.wikipedia.org/wiki/Sequence_alignment
there's also some very good lecture videos online at MIT open course ware
http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/VideoLectures/detail/embed15.htm
In HTML, when you repeatedly press the same key, it will rotate between all options starting with that character. I think I could fix this, but was wondering if someone has already done it, to compare the algorithms
You might want to reset to the top of the dropdown after every key press and then search for the appended buffer.

Categories

Resources