Share your advanced knowledge/code with the community.
poshu
 
Posts: 67
Joined: Mon Feb 24, 2014 11:46 pm

JSTools

by poshu Tue Jul 10, 2018 9:19 am

This is a short module containing JS procedures that I find myself using on almost all my projects. Some I found on this forum, some on stack overflow and some I wrote myself.
Code: Select all
DeclareModule JSTools
   ;Cordova Event
   #CordovaEvent_Pause = "pause"
   #CordovaEvent_Resume = "resume"
   #CordovaEvent_BackButton = "backbutton"
   #CordovaEvent_VolumeUpButton = "volumeupbutton"
   #CordovaEvent_VolumeDownButton = "volumedownbutton"
   
   Declare.s b64DecodeUnicode(str.s)                                     ; Decode an unicode string in base 64.
   Declare.s b64EncodeUnicode(str.s)                                       ; Encode an unicode string in base 64.
   Declare.i BindCordovaEvent(Event.s,*Callback)                     ; Bind a Cordova event to a callback.
   Declare.i UnBindCordovaEvent(Event.s,*Callback)                  ; Unbind a Cordova event from a callback.
   Declare.i FreeDebugOutput()                                                ; Actually close the debug window to avoid background window misalignment.
   Declare.i GadgetElement(Gadget, UseJquery.b=#True)            ; Get the DOM element for a gadget.
   Declare.s GetLocalLanguage()                                             ; Will return the user language as a string (EN, FR, etc...).
   Declare.i IsThisCordova()                                                   ; Will return true if executed in Cordova and false otherwise.
   Declare.i LoadCSS(FileName.s, *Callback,Tag)                     ; Load a CSS. Callback should be : callback(Tag,Result,URL,Error).
   Declare.i LoadScript(FileName.s, *OnLoadFunction, Tag.i)   ; Load a js file. Callback should be : callback(Tag,Result,URL,Error).
   Declare.i SetClipboardText(text.s)                                    ; Stores a string into the clipboard. If the clipboard already contains text, it will be overwritten.
   Declare.s uuidv4()                                                            ; Generate an UUID compliant with RFC 4122.
   Declare.i WindowElement(Window, UseJquery.b=#True)            ; Get the DOM element for a window.
EndDeclareModule

Module JSTools
   EnableExplicit
   
   ; Private declarations
   Declare LoadAsynchronously(FileName.s, *Callback, FileType.s,Tag.i)
   Declare SetClipboardText_FallBack(text.s)
   
   ; Public procedures
   
   Procedure.s b64DecodeUnicode(str.s)
      !return decodeURIComponent(atob(v_str).split('').map(function(c) {
      !   return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      !}).join(''));
   EndProcedure
   
   Procedure.s b64EncodeUnicode(str.s)
      !return btoa(encodeURIComponent(v_str).replace(/%([0-9A-F]{2})/g,
      !   function toSolidBytes(match, p1) {
      !      return String.fromCharCode('0x' + p1);
      !}));
   EndProcedure
   
   Procedure BindCordovaEvent(Event.s,*Callback)
      !document.addEventListener(v_event, p_callback);
   EndProcedure
   
   Procedure UnBindCordovaEvent(Event.s,*Callback)
      !document.removeEventListener(v_event, p_callback);
   EndProcedure
   
   Procedure FreeDebugOutput()
      !$('div').eq(0).remove()
   EndProcedure
   
   Procedure.i GadgetElement(Gadget, UseJquery.b=#True)
      Protected gadgetObject=GadgetID(Gadget), result
      !v_result =  (v_gadgetobject && v_gadgetobject.div)? v_usejquery? $(v_gadgetobject.div):v_gadgetobject.div:null;
      ProcedureReturn result
   EndProcedure
   
   Procedure.s GetLocalLanguage()
      Protected result.s
      !var lang = navigator.language.split("-");
      !var v_result = (lang[0]);
      
      ProcedureReturn result
   EndProcedure
   
   Procedure.i IsThisCordova()
      Protected result
      !if (typeof cordova !== 'undefined') {
      result =  #True
      !}
      
      ProcedureReturn result
   EndProcedure
   
   Procedure.i LoadCSS(FileName.s, *Callback,Tag.i)
      Protected jqxhr=LoadAsynchronously(FileName, *Callback, "text",Tag), result
      !result = v_jqxhr.done(function(data, status, jqxhr) {
      !   $('<style></style>').appendTo('head').html(data);
      !})
      ProcedureReturn result
   EndProcedure
   
   Procedure.i LoadScript(FileName.s, *OnLoadFunction, Tag.i)
      ProcedureReturn LoadAsynchronously(FileName, *OnLoadFunction, "script", Tag)
   EndProcedure
   
   Procedure SetClipboardText(text.s)
      !  if (!navigator.clipboard) {
      !       jstool$f_setclipboardtext_fallback(v_text);
      !       return;
      !  }
      !  navigator.clipboard.writeText(v_text);
   EndProcedure
   
   Procedure.s uuidv4()
      Protected Result.s
      !  v_result = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      !    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      !    return v.toString(16);
      !  });
      ProcedureReturn Result
   EndProcedure
   
   Procedure.i WindowElement(Window, UseJquery.b=#True)
      Protected winObject=WindowID(Window), result
      !v_result = (v_winobject && v_winobject.element)? v_usejquery? $(v_winobject.element):v_winobject.element:null;
      ProcedureReturn result
   EndProcedure
   
   ; Private procedures
   
   Procedure.i LoadAsynchronously(FileName.s, *Callback, FileType.s,Tag.i)
      Protected result
      !v_result = $.ajax({ url:v_filename, dataType:v_filetype, beforeSend:function(jqxhr, settings) { jqxhr.url = settings.url; } })
      !.done(function(data, status, jqxhr) { p_callback(v_tag,status,jqxhr.url); })
      !.fail(function(jqxhr, status, errorThrown) { p_callback(v_tag,status,jqxhr.url,errorThrown); });
      ProcedureReturn result
   EndProcedure
   
   Procedure SetClipboardText_FallBack(text.s)
      !  var textArea = document.createElement("textarea");
      !  textArea.value = v_text;
      !  document.body.appendChild(textArea);
      !  textArea.focus();
      !  textArea.select();
      !
      !  try {
      !    document.execCommand('copy');
      !  } catch (err) {
      !    console.error('Fallback failed', err);
      !  }
      !  document.body.removeChild(textArea);
   EndProcedure
   
EndModule
Last edited by poshu on Wed Aug 01, 2018 9:37 am, edited 6 times in total.
poshu
 
Posts: 67
Joined: Mon Feb 24, 2014 11:46 pm

Re: JSTools

by poshu Fri Jul 13, 2018 6:43 pm

+ Added : DestroyDebugOutput() : CloseDebugOutput() only hide the debug window. when associated with PB_Window_Background, it can result in some misalignment :

Image

DestroyDebugOutput() really closes it!

Thanks to @Falsam.
poshu
 
Posts: 67
Joined: Mon Feb 24, 2014 11:46 pm

Re: JSTools

by poshu Sun Jul 29, 2018 10:10 pm

+ Added : SetClipboardText(text.s) : Stores a string into the clipboard. If the clipboard already contains text, it will be overwritten.

/!\ Since the clipboard API is still experimental and support is limited, I added a fallback solution./!\
poshu
 
Posts: 67
Joined: Mon Feb 24, 2014 11:46 pm

Re: JSTools

by poshu Wed Aug 01, 2018 9:37 am

+ Added BindCordovaEvent() and UnBindCordovaEvent() to manage Cordova Events in SB. See https://cordova.apache.org/docs/en/latest/cordova/events/events.html for more informations.
~ Changed : DestroyDebugOutput() to FreeDebugOutput() for consistance.
Return to Tricks 'n' Tips

Who is online

Users browsing this forum: No registered users and 0 guests