Tag Archives: HTML5

B4X: ABMaterial 3.03 Public/3.20 Donators released

A lot of internal changes were made in the ABMaterial 3.20 ‘Chipmunk’ release.  For example, ABMContainer has been rewritten from the ground-up, but with minimal impact to your existing projects.  It allows adding them as array components, and has much shorter ID tags in the generated HTML.

Mindful and Stanmiller had another go on the cache issues.  They came up with a very nice solution (I had tears in my eyes) and both have done extensive testing on this subject. A big thanks again!  ABM 3.20 is backwards compatible with the previous 3.0.3 Cache System, but I would advice you to make the changes whenever you have the chance.

A nice new feature for mobile devices is the New Debug feature using a modified version of Conzole!

New Debug at work:

Using this new feature is very simple in B4J:

First, you have to enable the console in BuildPage():

' params are: open on load, width
page.DebugConsoleEnable(True, 300)

Two methods can be used to show or hide the console programmaticaly. Can be handy as a buid-in tool in your apps where the user enters a code on his device and you can then check the console.

page.DebugConsoleShow
page.DebugConsoleHide

Now you can start doing some cool stuff 🙂 Some examples:

Show some text, or a server value (note: strings must be between single quotes!)

page.DebugConsoleLog("'Server click at: " & DateTime.Time(DateTime.Now) & "'") ' shows the text

Now I generated an error on purpose, so the demo can show it catches the error:

page.DebugConsoleLog("'value: ' + $('#pi002-r2c1').html();") ' generates an error, the ; at the end is wrong

Same code, but with the correct javascript syntax, showing the html() value of the tag:

page.DebugConsoleLog("'value: ' + $('#pi002-r2c1').html()") ' generates the html value of the pi002-r2c1 tag

It works also on the desktop, although you probably will use the Chrome console as you can do more.

But there is more. You can also redirect all browser console message directly into the B4J log window!  You can use the following commands anywhere in your own code to start/stop receiving the browser console messages.

page.DebugConsoleB4JStart
page.DebugConsoleB4JStop

This is a very powerful feature if you develop Webapps for mobile devices.  It can be done otherwise, but it is a pain in the a$$ to set it up. Now, you can easily debug it on your iPhone, iPad, Android or any other device.

ABMaterial 3.20 has over 20 new features and bug fixes.  Following the same philosophy as B4X, the quick release cycle has proven to work very well for ABMaterial and its many users.  Donators will receive their download mail shortly.  The public version 3.03 can be downloaded from this blog too.

I’m also glad that with these releases, now everyone can work with ‘Chipmunk‘, and this does also mean the development cycle for ‘Butterfly‘  has ended.

I would like to take this opportunity to thank everyone for the support, hourless testing and inventive ideas you came up with in the last few years. You’ve made ABMaterial one hell of a WebApp Development Tool!

ThankYou

But we are not at the end! Far from it as I already have big ideas for the next releases.

Until then, happy programming!

Alwaysbusy

Click here to Donation and support ABMaterial


B4J: ABMaterial Facebook-like timeline in less than 200 lines!

ABMFacebook50

I recently had a question if it was possible to create a Facebook-like WebApp with ABMaterial for B4J. I had some time to spare tonight (yeah right):rolleyes: and decided to give it a go…

All I needed were a couple of ABMContainers and the new CloseContent/OpenContent feature introduced in 3.02. The existing NextContent system would provide the infinite page.

It also uses a ABMCustomComponent for the ‘Like’ feature (I based it on this project), and you can find the source code of the class under the video:

About an hour, and 200 lines of B4J code later, I had a working timeline!  A real project would of course need some way to add an article, save them in the database, user management, etc but this is out of scope of this article.

Note: This example will be included in the upcoming 3.02 Maintenance Update, but I would like to share the source source code for the ‘Like’ functionality beforehand.

Source code for the ‘Like’ custom component.
You’ll need this zip file for the images and js/css files. Put the images and css in the /www/css/custom folder, the js file in the /www/js/custom/ folder.

The class LikeComponent:

'Class module
Sub Class_Globals
   Public ABMComp As ABMCustomComponent
   Public Counter As Int
End Sub

'Initializes the object. Countries and data are Json Strings
Public Sub Initialize(InternalPage As ABMPage, ID As String, AlreadyLiked As Int)
   ABMComp.Initialize("ABMComp", Me, InternalPage, ID)
   Counter = AlreadyLiked
End Sub

Sub ABMComp_Build(internalID As String) As String
   Return $"
<div id="${internalID} class="facebook-reaction"><!-- container div for reaction system -->
        <span class="like-btn"> <!-- Default like button -->
          <span class="like-btn-emo like-btn-default"></span> <!-- Default like button emotion-->
           <span class="like-btn-text">Like</span> <!-- Default like button text,(Like, wow, sad..) default:Like  -->
<ul class="reactions-box"> <!-- Reaction buttons container-->
	<li class="reaction reaction-like" data-reaction="Like"></li>
	<li class="reaction reaction-love" data-reaction="Love"></li>
	<li class="reaction reaction-haha" data-reaction="HaHa"></li>
	<li class="reaction reaction-wow" data-reaction="Wow"></li>
	<li class="reaction reaction-sad" data-reaction="Sad"></li>
	<li class="reaction reaction-angry" data-reaction="Angry"></li>
</ul>
</span>
<div class="like-stat"> <!-- Like statistic container-->
           <span class="like-emo"> <!-- like emotions container -->
             <span class="like-btn-like"></span> <!-- given emotions like, wow, sad (default:Like) -->
           </span>
           <span class="like-details">${Counter} others</span></div>
</div>
"$
End Sub

Sub ABMComp_FirstRun(InternalPage As ABMPage, internalID As String)
   Dim script As String = $"$("#${internalID} .reaction").on("click",function(){  // like click
     var data_reaction = $(this).attr("data-reaction");
     $("#${internalID} .like-details").html("You and ${Counter} others");
     $("#${internalID} .like-btn-emo").removeClass().addClass('like-btn-emo').addClass('like-btn-'+data_reaction.toLowerCase());
     $("#${internalID} .like-btn-text").text(data_reaction).removeClass().addClass('like-btn-text').addClass('like-btn-text-'+data_reaction.toLowerCase()).addClass("active");;

     if(data_reaction == "Like") {
         $("#${internalID} .like-emo").html('<span class="like-btn-like"></span>');
     } else {
         $("#${internalID} .like-emo").html('<span class="like-btn-like"></span><span class="like-btn-'+data_reaction.toLowerCase()+'"></span>');
     }
     var json = {'target': '${internalID}', 'like': data_reaction};
     b4j_raiseEvent('likecomponent_liked', json);
     });    

     $("#${internalID} .like-btn-text").on("click",function(){ // undo like click
     if($(this).hasClass("active")){
       $("#${internalID} .like-btn-text").text("Like").removeClass().addClass('like-btn-text');
       $("#${internalID} .like-btn-emo").removeClass().addClass('like-btn-emo').addClass("like-btn-default");
       $("#${internalID} .like-emo").html('<span class="like-btn-like"></span>');
       $("#${internalID} .like-details").html("${Counter} others");
       var json = {'target':'${internalID}'};
         b4j_raiseEvent('likecomponent_unliked', json);
       }
     })"$

   InternalPage.ws.Eval(script, Array As Object(ABMComp.ID))
   ' flush not needed, it's done in the refresh method in the lib
End Sub

Sub ABMComp_Refresh(InternalPage As ABMPage, internalID As String)

End Sub

' do the stuff needed when the object is removed
Sub ABMComp_CleanUp(InternalPage As ABMPage, internalID As String)

End Sub

Usage:

Sub Class_Globals
   ...
   Dim myLike As LikeComponent
   ...
End Sub

' adding the component
myLike.initialize(page, ID & "Like", Rnd(20, 500))
myContainer.Cell(4,1).AddComponent(myLike.ABMComp)

Events (the name LikeComponent is set in the FirstRun() method of the class:

public Sub LikeComponent_Liked(value As Map)
   Log(value.Get("like") & " ----> " & value.Get("target"))
End Sub

public Sub LikeComponent_UnLiked(value As Map)
   Log("Unliked ----> " & value.Get("target"))
End Sub

Et voila,  a nice little demonstration of what you can make using B4J and ABMaterial.

I’ll end with a little word of advice:

If you only plan to learn one programming language this year, B4X is definitely the one you should pick!  With ABMaterial, I give you the power to write responsive, professional WebApps, and with the other B4X tools you write native Android, iOS, Desktop (Mac, Windows, Linux), Raspberry Pi and Arduino apps.  All with the same language!  You’ll wonder why you ever bothered looking at all those other pricy programming tools out there…

Happy programming!

Alwaysbusy

Click here to Donation and get the latest ABMaterial first!


B4J: Msgbox and Inputbox in ABMaterial 2.51

upload_2017-2-12_12-0-6Sometimes you just need to show a quick Msgbox or a single-field Inputbox to the user. In ABMaterial for B4J you have probably, just like me, already made a couple of modal sheets to do this.

But in 2.51 I’ve integrated the possibility for such cases just to do it in one line of code (like a normal msgbox/inputbox).

It replaces the default looking ‘alert’ box from JavaScript to a more modern looking box.  The SweetAlert2 library, which is build on the orginal SweetAlert one, has been extended for ABMaterial so you can ‘Theme’ about anything you want.

For example, to show the msgbox you see on top of this article, this is the code you need to write:

page.Msgbox("MSGBOX1", "This is a very simple msgbox", "Msgbox()", "OK", "")

Some more examples:

theme.AddMsgBoxTheme("image")
theme.MsgBox("image").ConfirmButtonColor = ABM.COLOR_GREEN
theme.MsgBox("image").CancelButtonColor = ABM.COLOR_RED
theme.MsgBox("image").SetImage("https://unsplash.it/400/200", 400, 200)
theme.MsgBox("image").BackColor = ABM.COLOR_BLUEGREY
theme.MsgBox("image").BackColorIntensity = ABM.INTENSITY_LIGHTEN5

page.Msgbox2("MSGBOX3", "This is an msgbox with an image using a {C:#00AA00}theme{/C}!", "Msgbox2() 2", "OK","CANCEL",True, ABM.MSGBOX_TYPE_WARNING, "image")

upload_2017-2-12_12-2-24

page.InputBox("INPUTBOX1", "This is an inputbox for text.","OK", "CANCEL", True, ABM.INPUTBOX_TYPE_QUESTION, ABM.INPUTBOX_QUESTIONTYPE_TEXT,"","Type some text...", "", "Please enter something!", "")

upload_2017-2-12_12-3-30

page.InputBox("INPUTBOX3", "This is an inputbox for a password.","OK", "CANCEL", True, ABM.INPUTBOX_TYPE_QUESTION, ABM.INPUTBOX_QUESTIONTYPE_PASSWORD,"","Type your password...", "", "Please enter a password", "")

upload_2017-2-12_12-3-43

page.InputBox("INPUTBOX6", "This is an inputbox with a radio selection.","OK", "CANCEL", True, ABM.INPUTBOX_TYPE_QUESTION, ABM.INPUTBOX_QUESTIONTYPE_RADIO,"#00ff00", "","{'#ff0000': 'Red','#00ff00': 'Green','#0000ff': 'Blue'}", "You must select a color", "")

upload_2017-2-12_12-4-43

page.InputBox("INPUTBOX7", "This is an inputbox with a checkbox.","OK", "CANCEL", True, ABM.INPUTBOX_TYPE_QUESTION, ABM.INPUTBOX_QUESTIONTYPE_CHECKBOX,"", "I agree with the terms and conditions","", "Please agree with the conditions", "")

upload_2017-2-12_12-5-51

Events:

Sub page_MsgboxResult(returnName As String, result As String)
   myToastId = myToastId + 1
   page.ShowToast("toast" & myToastId, "toastgreen", returnName & " " & result, 5000)
End Sub

Sub page_InputboxResult(returnName As String, result As String)
   myToastId = myToastId + 1
   page.ShowToast("toast" & myToastId, "toastred", returnName & " " & result, 5000)
End Sub

ABMaterial Mainenance Release 2.51 will be available for the donators in the following days.

Alwaysbusy

Click here to Donation and get the latest ABMaterial first!


B4J: Custom component ABMGridTable (Team Project)

One of the most asked for components in ABMaterial is an editable Grid.  We already have ABMTable and ABMTableMutable, but they have their limitations when it comes to being editable. So, as this kind of object is huge, I suggest we make it a Team Effort to build one.

I did have a look around and found a nice one jsGrid which is feature rich, easy to use and fits rather well with the ABMaterial look and feel.

I already did the first part: modified the default CSS so it works with ABMaterial (checkboxes and combos did not work), created a basic class template and a sample on how to use it in a webapp.

Copy the CSS and JS files from the zip the css/custom/ and /js/custom/ folders of the ABMaterial www folder.
Start with localhost:51042/GridDemo

My current result looks like this (allows adding, deleting, changing, sorting and filtering):

upload_2017-2-6_12-34-40

Creating even such a complex component is very easy in B4J with ABMaterial.  Lets dive into some code:

The ABMTableGrid class

'Class module
Sub Class_Globals
	Public ABMComp As ABMCustomComponent
	Private cmbCountries As String
	Private DBdata As String
End Sub

'Initializes the object. Countries and data are Json Strings
Public Sub Initialize(InternalPage As ABMPage, ID As String, Countries As String, data As String)
	ABMComp.Initialize("ABMComp", Me, InternalPage, ID)
	cmbCountries = Countries
	DBdata = data
End Sub

Sub ABMComp_Build(internalID As String) As String
	Return $"
<div id="${internalID}"></div>
<script>var _${internalID};</script>"$
End Sub

Sub ABMComp_FirstRun(InternalPage As ABMPage, internalID As String)
	Dim script As String = $"_${internalID} = $("#${internalID}").jsGrid({
		height: "100%",
		width: "100%",
		filtering: true,
		inserting: true,
		editing: true,
		sorting: true,
		paging: true,
		autoload: true,
		pageSize: 10,
		pageButtonCount: 5,
		deleteConfirm: "Do you really want to delete the client?",
		controller: {
			loadData: function(filter) {
				return $.grep(${DBdata}, function(client) {
					var fName = filter.Name.toUpperCase();
					var fAddress = filter.Address.toUpperCase();
					return (!filter.Name || client.Name.toUpperCase().indexOf(fName) > -1)
						&& (!filter.Age || client.Age === filter.Age)
						&& (!filter.Address || client.Address.toUpperCase().indexOf(fAddress) > -1)
						&& (!filter.Country || client.Country === filter.Country)
						&& (filter.Married === undefined || client.Married === filter.Married);
					});
			},
			insertItem: function(insertingClient) {
				var json = JSON.stringify(insertingClient);
				b4j_raiseEvent('${ABMComp.ID}_inserted', {'value':json});
			},
			updateItem: function(updatingClient) {
				var json = JSON.stringify(updatingClient);
				b4j_raiseEvent('${ABMComp.ID}_updated', {'value':json});
			},
			deleteItem: function(deletingClient) {
				var json = JSON.stringify(deletingClient);
				b4j_raiseEvent('${ABMComp.ID}_deleted', {'value':json});
			}
		},
		fields: [
			{ name: "Name", type: "text", width: 150 },
			{ name: "Age", type: "number", width: 50 },
			{ name: "Address", type: "text", width: 200 },
			{ name: "Country", type: "select", items: ${cmbCountries}, valueField: "Id", textField: "Name" },
			{ name: "Married", type: "checkbox", title: "Is Married", sorting: false},
			{ type: "control" }
		]
	});"$

	InternalPage.ws.Eval(script, Array As Object(ABMComp.ID))
	' flush not needed, it's done in the refresh method in the lib
End Sub

public Sub SetDBData(data As String)
	DBdata = data
End Sub

Sub ABMComp_Refresh(InternalPage As ABMPage, internalID As String)
	Dim script As String = $"$("#${internalID}").jsGrid("refresh");"$
	InternalPage.ws.Eval(script, Null)
End Sub

Usage in a WebApp:

Sub Class_Globals
	...
	Dim myTableGrid As ABMTableGrid
	' fake database for demo purposes
	Dim database As Map
End Sub

' make sure you copied the files from the .zip in the right folders
public Sub BuildPage()
	...
	page.AddExtraCSSFile("custom/jsgrid.min.css")
	page.AddExtraCSSFile("custom/jsgrid-theme.min.css")
	page.AddExtraJavaScriptFile("custom/jsgrid.min.js")
	...
End Sub

public Sub ConnectPage()
	...
	' as for the demo, we fake a real database here
	LoadFakeData

	page.Cell(2,1).SetFixedHeight(500)

	' for our combo, we add a Json string counting the countries
	myTableGrid.Initialize(page, "myTableGrid", $"[
		{ Name: "", Id: 0 },
		{ Name: "United States", Id: 1 },
		{ Name: "Canada", Id: 2 },
		{ Name: "United Kingdom", Id: 3 },
		{ Name: "France", Id: 4 },
		{ Name: "Brazil", Id: 5 },
		{ Name: "China", Id: 6 },
		{ Name: "Russia", Id: 7 }
	]"$, LoadData)
    page.Cell(2,1).AddComponent(myTableGrid.ABMComp)
	...
End Sub

Sub LoadData() As String
	' we have to return a Json string
	Dim data As StringBuilder
	data.Initialize
	data.Append("[")
	For i = 0 To database.size - 1
		If i > 0 Then
			data.Append(",")
		End If
		data.Append(database.get(i))
	Next
	data.Append("]")
	Return data.ToString
End Sub

Sub myTableGrid_Inserted(value As Map)
	log(value.get("ID")
End Sub

Sub myTableGrid_Updated(value As Map)
	log(value.get("ID")
End Sub

Sub myTableGrid_Deleted(value As Map)
	log(value.get("ID")
End Sub

Sub LoadFakeData()
	database.Initialize
	database.Put(0,$"{"ID": 0,"Name": "Otto Clay","Age": 61,"Country": 6,"Address": "Ap #897-1459 Quam Avenue","Married": false}"$)
	database.Put(1,$"{"ID": 1,"Name": "Connor Johnston","Age": 73,"Country": 7,"Address": "Ap #370-4647 Dis Av.","Married": false}"$)
	...
End Sub

As you can see, adding this rather complex component took me about 10 minutes to make, literally the time to put on a pot of Java. (pun intended!)

So this is were you guys can come in!

Some suggestions:
1. Adapt my class so the fields are generic (maybe by passing a Map with field definitions in initialize and then ‘build’ the correct JavaScript string in FirstRun?).
2. I only have set some basic parameters (like sorting, filtering etc), but this component has a lot more to offer. They can become properties of the class. See the jsGrid link at the top of this article.

Download the full source code and share your changes in this B4J Forum topic, so everyone can benefit from your creation.

Alwaysbusy

Click here to Donation if you like my work


B4J: ABMaterial 2.20 Public/2.50 Donators released

abmaterial250

This is just an announcement for the new version(s) of ABMaterial for B4J! It has been a while since I’ve been able to release a new free (public) version, but it is worth the wait!

As the donators already know, 2.20 was a major release, as it tackled a whole new reconnecting system.  If you’re using the free version (pre 2.00), make sure you read the included documents to see how you need to upgrade to the new version!

It was also the first version that introduced the Grid Builder.  With this tool, it is now very easy to create your responsive framework.

2.50 containes a lot of new stuff, as you’ve read in the posts on this blog: ABMChat, ABMPlanner and ABMPercentSlider are only a few of the new things.  Worth mentioning are the major changes in the ABMPivot component, adding new features like exporting to Excel, collapsable rows and columns, new presentations and so on.

Check out the online demo abmaterial.com or download your free copy from the B4J website.

Donators will receive a download link for 2.50 shortly.

Happy Programming!

Alwaysbusy

Click here to Donation if you like my work


B4J: New ABMPlanner and ABMPercentSlider (ABMaterial 2.50)

abmplannerA friend of mine, who is a doctor, wanted me to write a scheduling webapp. He had some perticular requests:

1. You should be able to schedule per 5 minutes
2. But still need to be able to see the whole week
3. Wanted only to see the 5 working days (no weekends)
4. Should see from 06:00 to 21:00
5. As his assistant has to ‘fill’ the schedule, he also wanted somehow to show her when he would not be available.

I told him this quickly added up to showing about 840 possible appointments I had to show him on his desktop, tablet and iPhone. “Yes”, was his dry answer…

I didn’t know any such object, so I’ve put on my thinking hat and came up with ABMPlanner for B4J!

Although it has been written especially for his needs, I’m sure it can come in handy for other kind of projects too. For example you can schedule per 5, 10, 15, 20 or 30 minutes. You can set the start/end time of a day. And it can show a full week (including the weekend). You can give each task different colors etc…

It can also show the week as a ‘HeatMap’, so he can see very fast where he can put someone in-between other patients.

The second component ABMPercentSlider (in the video when the modalsheet is opened) is an alternative radio group component. It ranges the possibilities in a ‘percentage’ range, with 5% intervals.

But have a look at the video (app is work in progress and sorry it is in dutch). It can be intimidating at first glance, but once you ‘get’ it, it’s actually a breeze to schedule stuff.

Some relevant code:

BuildPage:

Dim plan As ABMPlanner
plan.Initialize(page, "plan", False, 6,20, 5,False,"black")
plan.UseHeatMap("1,3,6")
page.Cell(2,1).AddComponent(plan)

Adding a task (loading a random generated week):

Sub LoadRandomWeek(StartDay As Long,doRefresh As Boolean)
   Dim plan As ABMPlanner = page.Component("plan")
   plan.ClearPlanner

   Dim Days(7) As String
   Dim Day As Int = DateTime.GetDayOfMonth(StartDay)
   Dim nextDay As Long = StartDay
   Dim perNext As Period
   perNext.Initialize
   perNext.Days = 1
   For i = 0 To 6
     If ActiveDay = -1 Then
       If DateTime.Date(nextDay) = DateTime.Date(DateTime.Now) Then
         ActiveDay = i
       End If
     End If
     Days(i)   = Day
     If Days(i).Length = 1 Then
       Days(i) = "0" &amp; Days(i)
     End If
     nextDay = DateUtils.AddPeriod(nextDay, perNext)
     Day = DateTime.GetDayOfMonth(nextDay)
   Next
   Dim mins As List
   mins.Initialize
   mins.Add(1)
   mins.Add(3)
   mins.Add(6)
   mins.Add(12)
   plan.SetDayLabels("MA " &amp; Days(0), "DI " &amp; Days(1), "WO " &amp; Days(2), "DO " &amp; Days(3), "VR " &amp; Days(4),  "ZA " &amp; Days(5),  "ZO " &amp; Days(6))
   Dim PerTotal As Int = 12

   For i = 0 To 4
     Dim u As Int = 6
     Dim m As Int = 0
     Dim l As Int = 0
     Dim lIndex As Int
     Do While u &lt; 21
       Do While m &lt; PerTotal    
         m = m + Rnd(1,3)          
         lIndex = Rnd(0,3)
         l = mins.Get(lIndex)
         If (u*PerTotal + m + l) &lt; (21*PerTotal) And m &lt; PerTotal And (i &lt;&gt; 2 Or u &lt;=11 ) Then
           Dim patient As String = FirstNames.get(Rnd(0,19)) &amp; " " &amp; LastNames.get(Rnd(0,19))
           counter = counter + 1
           plan.AddTask(NewTask(i, "T" &amp; counter,u,m,l,patient,lIndex)) ' taskid must be a string!                
         End If
         m = m + l
       Loop
       m = m - PerTotal
       u = u + 1
     Loop
   Next

   plan.SetActiveDay(ActiveDay)
   For i = 12 To 20
     plan.SetHourStatus(2,i,False)
   Next
   If doRefresh Then
     plan.Refresh
   End If
End Sub

Events:

Sub plan_ActiveDayChanged(day As Int)
   Log("New day: " &amp; day)
   ActiveDay = day
   ' important to sync the server with the browser!
   Dim plan As ABMPlanner = page.Component("plan")
   plan.SetActiveDay(ActiveDay)
End Sub

Sub plan_MinutesClicked(Value As String)
   Dim spl() As String = Regex.Split(";", Value)
   ' spl(0) is here always 0, as this would contain the menu item clicked.  This is to be uniform with the MenuClicked Value param
   Log("Day: " &amp; spl(1))
   Log("Hour: " &amp; spl(2))
   Log("MinPer5: " &amp; spl(3))
   ' use the ABM.PLANNER_STATUS_ constants to check the status
   Log("Status: " &amp; spl(4))
   Log("Task ID: " &amp; spl(5))

   page.ShowModalSheet("patientafspraak")
End Sub

Sub plan_MenuClicked(MenuType As String, Value As String)
   Dim spl() As String = Regex.Split(";", Value)
   Dim plan As ABMPlanner = page.Component("plan")
   Log("MenuType: " &amp; MenuType)
   Log("Value: " &amp; Value)
   Select Case MenuType
     Case ABM.PLANNER_MENUTYPE_DAY
       ' update the database

       Log("Day: " &amp; spl(1))

       Select Case spl(0)
         Case ABM.PLANNER_MENU_SETFREE
           plan.SetDayStatus(spl(1), True)
         Case ABM.PLANNER_MENU_SETNOTAVAILABLE
           plan.SetDayStatus(spl(1), False)
       End Select

       ' IMPORTANT to perform the action in the browser
       plan.PerfromDayHourMenuAction
     Case ABM.PLANNER_MENUTYPE_HOUR
       ' update the database

       Log("Day: " &amp; spl(1))
       Log("Hour: " &amp; spl(2))

       Select Case spl(0)
         Case ABM.PLANNER_MENU_SETFREE
           plan.SetHourStatus(spl(1), spl(2), True)
         Case ABM.PLANNER_MENU_SETNOTAVAILABLE
           plan.SetHourStatus(spl(1), spl(2), False)
       End Select

       ' IMPORTANT to perform the action in the browser
       plan.PerfromDayHourMenuAction  
     Case ABM.PLANNER_MENUTYPE_MIN
       ' update the database

       Log("Day: " &amp; spl(1))
       Log("Hour: " &amp; spl(2))
       Log("MinPer5: " &amp; spl(3))
       ' use the ABM.PLANNER_STATUS_ constants to check the status
       Log("Status: " &amp; spl(4))
       Log("Task ID: " &amp; spl(5))

       Select Case spl(0)
         Case ABM.PLANNER_MENU_CUT
           cutTaskID = spl(5)
           copyTask = plan.GetTask(spl(5))
           IsCut = True
           myToastID = myToastID + 1
           page.ShowToast("toast" &amp; myToastID, "toastred", "Verplaats " &amp; copyTask.Text &amp; " naar...", 5000)
         Case ABM.PLANNER_MENU_COPY
           copyTask = plan.GetTask(spl(5))
           IsCut = False
           myToastID = myToastID + 1
           page.ShowToast("toast" &amp; myToastID, "toastred", "Kopieer " &amp; copyTask.Text &amp; " naar...", 5000)
         Case ABM.PLANNER_MENU_PASTE
           If IsCut Then
             plan.RemoveTask2(cutTaskID)
           Else
             counter = counter + 1
             copyTask = copyTask.Clone("T" &amp; counter)
           End If
           copyTask.Day = spl(1)
           copyTask.StartHour = spl(2)      
           copyTask.StartMinututesPer = spl(3)
           plan.AddTask(copyTask)      
           plan.Refresh
           If IsCut Then
             myToastID = myToastID + 1
             page.ShowToast("toast" &amp; myToastID, "toastred", copyTask.Text &amp; " verplaatst!", 5000)
           Else
             myToastID = myToastID + 1
             page.ShowToast("toast" &amp; myToastID, "toastred", copyTask.Text &amp; " gekopieerd!", 5000)
           End If
         Case ABM.PLANNER_MENU_DELETE
           plan.RemoveTask2(spl(5))
           plan.Refresh
       End Select

   End Select
End Sub

These are the final components for ABMaterial 2.50. I’m now going to prepare everything for the next release. (updating the demos etc), so donators will receive these new toys shortly…

Alwaysbusy

Click here to Donation and support ABMaterial

 

 


B4J: New ABMChat component for ABMaterial 2.50

abmchat

ABMChat is a new cool looking ABMaterial component to create a Web based chat program. The inner workings are very much like Erels ChatRoom, but with a slick interface. This can be a useful control if for example you want to give chat-like support within you own B4J webapp.

Some features:
– Balloon/Bubble-like chat
– Support for some ASCII emoji
– IsTyping ballon

Coding this with B4J and ABMaterial is very easy:

Code ChatShared module:

Sub Process_Globals
   Public AvoidDuplicates As Map
   Private connections As Map
   Public LastMessages As List
   Private IsTypingMap As Map
End Sub

public Sub Init
   AvoidDuplicates = Main.srvr.CreateThreadSafeMap
   connections.Initialize
   LastMessages.Initialize
   IsTypingMap.Initialize
End Sub

public Sub NewConnection(page As ChatPage, pageID As String)
   DateTime.TimeFormat = "HH:mm"

   Dim IdentifyBubble As ABMChatBubble
   IdentifyBubble.Initialize("Server", page.ChatName & " has joined the chat...", "Server " & DateTime.Time(DateTime.Now), "server", "server")
   JoinLeftMessage(pageID, IdentifyBubble)
   connections.Put(pageID, page)
   CallSubDelayed2(page, "CurrentConversation", LastMessages)
End Sub

public Sub NewMessage(pageID As String, Message As ABMChatBubble)
   LastMessages.Add(Message)
   For Each page As ChatPage In connections.Values
     CallSubDelayed2(page, "NewMessage", Message)
   Next
End Sub

public Sub JoinLeftMessage(pageID As String, Message As ABMChatBubble)
   For Each page As ChatPage In connections.Values
     CallSubDelayed2(page, "NewMessage", Message)
   Next
End Sub

public Sub IsTyping(pageID As String, Value As String)
   Dim typeBool As Boolean
   If Value = "" Then
     IsTypingMap.Remove(pageID.ToLowerCase)
   Else
     IsTypingMap.put(pageID.ToLowerCase, "true")
   End If
   If IsTypingMap.Size > 0 Then
     typeBool = True
   End If
   For Each page As ChatPage In connections.Values
     CallSubDelayed3(page, "IsTyping", pageID, typeBool)
   Next
End Sub

public Sub Disconnected(page As ChatPage, pageID As String)
   If connections.ContainsKey(pageID) = False Or connections.Get(pageID) <> page Then Return
   Dim LeaveBubble As ABMChatBubble
   LeaveBubble.Initialize("Server", page.ChatName & " has left the chat...", "Server " & DateTime.Time(DateTime.Now), "server","server")
   JoinLeftMessage(pageID, LeaveBubble)
   connections.Remove(pageID)
   AvoidDuplicates.Remove(pageID.ToLowerCase)
End Sub

Public Sub HasIdentified(pageID As String) As Boolean
   Return connections.ContainsKey(pageID)
End Sub

Relevant Code ChatPage class:

Private Sub WebSocket_Disconnected
   Log("Disconnected")
   If ABMPageId <> "" Then CallSubDelayed3(ChatShared, "Disconnected", Me, ABMPageId)
End Sub

public Sub BuildTheme()
   ' start with the base theme defined in ABMShared
   theme.Initialize("pagetheme")
   theme.AddABMTheme(ABMShared.MyTheme)

   ' add additional themes specific for this page
   theme.AddChatTheme("myChat")
   theme.Chat("myChat").AddBubble("server")
   theme.Chat("myChat").Bubble("server").Color = ABM.COLOR_BLACK
   theme.Chat("myChat").Bubble("server").TextColor = ABM.COLOR_WHITE

   theme.Chat("myChat").AddBubble("me")
   theme.Chat("myChat").Bubble("me").Color = ABM.COLOR_LIGHTBLUE
   theme.Chat("myChat").Bubble("me").TextColor = ABM.COLOR_WHITE

   theme.Chat("myChat").AddBubble("them")
   theme.Chat("myChat").Bubble("them").Color = ABM.COLOR_GREY
   theme.Chat("myChat").Bubble("them").ColorIntensity = ABM.INTENSITY_LIGHTEN2
   theme.Chat("myChat").Bubble("them").TextColor = ABM.COLOR_BLACK
End Sub

public Sub ConnectPage()
'   connecting the navigation bar    

'   init all your own variables (like a List, Map) and add your components
   Dim chat As ABMChat
   chat.Initialize(page, "conversation",600, 450, 255, "mychat")
   chat.AddBubble("Server", "I'm Server, what is your name?", "The Server", "server", "server")

   page.Cell(1,1).AddComponent(chat)

   Dim ChatInput As ABMInput
   ChatInput.Initialize(page, "ChatInput", ABM.INPUT_TEXT, "", False, "")
   ChatInput.PlaceHolderText = "Type your message here...."
   ChatInput.RaiseChangedEvent = True
   page.Cell(2,1).AddComponent(ChatInput)

   ' refresh the page
   page.Refresh
   ' Tell the browser we finished loading
   page.FinishedLoading
   ' restoring the navigation bar position
   page.RestoreNavigationBarPosition
End Sub

Sub ChatInput_Changed(value As String)
   If ChatShared.HasIdentified(ABMPageId) Then
     CallSubDelayed3(ChatShared, "IsTyping", ABMPageId, value)
   End If
End Sub

Sub ChatInput_EnterPressed(value As String)
   DateTime.TimeFormat = "HH:mm"

   If ChatShared.HasIdentified(ABMPageId) Then
     Dim bubble As ABMChatBubble
     bubble.Initialize(ChatName, value, ChatName & " " & DateTime.Time(DateTime.Now), "me", "them")
     CallSubDelayed3(ChatShared, "NewMessage", ABMPageId, bubble)
     CallSubDelayed3(ChatShared, "IsTyping", ABMPageId, "")
   Else
     If value = "" Then Return
     If ChatShared.AvoidDuplicates.ContainsKey(value.ToLowerCase) Then
       Dim chat As ABMChat = page.Component("conversation")
       chat.AddBubble("Server", "Sorry, but " & value & " is already taken!", "The Server", "server", "server")
       chat.Refresh
     Else
       ChatName = value
       ChatShared.AvoidDuplicates.Put(value.ToLowerCase, value)
       Dim chat As ABMChat = page.Component("conversation")
       chat.SetMyFrom(ChatName)
       chat.AddBubble("Server", "Welcome to ABMChat " & ChatName & "!", "The Server", "server", "server")
       chat.Refresh
       CallSubDelayed3(ChatShared, "NewConnection", Me, ABMPageId)
     End If
   End If

   Dim ChatInput As ABMInput = page.Component("ChatInput")
   ChatInput.Text = ""
   ChatInput.Refresh
End Sub

public Sub NewMessage(bubble As ABMChatBubble)
   Dim chat As ABMChat = page.Component("conversation")
   chat.AddBubble2(bubble)
   chat.Refresh
   chat.ScrollToBottom   ' scroll to the end of the chat
End Sub

public Sub IsTyping(pageID As String, typeBool As Boolean)
   Dim chat As ABMChat = page.Component("conversation")
   If pageID <> ABMPageId Then
     If typeBool = False Then
       chat.ThemAreTyping(False, "") 'hide the 'is typing' bubble
     Else
       chat.ThemAreTyping(True, "") ' show the 'is typing' bubble if not yet shown
     End If
     chat.Refresh
     chat.ScrollToBottom   ' scroll to the end of the chat
   End If
End Sub

public Sub CurrentConversation(LastMessages As List)
   If LastMessages.Size > 0 Then
     Dim chat As ABMChat = page.Component("conversation")
     chat.SetConversation(LastMessages)
     chat.Refresh
     chat.ScrollToBottom   ' scroll to the end of the chat
   End If
End Sub

So, there you have it. A complete modern looking multichat webapp that runs on all platforms in just about 150 lines of code!

Alwaysbusy

Click here to Donation and support ABMaterial


%d bloggers like this: