<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>The Zonebuilder</title> <atom:link href="http://192.168.1.170/feed/" rel="self" type="application/rss+xml" /><link>http://192.168.1.170:8000</link> <description>web development, programming, IT, society, philosophy, politics</description> <lastBuildDate>Sat, 19 Oct 2024 15:37:15 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <item><title>TypeScript Lite</title><link>https://the-zonebuilder.freetzi.com/typescript-lite/</link> <comments>https://the-zonebuilder.freetzi.com/typescript-lite/#comments</comments> <pubDate>Tue, 20 Feb 2024 16:49:20 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[society]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=258</guid> <description><![CDATA[Looking for the perfect programming language for writing your application? And so many experts told you that there isn&#8217;t one, only certain tools for certain tasks. Yes there is, it&#8217;s your imagination. You just have to know how to share it with the others. The types paradigm Historically, programming languages divided between two major categories: [&#8230;]]]></description> <content:encoded><![CDATA[<p>Looking for the perfect programming language for writing your application? And so many experts told you that there isn&#8217;t one, only certain tools for certain tasks. Yes there is, it&#8217;s your imagination. You just have to know how to share it with the others.</p><h2>The types paradigm</h2><p>Historically, programming languages divided between two major categories: a smaller subset of dynamic or typeless languages such as PHP, JavaScript, Python or Ruby, and a larger one of typed languages starting from C, C++, Pascal, Fortran, Java, C#, Go or Rust and reaching to type-augmented languages like TypeScript or Dart. Yet, the dynamic languages do use types for data manipulation and even perform some type-checking at run time, while the typed or static languages usually get a binary form when running, where type-checking isn&#8217;t performed by default for the memory zones that were variables or data structures, which already got checked at compile time. So, types are always meant when we&#8217;re coding, but not so relevant for the machine executing the code. This is because type is a human concept sitting near similar ones like category, kind, sort, class and so on. Although static languages have used the stricter syntax to perform better error checking, ahead-of-time compilation and optimizations, dynamic languages have caught up in features and performance using techniques like just-in-time compilation and execution paths. For a limited set of types of a variable in code, most of their use-case scenarios invalidate when actually executing the program.<br /> In a more natural programming language, the variable naming would have word meaning, so that the bundler/compiler can look up in a human language dictionary in order to perform additional type detection. We, as humans, take advantage of the other sensorial information, knowledge and context to even better infer the types of the objects.  A smart compiler, parser or IDE can use interaction /prompting or AI assistance to complete the type identification at development.<br /> The long time debate of the syntactical expression of the types throughout the code may become, after all, simply a matter of to type or not to type.</p><h2>A good idea revived</h2><p>As described in <a title="TypeScript Lite" target="_blank" href="https://github.com/zonebuilder/tslite-node">TypeScript&#8217;s Lite project page</a>, this Node.JS package (TSLite) converts a JavaScript source tree into a TypeScript source tree. This is possible because TSLite transparently uses one of the simplest form of type annotations: the prefix notation.<br /> The idea of the prefix naming, also called the Hungarian notation, was first brought up several decades ago by large software companies for some of their in-house platforms such as Microsoft MFC, Win32 API, or Borland OWL. Because the notation was used at platform level, and companies insisted in a canonical construction of the required prefixes, pretty soon developers confronted to referencing a large amount of prefix items made mainly of consonants that made them joke about learning in fact the spelling of a foreign language, and the naming practice faded away.<br /> By contrast to the original implementation, which still has the merit of a good beginning, the TSLite prefix notation has the following key features:</p><ul><li>Prefixes are user-defined at project level via a configuration file. It&#8217;s also possible to specify prefixes at file level via a dedicated block comment.</li><li>User can choose lowercase prefixes of any length, and even by regex pattern match. These prefixes apply to built-in or user-defined variable types, but also to specific chosen variables.</li><li>In CommonJS and ES modules, the imported and exported variables and top-level functions can and should be excepted from the prefix naming. typescript will infer the types from the imported modules and from function signatures. No prefix notation will be applied to object/class/map members. For these structures, one can use external TS definition files or structural JSDoc comments.</li></ul><p>An example of a conventional Express.JS app stub that gets converted to TypeScript based on variable prefixes and a config file, is shown below.</p><h4>app.js</h4><pre class="brush:js">/* tslite-add
 * interface Request { app: any; }
 * interface Response { locals: any; render: Function; }
 */
const cookieParser = require('cookie-parser')
const express = require('express')
const httpErrors = require('http-errors')
const logger = require('morgan')
const path = require('path')

const indexRouter = require('./routes/index')

/// @ts-ignore
const app = express()

app.set('views', path.join(__dirname, 'views'))
// view engine setup
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())

app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)

// catch 404 and forward to error handler
app.use((req, res, next) =&gt; {
    next(httpErrors(404))
})

// error handler
app.use((err, req, res, next) =&gt; {
    // set locals, only providing error in development
    res.locals.message = err.message
    res.locals.error = req.app.get('env') === 'development' ? err : {}

    // render the error page
    /// @ts-ignore
    res.status(err.status || 500)
    res.render('error')
})

module.exports = app</pre><h4>app.ts</h4><pre class="brush:js">interface Request { app: any; }
interface Response { locals: any; render: Function; }
const cookieParser = require('cookie-parser')
const express = require('express')
const httpErrors = require('http-errors')
const logger = require('morgan')
const path = require('path')

const indexRouter = require('./routes/index')

/// @ts-ignore
const app = express()

app.set('views', path.join(__dirname, 'views'))
// view engine setup
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())

app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)

// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: Function) =&gt; {
    next(httpErrors(404))
})

// error handler
app.use((err: any, req: Request, res: Response, next: Function) =&gt; {
    // set locals, only providing error in development
    res.locals.message = err.message
    res.locals.error = req.app.get('env') === 'development' ? err : {}

    // render the error page
    /// @ts-ignore
    res.status(err.status || 500)
    res.render('error')
})

module.exports = app</pre><h4>tslite.json</h4><pre class="brush:js">{
  &quot;input&quot;: [&quot;express-app&quot;, &quot;sample.js&quot;],
  &quot;output&quot;: &quot;../src-ts&quot;,
  &quot;matcher&quot;: [
    &quot;/\\.js(x?)$/i&quot;,
    &quot;.ts$1&quot;
  ],
  &quot;prefixes&quot;: {
    &quot;a&quot;: &quot;any[]&quot;,
    &quot;b&quot;: &quot;boolean&quot;,
    &quot;f&quot;: &quot;Function&quot;,
    &quot;n&quot;: &quot;number&quot;,
    &quot;o&quot;: &quot;any&quot;,
    &quot;s&quot;: &quot;string&quot;,
    &quot;$e[0-9]*&quot;: &quot;any&quot;,
    &quot;$[i-nx-z][0-9]*&quot;: &quot;number&quot;,
    &quot;req&quot;: &quot;Request&quot;,
    &quot;res&quot;: &quot;Response&quot;,
    &quot;$next&quot;: &quot;Function&quot;,
    &quot;$err&quot;: &quot;any&quot;
  }
}</pre><h4>tsconfig.json</h4><pre class="brush:js">{
  &quot;compilerOptions&quot;: {
    &quot;outDir&quot;: &quot;dist&quot;,
    &quot;strictNullChecks&quot;: false,
    &quot;target&quot;: &quot;es2016&quot;,
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;esModuleInterop&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;strict&quot;: true,
    &quot;skipLibCheck&quot;: true
  }
}</pre><p>Being generated by an automated tool (yeoman), the JS code is kept unaltered, but you can easily apply the prefix notation to all desired variables and immediately see the additional resulting TS typings.<br /> Although the TSLite package is a Node.JS console app, it can be run uniformly on a mobile, browser, server or any ES5.ES6project code. A typical workflow to choose is: first write your ES6 prefixed code and verify it with ESLint, second convert the code with TSLite and verify it with TSC.<br /> As this toolset allows you to write robust JavaScript code that gets converted in one step in any TS annotation dialect (like e.g. AssemblyScript), you can use the prefix notation to automatically map to a typed/static source code.</p><h2>Stenography</h2><p>People have used the shorthand notation, also called stenography, since the classical Greek antiquity  (ca. 400 BCE), to record spoken messages in writing with a speed comparable to that of the speaker. Departing from the Greek and Roman era, stenography has greatly evolved in the 18th and 19th centuries, with forms of shorthand based on geometrical shapes (circles, lines, dots), and then on symbols for phonemes (spoken sounds). The latter standardized and has been adopted in a few decades in over 16 languages from Europe, America and Asia. In the same time, stenography, orthography (of punctuation marks and abbreviations), and the symbolic notation in sciences borrowed heavily one from another, while maturing and becoming standard methodologies. What started as a need for speed in writing, became a universal approach to convey meaningful, concise, and precise information for people all over the world.<br /> A century later, the creators of the 3rd generation programming languages drew from the principles of the shorthand and symbolic notations, building the first human-like syntax of what was still perceived at the time as a wrapper around computational logic and machine instruction sets. Due to their universality, some of these languages have become the backbone of modern programming, being adopted in every corner of the world, where they popularized a common technological advancement and the slang that we call today &#8220;IT English&#8221;.<br /> It is supposed that coding tools mainly solve technical problems, yet they are also, everywhere, a powerful way of collaboration and communication, as the shorthand and symbolic notations have already been a century before the digital era.</p><h2>The Script</h2><p>Taking into account the previous arguments, one can say that the general purpose programming  language of the near future will have the following key features:</p><ul><li>-	It comes from a human-centric approach based on Math and Physics as opposed to the one based on the machine instruction set. Current algorithmics, tools and AI are able to translate from the human expression syntax to the computer logic. It is expected that the future programming of most system will solely concern to the business problem, while allowing a full range of human inputs besides writing.</li><li>It uses short words, abbreviations (e.g. of simplified International English), and symbols for keywords and operators, keeping an easy to understand language vocabulary while adhering to the shorthand notation principle of writing concisely and precisely. The code is written in some kind of universal language, but it reads aloud in the natural language of the reader, much like the pseudo-code is read today.</li><li>It targets both interpreted and compiled runtimes. The original human inputted code is considered the source of truth. For any target, an augmented code may be generated automatically or by user assistance. The augmented code is link to segments or logical units (of a factor of several lines) of the original code. Modifying a segment of the original code invalidates the corresponding fragment of the augmented code, that will need to be regenerated depending of the target requirements.</li><li>It has a framework of controlling data structures and program flow called the program constraints. This program constraints framework describes and configures the followings: data types, objects&#8217; shape (structure), field validation, error hierarchy, module priority (sequence), concurrency configuration etc. it is secondary and applies immediately after the original code, thus affecting any augmented code. It is available to rely on at runtime, effectively taking part in the running program.</li></ul><p>The software that enables programming with this language has a modern set of development tools including: linting, compiling, code audit and tests generation, packing, runtime emulation (sandbox). For all stages of outputting some form of code or a program there is traceability, and the human factor can intervene if necessary.<br /> The language, that we&#8217;ll simply call &#8220;The Script&#8221;, makes it easy to use high order data structures and algorithms (like in C++ STL), asynchronous and web services wrappers, various tools for data processing and AI, by including their code in its user standard library.<br /> Many general purpose programming languages of today acquired built-in optimizations for compiling or just-in-time, sleek and freely available libraries for common domains of interest,, and good ergonomics for the developer aiming at complex problem-solving. Their basic learning has become trivial because of the AI code generating, and their inter-changeability evident because of the  excellent capabilities of today&#8217;s code transpilers. Instead of learning ten dialects or ten ways of using an advanced instrument which is our software solution platform, one can concentrate at mastering the general purpose language that targets all common runtimes either compiled or interpreted, and offers flexible optimization settings, specialized code libraries for business and technology,  and a universal environment ready to implement any creative Endeavour.</p><h2>Full circle</h2><p>Imagine that on your computer keyboard you also have two rows of keys which are regular shapes and known symbols like those we currently use. Any of these twenty symbol keys starts and completes a sequence of maximum three keystrokes that will become finally a geometrical symbol. The first keystroke will draw the typed shape as a lower part at the typing position, the second keystroke will draw the typed shape or symbol as the upper part maybe with a temporary slight overlapping, and the third keystroke will draw as superscript or subscript (by a key modifier), within the same geometrical symbol that will take the place of one character. From the first keystroke, a popup list will appear near the typing position containing final geometrical symbols sorted by similarity to the progressing typing sequence. This is a single-selection list where each item is a geometrical symbol followed by a word in the natural or preferred language of the user, but with the same global meaning when translated. The selection within the list moves or refines as you type the sequence or by user navigation (arrow keys, mouse, tapping, dictation, etc.). The sequence is terminated either by the third keystroke, or by pressing a terminator key (e.g. enter) or a character/delimiter key other than those twenty, or by choosing an item from the list.<br /> The final symbol isn&#8217;t a direct juxtaposition of the typed shapes, but is rather hinted by their succession and of their composition, looking and acting in fact as a truetype font. Examples of such a final symbols may be: a square followed by a sitting triangle gives the &#8216; house&#8217; symbol, a square followed by an upside-down triangle gives the &#8216; tree&#8217; symbol, an underline followed by a circle gives the &#8216; sunrise&#8217; symbol, an underline followed by a circle and then by an asterisk gives the &#8216; sunset&#8217; symbol.<br /> The inputted symbolic script will also carry  a word transcript in a default spoken language (e.g. English) which translates word-to-word to the words chosen by the typing user.</p><p>When used in coding, this typing method allows the use of geometrical symbols everywhere when we use words for naming like in variables, functions, classes, member names, etc. this can work with the actual code while keeping the text format for the exchanged data like JSON or XML.<br /> Remember that the Latin script descends in order from Greek, Phoenician, Aramaic, and ultimately from the Egyptian hieroglyphs, and the abstract sketching predates writing as a concept of the human mind. Also, various sci-fi depictions show a group of geometric shapes or symbols as a controls sequence for activating some distant future technologies.<br /> It is said that the most perfect shape in the universe is the circle, hence its constant use in arts, beauty, and even sciences. The planets in every gravitational field of their star fly into the space with least energy los on closed and almost circular paths. Even the tiny electron goes round around atom&#8217;s nucleus inside a closed strip, called energy level.<br /> It seems that the circular path is one of the fundamental laws of the universe. Some people say that the human history itself tends to repeat in cycles after a couple of hundred or thousand years.<br /> But some of us also noticed that planets when closing their path do not return in the same point of the universe because the stars and entire galaxies have their traveling paths. And the tiny electron has a tendency of jumping from an energy level to another, and even leaving the atom. If you are drawing a circle in the sand, it won&#8217;t close in the same point in space because the planet has been revolving in the meantime. Circles of living beings evolve themselves into spirals.<br /> So we&#8217;ve learned that there is a second fundamental law of the universe, at least as important as the first, called evolution.<br /> For those of us who value the human knowledge, there must be no place of being afraid of closed paths, or that history might repeat itself.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/typescript-lite/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>The 3 data models</title><link>https://the-zonebuilder.freetzi.com/the-3-data-models/</link> <comments>https://the-zonebuilder.freetzi.com/the-3-data-models/#comments</comments> <pubDate>Wed, 07 Jun 2023 17:11:35 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Web development]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=244</guid> <description><![CDATA[With the rise of the web as a programming platform, a series of design patterns starting with MVC, MVVM and ranging to data binding, state store and GraphQL have been implemented in web applications. But what&#8217;s becoming a major tendency in app development is the data-centric approach of describing an application. The application is the [&#8230;]]]></description> <content:encoded><![CDATA[<p>With the rise of the web as a programming platform, a series of design patterns starting with MVC, MVVM and ranging to data binding, state store and GraphQL have been implemented in web applications. But what&#8217;s becoming a major tendency in app development is the data-centric approach of describing an application.</p><h2>The application is the data</h2><p>An application comes from a stored code which can be regarded as its starting configuration. The isles of programming code converted into an executable form may be viewed as immutable isles of data which are giving birth to the actual program. The variables and the allocated memory zones can be regarded as mutable isles of data that are visited and transformed by the signal which is the running app. Furthermore, an application may have a set of configuration data that is stored as a configuration tree that is also almost static compared to the running program.<br /> Separating and structuring the mutable and the immutable data is the key to build a lasting solution that scales and adapts in time.</p><h2>The application is the business</h2><p>Separating the valuable data falls in the domain of architecture design of the current applications. For a web based app, that architecture is the client-server model with the division of the app in the UI, the server program, and the data centre. Usually, the data model used by the last part is carried over to the first two parts, which are structured more often with patterns of concern separation in mind, such as MVC or MVVM. But, as we will demonstrate below, the real application is the server processing part which can also be called the business logic. Also, the communication channel between client and server sections can be remote, local or direct, the last case depicting &#8216;classic&#8217; apps like the desktop ones that will be greatly leveraged by the proposed architecture.</p><p><a href="/site/wp-content/uploads/2023/06/3-data-models.png"><img class="aligncenter size-full wp-image-255" alt="3 data models" src="/site/wp-content/uploads/2023/06/3-data-models.png" width="960" height="720" /></a></p><h2>The 3 data models</h2><p>Let&#8217;s assume that both data exchange channels from the UI to the business logic and from the business logic to the persistence service use JSON messaging. Each JSON message, either pulled or pushed, may have several kinds of data isles such as: content, validation, error, query params, and so on. This data structures can be tailored to correspond to the JSON schema describing the application data model, see e.g. the <a title="Introduction to GraphQL" href="https://graphql.org/learn/" target="_blank">GraphQL approach</a>. What if, immediately after receiving a message, or right before sending it we apply a data transformation over its data isles, something more complex and non-linear like a XSLT variant for JSON, or simpler and linear like the <a title="JUL Data Mapper" href="https://www.npmjs.com/package/jul-data-mapper" target="_blank">JUL Data Mapper</a>.<br /> We can now decouple the business logic model from the other two parts, the UI and the persistence layer, and can use three JSON schemas to describe each model separately.<br /> It should be noted that an application can have multiple UI perspectives like web, mobile, desktop, ad version, paid version etc. it can also connect to several persistence services such as local or remote data base, cloud APIs, serverless etc. The advancement in versioning of the application&#8217;s data model is, in fact, the adjustment of its business logic model, and not necessarily of the other two parts which can have a quite different structure and field naming. If we regard the UI and the storage services of different perspectives as external services, it becomes clear that the application functionality should concentrate in its business logic part. This is now enabled by separating the three data models based on the data transformation applied on the JSON data channels. We will call the transformation code as a data transformation driver (DTD).</p><h2>Workflow</h2><p>First step is correctly identifying the business logic part of the app. This app part has certain common but not mandatory or exclusive features, such as: ability to serve multiple clients at the same time, residing server-side, externalization of the storage/persistence services. The key feature though, is processing the business critical data, process that includes automatic decision making, data validation, error handling, maintenance, data aggregation etc.<br /> Second step is formatting all the requests and responses of each of the three parts of the application according to the usage and the semantics of the respective part, i.e. its data schema. As an example, if the client UI part sends a GET request to the server business logic, we usually send a query ID and a key/value hash of query parameters. We&#8217;ll use NAMED query params in the form &#8216;prop1.prop2.prop3 &#8216;, and convert the hash to a structured object that follows the UI data schema using a simple method like applying the <a title="JUL - The JavaScript UI Language" href="/jul-the-javascript-ui-language/">JUL</a>.ns() over each named key. The JSON response received from the server will have the items array, and maybe validation or error data structured to fit the data schema of the business logic, and not necessarily as direct members of the JSON root object.<br /> Third step is determining where to insert the DTD code. For the UI client part, there is usually a remote JSON data channel to the business logic server endpoints like the REST API architecture. We&#8217;ll apply the DTD at the client endpoint of the data channel, just before calling JSON.stringify () or immediately after JSON.parse () nethods, or their equivalent hooks/callbacks.<br /> The business logic is connected to a persistence/storage service via an ORM or an entity-to-service module and then, in many cases, a remote data channel that may not be JSON messaging. The ORM must be regarded as part of the data model of the service, and must follow the data schema of the persistence service. We will insert the DTD code as data transforming hooks on the argument values and on the response/result value of the CRUD and other ORM methods. For the cases where the exchange channel between the mid/second part of the app and the third part of the app is JSON, like web APIs or NoSQL, messaging, the DTD sits at the business logic endpoint of the data channel.<br /> Fourth step is organizing the DTD code in modules. For the client UI, there is usually a single bidirectional DTD module that will be used to transform the sent or received JSON messages i.e. request and responses. At the business logic, there are usually multiple DTD modules, one for each persistence service, some of them acting only on the received JSON data. In special cases, when also user programmable processing is available at the persistence service, a DTD module may be applied at that end of the application.<br /> Fifth step is end-to-end testing of the application with the inserted DTD modules. This is done by incrementally changing the structure of the data model of the business logic then adjusting the affected client UI and business-to-service DTD modules. The DTD code adjustment should be made via configuration, leaving intact the main data transformation code as in e.g. JUL Data Mapper. Of course, structural data changes may be applied also to the client UI or to the persistence services, albeit in a separate test step.</p><h2>Types of DTD and related data channels</h2><p>The DTD code can be scripted, run as a binary, or even embedded in hardware. All these methods have in common the running of the data transformation in memory, leaving as user configuration the DTD configuration matrix or its equivalent code. The in-memory data transformation can be applied over any tree-like data structures such as XML, DOM, SVG, JSON, etc. and is, essentially, language agnostic.<br /> A common pattern of using data channels is transmitting over a physical infrastructure or delivering compressed/encrypted data in software. At a closer look, in all the cases when we have a data channel to transmit the relevant data, we also have at least one hardware or software data connector that acts on relevant data, in the simplest case as an identity matrix.<br /> We will use the reverse of the before mentioned pattern as a rule for describing the architecture of a web app: <em>in an application, wherever is a data connector i.e. a DTD, there is a data channel</em>.<br /> Summing up, the types of data channels in relation to a DTD are:</p><ul><li>Remote data channels: when the two ends of the data channel are on different systems/infrastructures</li><li>Local data channels: when both ends of the data channel are on the same system</li><li>Virtual/direct data channels: when we insert a data connector on an otherwise unaltered in-memory or direct data exchange</li></ul><p>It&#8217;s worth mentioning that besides the typical one-to-one DTDs, there can also be one-to-many DTDs which may serve as a data aggregator for multiple data channels. In this case though, the problem of time syncing the data inputs will appear, changing the DTD from a direct linear matrix transformation into a state machine. You may want to use multiple one-to-one DTDs followed by a data aggregation module.</p><h2>Applications</h2><p>The typical scenario for applying the proposed architecture is the insertion of the DTDs in a client server web application. Given the clear distinction between the three parts of the app, the benefits of using the 3 data models are outlined previously, and apply to the deployed application, but especially to the phases of initial development, software maintenance, and software upgrading of the product.<br /> The palette where a DTD can be applied is larger though, and includes mobile, desktop, embedded, VR or natural language ones, among others. This is because the UI/UX part of these types of applications can be regarded as a user perspective of accessing and manipulating the business part of the respective apps. For example, if we take a desktop app that connects to a local service database, the data bindings in the UI follow the naming and the structure of the database model through an ORM code. If, however, we insert a direct DTD before the ORM, not only we&#8217;ll be able to use a single UI code if we upgrade the connection to a production database, but we can use the business code that controls the CRUD operations for a different UI like e.g. a remote mobile app.<br /> So, you see, the 3 data models is a straightforward way for you to build more scalable and more universal applications.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/the-3-data-models/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Economics of the Future</title><link>https://the-zonebuilder.freetzi.com/economics-of-the-future-draft/</link> <comments>https://the-zonebuilder.freetzi.com/economics-of-the-future-draft/#comments</comments> <pubDate>Mon, 10 Oct 2022 08:16:23 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[fiction]]></category> <category><![CDATA[politics]]></category> <category><![CDATA[society]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=227</guid> <description><![CDATA[The earth&#8217;s biosphere has had a couple of billion years to adapt and survive the countless natural phenomena. But, it&#8217;s still unprepared for the artificial phenomena mankind has brought in the last centuries. These are today&#8217;s global challenges like pollution, global warming, industrial and domestic waste, natural resources consumption rate, etc. They should pose no [&#8230;]]]></description> <content:encoded><![CDATA[<p>The earth&#8217;s biosphere has had a couple of billion years to adapt and survive the countless natural phenomena.<br /> But, it&#8217;s still unprepared for the artificial phenomena mankind has brought in the last centuries. These are today&#8217;s global challenges like pollution, global warming, industrial and domestic waste, natural resources consumption rate, etc.<br /> They should pose no challenge for an intelligent race that acts as a super-organism.</p><h2>Global challenges</h2><p>The negative environmental effects, such as those enumerated above, have one common cause: the human desire for comfort. This is a part of the human nature for the foreseeable future, because any living being will strive for a better life.<br /> The destination model for an evolved race has some known features: ability to adapt, ability to evolve, act as a single will when necessary, think like a single mind for a common concern, cope with its environment but keep the balance between nature, needs and interests.<br /> First steps towards such a super-organism are already taken: tight global communication and the global sharing of ideas/thoughts. The next predictable steps are global standard education and global awareness of humanity&#8217;s problems.<br /> Our global challenges are , in fact, correctly performing these positive evolutionary steps up to the point where taking care of the planet and its inhabitants is taking care of our personal home.</p><h2>Space jump</h2><p>One would think that the next step in human evolution is space exploration and colonization.<br /> While this step seen reasonable, the annotation &#8220;next&#8221; may not get entirely accurate.<br /> In the first stage of the colonization of even our own solar system, we must provide a home base to return to, or to get help from, in the vast majority of cases where far away missions will serve rather to learn than to be successful.<br /> What if our next step is a close by space jump meant to safeguard our home base, i.e. to help save Earth&#8217;s biosphere?<br /> Some ambitious initial targets would be e.g. moving 15% of the equivalent electrical energy produced on the surface and 10% of metal processing heavy industry into outer space, near the planet. Combined with the green economy ongoing plan, this will see significant percentage reduction in thermal dissipation and in industrial waste over a much shorter period of time.</p><h2>Principle of local conservation</h2><p>The wonder of life on Earth was predetermined by a series of cosmic and geological factors such as: the shape of the planet&#8217;s orbit, its rotation period, its revolving speed, the tilt angle, the temperature of the core and of the Earth&#8217;s crust, the size and composition of its atmosphere, the orientation of the magnetic poles and the strength of the electromagnetic shielding, and so on.<br /> It is expected that, for the next couple of thousands years or more, the human race won&#8217;t control the complexity of the previously mentioned factors.<br /> So, the following principle of local mass and energy conservation may apply:<br /> <em>The total mass of the planet and of its orbiting bodies, and the thermal energy absorbed by the planet and its atmosphere must be kept constant, as in their naturally occurring values.</em><br /> Among other things, this implies that we don&#8217;t bring space bodies from outside of the gravitational field of Earth but rather use those already caught in it, and we don&#8217;t augment the thermal dissipation on the planet&#8217;s surface with the energy produced in outer space but rather replace part of the ground production with the latter.<br /> In this context, all the plans to make the environment healthier and green remain very much valid.</p><h2>Project Zenyth</h2><p>At the beginning of the 3rd millennium, the human kind set out to build three space stations revolving around the Earth. Assembled from previously launched space vehicles, they are a precursor to the industrial ring that will provide the top-level planetary production in the 4th millennium.<br /> The stations are 120 degrees apart from one other, and describe an equatorial orbit of 8 hrs from west to east. This gives a positional speed twice of the revolving speed of Earth&#8217;s surface, i.e. less than 1 km/s.<br /> The round-trip of the electromagnetic signal between earth and a space station is below 0.1 s, which makes quasi-realtime operations with the station possible.<br /> Two space stations have the role of delivering supplemental energy to the planet, and the other copes with space mining and space facility building. Each station is able to produce energy and has robotic machinery at least at a base level.<br /> The stations have very small onboard crews commissioned on a two-year period with approved individual shore leaves. The vast majority of operations are performed by <a title="telepresence" href="#telepresence">telepresence</a> by a large number of domain specialized personnel based on earth. <em id="telepresence"> The telepresence is the process of connecting the human sensorial and volitional inputs and outputs to a combination of actuators, robotics, an AI assisted operations, within a frame of a fast perceived feedback and an automated micro-time control.</em><br /> Even from the early stages, the communication, the coordination, and the collaboration between the three space stations are both desirable and required.</p><p> </p><h2>Artemis</h2><p>Built by the Pacific Partnership which includes among others, USA, Japan, Korea and Australia, this space station transfers solar energy to the Earth using the red laser technology.<br /> By employing a series of concave mirrors and light concentrators, the station delivers several focused beams, which reach the Earth&#8217;s atmosphere with a radius below 100 m AND an infrared intensity up to 30 times the solar radiation. The beams are intermittent, with an on time of 0.3 s and an off time of 0.2 s.<br /> Between tropics, scattered all around the globe, near the shore or on the ground, are almost 200 solar plants ready to receive and utilize the concentrated light beams. A solar plant is a field of adjustable focalizing mirrors with a support layer of solar panels beneath that is spread on a 1.732 x 1.0 square km area from west to east.<br /> Depending on the atmospheric conditions, the space station chooses and gets in sync with a solar plant, and starts sending the beam bursts for about 5 minutes, when the longitudinal azimuth deviation remains under 1.5 degrees. Any perturbation on the send path or at receiving site cuts off the emission.<br /> The receiving mirror system is able to focus the beams to several vertical metallic-ceramic heat accumulators, or in the optimal case, to a single focus point, which can act as a micro-nuclear reaction enabler. The plant uses the heat to decompose the water in oxygen and hydrogen, the last being collected and slowly liquefied with micro-pumps into small tubular glass-fiber cells. Each plant has a support array of electrical accumulators for operation and maintenance.<br /> It also has 24/7 remote control and monitoring, and a third-party can load an amount of hydrogen from the plant, after receiving an unlock code from the energy provider.</p><p><em>Synopsis</em></p><p>After three hours of travel, the passengers of the regular morning flight from Atlanta to Johannesburg are awakened by a voice: &#8220;Good morning ladies and gentlemen, and sorry for the inconvenience. We are over the north-eastern cost of Brazil, but will make a small detour of half an hour because a solar plant below is just commencing its receiving activity. Please connect to your VR displays if you want to enjoy the show. This is the captain, thank you. &#8221;<br /> They can see through their VR sets something that looks like a lotus flower taken from far away. In a few moments, the lotus brightens its red petals that extend now like rays over a long distance, signaling the start of the intense activity of the solar plant. Suddenly, a red vertical lightening strikes through the skies directly to the plant and carries on making the sky red and the plant gone from sight. After a while, the eyes are becoming accustomed with what seems now a laser bombardment from an alien ship. Several long minutes pass, the bursts stop as sudden as they have started, and the small lotus appears unshattered, to the much dismay of the viewers.<br /> &#8220;How can they make sure not hitting an airplane or, even worse, a house on the coast?? &#8221; said a young lady, thinking aloud. &#8220;Dear miss&#8221; replied a gentleman upfront, &#8220;scientists developed for the space-station, what&#8217;s called a logarithmic gun whose shape allows a precision of 100 m beam landing radius, the same as if one used a 1 cm reflective pipe of 1.4 km length. &#8221;<br /> Captain&#8217;s voice is heard again: &#8220;Folks, my second notice that we can witness a very rare phenomenon: the vertical rainbow. We will descend 3000 feet at the cloud level and the windows of the plane will clear for outside view. &#8221;<br /> The last traces of sleep are gone from the faces of the kids and grownups as they rush to the right side of the plane to look on the window.<br /> As the plane goes on steady in its voyage over the Atlantic, at the far rear, it seems that someone has painted a colorful strip on a wall in the sky, shining down in light purple, yellowish orange, and pale red.</p><p> </p><h2>Lyna</h2><p>Built by the Pan-Asian Convention, which includes among others China, India, Russia and Iran, it uses the microwave technology to convert and transmit the solar energy to hovering receivers in the Earth stratosphere. The station converts high energy solar radiation into electricity, and then emits focused microwave bursts to targets in the lower stratosphere.<br /> These are large ellipsoidal balloons of 1.2 km x 0.6 km axes size, capable to easy reach and maintain above-clouds altitudes.<br /> Built from textile fibber impregnated with fireproof natural rubber, a balloon has over 90% hot air chambers and a small number of helium chambers, so that, when the air is cooled, the balloon slowly descends to the ground.<br /> In the nacelle there are electrical accumulators and circuitry that produce small high-voltage discharges that keep the air hot and slowly ionize it.<br /> On the upper side of the balloon is a mix of microwave receivers and solar panels. The receivers directly convert the microwave bursts from the space station into high-voltage discharges, greatly increasing the ionizing rate.<br /> The efficiency of the discharges may be increased by making them inside small cells where the air passed pressurized several atmospheres.<br /> From the almost 150 energy balloons, a third of them that are fully charged are landed and brought to the nearest city, where they act as a huge battery by gradually converting the gas ionization into electricity, using an elaborated energy converter in the nacelle. A third-party may retrieve the balloon, but the electricity can be accessed after receiving an unlock code from the energy provider.<br /> Each balloon has an always-on transponder which sends its precise location and realtime stats.<br />  <p><em>Synopsis</em></p><p>The sun is rising above one of the southern ports of Okinawa, where the crews of two small frigates swiftly prepare for departure on the sea.<br /> &#8220;Gentlemen &#8220;, says Yosh Nakamuro, captain of one of the two ships , &#8220;today will go hunting an e-whale, also known as an energy balloon. If we succeed, you will have less financial worries for the next three months. &#8221;<br /> One hour later, at the northern coast of Philippines, twelve electric fishing ships embark for the same mission. With the wind gently blowing from the south in their additional sails, they are confident of reaching until evening the balloon landing point in the Pacific, twice as close as from their Japanese counterparts.<br /> The day is closing to sunset, when the Filipino sailors start to see at a big distance the large behemoth slowly coming down from the air. The Japanese are almost 20 minutes behind, but Captain Nakamura communicates to the other frigate: &#8220;Our radar shows that this balloon is &#8220;landing with 10 m/s, twice as usual. This will create a splash wave 5 meters high on a 3 km radius. I recommend slowing down and aligning the ships for the impact &#8221;<br /> Five of the fishing ships are caught too close by the small tsunami and get damaged, forcing the other seven to render assistance. Closing from the opposite direction, the first frigate launches the traction and data cable guided by a coupling torpedo. As soon as the cable is coupled to the balloon&#8217;s nacelle, they enter a retrieval code and the balloon becomes definitive custody of the crew.<br /> Now begins the challenging way back home, where, after a short ceremony, they will transfer the custody of the balloon to the local authorities.</p><h2>Hera</h2><p>Built by the Mediterranean Economic Forum, which includes among others EU, UK, the Arab League and the African Confederation for Progress, the station uses advanced robotics technology for spacecraft and aircraft construction and for mining nearby space bodies like asteroids or meteorites.<br /> It ships certain rare minerals and metals to the planet through the freshly built stratospheric planes, and receives retro-engine fuel for its close by space missions.<br /> The majority of the space missions are bringing the small mining fragments in a synchronous orbit to the Earth, preferably close to that of the station.<br /> The farther the space body is from the Earth, the lesser retro-engine power is required to deviate it from its trajectory.<br /> The space station accepts building and mining orders from a third-party based on commercial contracts.<br />  <p><em>Synopsis</em></p><p>It looks like a quiet and clear nightfall in the northern hemisphere, but up in the sky, the station is running a fast paced activity. A small ship launches from the station, and quickly begins a descending orbital trajectory towards the atmosphere. It has six rhombus-shaped shields facing the three orthogonal directions, coupled with six retro-engines beneath each shield.<br /> Upon entering the atmosphere, the silver ship turns red because of the friction heat, when, quite surprisingly, it gradually transforms its shape to a V-wing supersonic airplane that swiftly carries on to its destination.<br /> On the ground, in the welcoming city of Abu Dhabi, a team of European scientists and local representatives carefully supervises the arrival of the self-pilots stratospheric plane.<br /> A round of applauses is heard in the reception hall of the flight coordination agency, when the press comes in an prepares to interview the visiting and local teams.<br /> &#8220;Professor Kroner&#8221;, says Kim Min Hae, one of the reporters, &#8220;Congratulations for the success of your aero-spatial industry accomplishment. But our astronomical observers have discovered a space dock building startup 50 km east from the space station. Care to comment on this subject? &#8220;.<br /> After a short smile, Professor Peter Kroner replies: &#8220;It is a joint effort of the American, the Asian, and the European space agencies. It is in its early stage because we are still monitoring the progress of the fusion drive, electromagnetic shielding, and poly-alloy armor technologies. &#8220;. The reporter adds: &#8220;We heard that a designation and a name are already chosen for the first ship build there. &#8220;, and the scientific Team leader : responds: &#8220;She doesn&#8217;t have an official name yet, but our international colleagues and us like to call her: Enterprise. &#8220;.</p><h2>Connected to the future</h2><p>It&#8217;s a sunny afternoon in the perpetual city of Mumbai, India, where the students of the second grade of the Central High-School prepare for the two hours astronomy class. &#8220;Today we will pay a visit to the space station our country is a part of. Please put on the VR suits and join the virtual visiting group. &#8220;, says the teacher.<br /> In a few moments the landscape changes, and, in a large cabin full of monitors, they are met by a cheerful middle-aged man dressed in a ceremony uniform. &#8220;Good afternoon kids. I am Commander Alexey Markov, and, on behalf of Captain Lee Po Fang, I welcome you to our international space station. In the first part of your visit, you will enjoy the famous balloon monitoring panorama, where you can see our energy balloons colored from white for those freshly lifted to Intense orange for those fully charged, and even blue for those few that are descending. In the last part, those of you that opted in, will take a space walk with our chief engineer and a member of his team to the mobile space arm on the docking platform of the station. Just remember a simple rule for any future cosmonaut: in space there is no upside-down. As a homework, I give you the easy task of computing the total mass for a spherical air bubble of 300 m radius, given the nominal air density of 1.204 kg per cubic meter, and, 0.5236 as the volume ratio between a sphere and a cube of the same size. For those of you that come upon the right answer, fear not my children: as per the Archimedes&#8217;s law, in the atmosphere, our flying bubble is light like a bird. &#8220;.<br /> As the amazing astronomy class finishes, for some of the students, this will mark a decisive turn in their future career of becoming international specialists in the spatial operations of the human race.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/economics-of-the-future-draft/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Solidarity Grant</title><link>https://the-zonebuilder.freetzi.com/solidarity-grant/</link> <comments>https://the-zonebuilder.freetzi.com/solidarity-grant/#comments</comments> <pubDate>Wed, 10 Oct 2018 18:36:50 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[politics]]></category> <category><![CDATA[society]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=221</guid> <description><![CDATA[As described in the article &#8220;Economics of the future&#8221;, the global economy faces a major shift towards a large scale space facility building. In order to mount such an industry, not only the conjugate efforts of multiple countries or political unions are necessary, but also the individual resource of human expertise and creativity is critical. [&#8230;]]]></description> <content:encoded><![CDATA[<p>As described in the article &#8220;Economics of the future&#8221;, the global economy faces a major shift towards a large scale space facility building. In order to mount such an industry, not only the conjugate efforts of multiple countries or political unions are necessary, but also the individual resource of human expertise and creativity is critical.<br /> But, where do you find the adequate human resource when the planetary challenges become overwhelming and escalate with waiting?</p><h2>Strength in numbers</h2><p>It is known that, when dealing with a large task, a team is preferable to an individual. That applies more if the task involves qualified work or technological know-how. But, if we &#8216;are talking about the field of research, the effects of many, although more subtle, are even more decisive.<br /> Imagine that for the work of a breakthrough in cold fusion technology, a developed country can provide 100 specialists for a certain period of time, say 30 years. If the same country could provide for the same task 1,000 specialists, not only the estimated speed of research will increase 10 times, but also the probability that one of them is the future Einstein will increase accordingly. That is of course a simplified scenario, but you get the idea.</p><h2>Mawi</h2><p>In Central Africa the desert borders a savannah and a river bed that fills with water in the raining season. The inhabitants of a small village near the river move their herds of cattle along with the season changing, searching for the best pastures to ensure their living.<br /> Even when he was a ten years boy, Mawi learned from his grandpa that we should live in harmony with the nature, for everything we take we should give something back. Grandpa also said that there are unseen forces that bind all things together, and one should acknowledge and respect these forces. Among the other kids, Mawi was the first to learn to read the weather changing, to find the clues for a soil with underground water, and even learned several stars on the sky that help the traveler going to a distant place.<br /> All the villagers obeyed a strict code of honoring the traditions and gave praise to the forces of the nature that granted them a continuous existence for many generations. But Mawi felt that the unseen forces are meant to be known by the man, and he could reach deeper in understanding what the other villagers consider to be immutable.<br /> One day a group of strangers wearing long coats and sun glasses arrived into the village. They gather the kids to play a contest of keenness using some little devices that talk and show various images while held in your hand. They noticed that Mawi was very fast to learn and had a natural way of interacting with the device and decided to give it to him as a present. They spoke with the elders of the village and offered to return two years later with a proposal of scholarship for Mawi as he progresses with his learning.<br /> Twenty two years later, in North America, at the Physics and Astronomy Institute, Professor Eric Shuman, chairman of the Science Academy, opened the biennial conference on Achievements and Discovery with a speech: &#8220;We gathered here to salute the decisive step forward in setting the basis of the world spatial sustainable economy, made possible by the astounding discovery of the anti-graviton waves by our exceptional colleague Dr. Mawi Erbassa. The efficient space transportation and the orbital manufacturing in our planetary systems can finally become a daily reality &hellip;&#8221;</p><h2>Necessity or evolution?</h2><p>As seen in <a href="https://en.wikipedia.org/wiki/Maslow%27s_hierarchy_of_needs" target="_blank">the Maslow&#8217;s pyramid of needs</a>, an individual is driven by basic and higher tier needs, when it comes to describing the human behavior. But, whereas the individual needs can be identified pretty accurately, the needs of the society made of many individuals form the base of the endless political and philosophical debates throughout the history.<br /> In an age where the communication between people is quasi-instantaneous, the society is much more integrated regarding the sharing of ideas, exchange of opinions, and many other thinking related activities. One should look at the human race like as a super-organism whose needs need to be identified properly and even anticipated. An umbrella under all those needs may be gathered is the evolution of the human kind. The history of life has shown that if a species should succeed in its endeavors, it must succeed in its evolution. If we want to identify the necessities of the human race, we must anticipate its trajectory, looking especially for its future evolution. As in the pyramid of needs, the entire race will be hindered in its evolution if the basic needs of all the people will remain unmet.</p><h2>Solidarity Grant</h2><p>The definition of the solidarity grant is:<br /> <em>Each human must be granted the access to food and shelter.</em></p><h2>Implementation</h2><p>Each country or political union will build a series of modular accommodations grouped in areas called solidarity campuses.<br /> The operation of these areas will be ensured by the army or an equivalent legal organization with a strict code of conduit and good operational performance where no army is constituted. The financing and the material needs of the campuses will be ensured by the government or an equivalent legal budget ordering organization where no government is constituted. The supervising and the political responsibility for the welfare of the campuses will be ensured by the parliament or an equivalent legal representative organization where no parliament is constituted.<br /> Any person with self-responsibility may request access to the campus for a given period of time starting with one month, e.g. 1, 3, 6, 12 months, and renew the request several days before expiration. Children under 2 are allowed with their mother if present. For the other children, any person who requests a period of access and is a legal tutor of those children will agree that the state through its institutions will take care of their food, shelter and education for the same period of time.<br /> Inside the campus applies the rule of law, the human rights and the solidarity grant. Only the functions of food and shelter will be performed by the campus, other supportive functions will ultimately defeat its existence. The access will be permitted for sheltering hours like 6 hours sleeping; bad weather like under -20&deg;C or natural catastrophe decreed by law. Also the access will be allowed for three short periods of time when the food is distributed and ingested. Any personal belongings are held at the entrance and returned at exit. A person may exit any time the campus but will be allowed in only when a period of shelter or of meal begins. Also, at the end of each period the campus will be evacuated and will do maintenance tasks.<br /> The campus consists in modular living units for one person each and several service units like toilets, personnel offices, energy and communication units. Each unit has a minimal decor, is connected to a heating and energy source, has surveillance capacity and may be inspected by the operation personnel. A person will be given a random living unit which differs each time a food or shelter period begins. The food will be delivered and consumed inside these living units. Several periods can be glued together for efficiency reasons eliminating intermediary evacuations, but keeping at least two daily maintenance periods of 4 hours each. Circulation and access inside the campus will be limited and monitored. Toilets are single person nodules with washing sets included. Other than some administrative restrictions, no obligation will be created for the persons accessing the campus.</p><h2>Consequences</h2><p>Freeing the individual from the necessity of solving two of the most basic needs will contribute dramatically to the evolution of the race. The higher level needs will get much more attention, and the problem solving capacity of the global community will increase ten times. Also, the basis for more civilized and a more educated world is set with the integration in the human minds of the solidarity grant. People will soon consider a habit like washing on hands to work in a small fraction also for the need of the community which in turn will ensure their access to the solidarity grant. It is worth mentioning also that moral rights like human dignity and self-esteem will be strongly enhanced.<br /> The vectors of evolution of the human race can be changed by various events in ways not necessary positive for the future. Why not change them in a controlled way with decisive positive contribution to the human being?</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/solidarity-grant/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Advanced JUL Concepts part 2</title><link>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-2/</link> <comments>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-2/#comments</comments> <pubDate>Fri, 03 Nov 2017 17:04:08 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JUL]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=219</guid> <description><![CDATA[In the previous article we have seen that JUL can generate component trees and manage the work with configuration objects. But JUL has more cards in its sleeve when playing in the field of the configuration namespaces. Namespaces &#8211; utility &#38; relativity In JavaScript, a namespace is a global object that stores various other objects [&#8230;]]]></description> <content:encoded><![CDATA[<p>In <a title="Advanced JUL Concepts - part 1" href="/advanced-jul-concepts-part-1/">the previous article</a> we have seen that JUL can generate component trees and manage the work with configuration objects.<br /> But JUL has more cards in its sleeve when playing in the field of the configuration namespaces.</p><h3>Namespaces &#8211; utility &amp; relativity</h3><p>In JavaScript, a namespace is a global object that stores various other objects and functions. Historically, namespaces were used to allow a non-conflicting existence of several libraries or JavaScript tools in the same runtime environment (web page). By using namespaces, authors achieved not only the clear non-polluting use of the global scope, but also the inherent organizing structure of their utilities. Most recently, the role of managing the loading and using the JavaScript libraries into an environment was taken by the modules, with the CommonJS in Node being the most relevant example. Some say that, with the advent of the module pattern, namespaces are obsolete, but namespaces mean structure, and structure is never obsolete.<br /> JUL offers several utilities for working with namespaces: JUL.ns(), JUL.get(), JUL.Instance().<br /> If you want to create an object into a given namespace, even when the namespace doesn&#8217;t exist, you can use JUL.ns().<br /> If you want to retrieve an object by its path in the global scope (the succession of property names separated by dots), you can use JUL.get().</p><pre class="brush:js">// creating a namespace
var oNS = JUL.ns('@.non-standard.tools &amp; libs');
JUL.apply(oNS, {
	setting1: 'Custom NS',
	setting2: ['first', 'second', 'third'],
	method1: function() {
		console.log('Method 1');
	}
});
// retrieving a namespace member
console.log(JUL.get('@.non-standard.tools &amp; libs.setting2.2'));</pre><p>But namespaces are not necessarily linked to the global scope (absolute), they being able to be used relative to a local scope.<br /> The most powerful scoping of the namespace usage is given by the JUL.Instance() class, which makes all the namespacing operations, like JUL.get() or JUL.ns(), relative to a base (root) namespace. For any parsers and references created by JUL, one can use JUL.getInstance() utility to get the actual instance that created the object.</p><pre class="brush:js">var sNS = '#.non-standard.~tools~';
var oLocal = {};
// creating a relative namespace
var oNS = JUL.ns(sNS, {}, oLocal);
JUL.apply(oNS, {
	property1: {x: 5, y: 3},
	property2: /^new/i,
	'a-method': function() {
		console.log('A method');
	}
});
// getting a relative namespace member
var fCall = JUL.get(sNS + '.a-method', oLocal);
fCall();
// creating a JUL instance bound to a a namespace
var jul = new JUL.Instance({nsRoot: oNS});
console.log(jul.get('property1.x'));
// getting an implicit instance
var oParser = new JUL.UI.Parser({
	nsRoot: oNS,
	yopDown: true,
	useTags: true
});
console.log(JUL.getInstance(oParser).get('property2'));</pre><h3>Method retrieving and scoping</h3><p>Several JUL utilities like JUL.factory() or JUL.UI.createDom() accept a dotted path where a function / callback is expected. Internally, this path is resolved to the actual object using JUL.get().</p><pre class="brush:js">var oTree = {
	tag: 'div',
	css: 'wrapper',
	children: [
		{tag: 'input', id: 'input-name', value: 'A text', listeners: {change: 'NS.lib.defaultChange'}},
		{tag: 'button', id: 'button-go', html: 'Go', listeners: {click: 'NS.lib.defaultClick'}}
	]
};
var oParser = new JUL.UI.Parser({
	defaultClass: 'html',
	customFactory: 'JUL.UI.createDom',
	topDpwm: true,
	useTags: true
});
var oNS = JUL.ns('NS.lib');
JUL.apply(oNS, {
	defaultClick: function() {
		console.log('Button clicked');
	},
	defaultChange: function() {
		console.log('Text changed');
	}
});
oParser.create(oTree, null, window.document.body);</pre><p>This allows a configuration object to store un-resolved callbacks by the time of their loading. But, if you want the desired callbacks to be called in a given scope, you can use JUL.makeCaller() to create a cached wrapper for a given function with a fixed scope (analogous to ES5 Function.prototype.bind()). When attaching listeners to a DOM element, JUL.UI.createDom() does the binding automatically if you provide a scope property in the listeners config object.</p><pre class="brush:js">var oTree = {
	tag: 'div',
	css: 'wrapper',
	children: [
		{tag: 'input', id: 'input-name', value: 'A text', listeners: {scope: 'NS.lib', change: 'NS.lib.defaultChange'}},
		{tag: 'button', id: 'button-go', html: 'Go', listeners: {scope: 'NS.lib', click: 'NS.lib.defaultClick'}}
	]
};
var oParser = new JUL.UI.Parser({
	defaultClass: 'html',
	customFactory: 'JUL.UI.createDom',
	topDpwm: true,
	useTags: true
});
var oNS = JUL.ns('NS.lib');
JUL.apply(oNS, {
	clickMsg: 'Button clicked',
	changeMsg: 'Text changed',
	defaultClick: function() {
		console.log(this.clickMsg);
	},
	defaultChange: function() {
		console.log(this.changeMsg);
	}
});
oParser.create(oTree, null, window.document.body);</pre><h3>Dotted path escaping</h3><p>When using the namespace path string (dotted oath) to retrieve an object, there are several things to take care of.<br /> Each path segment describes an object property string, so it can have a much wider format than the strings for variable names or array indexes. A single separator (i.e. a dot) will be used to separate two segments of the path, and the path can be used to traverse any configuration objects, including arrays.<br /> To cover all use cases, JUL offers an escape syntax for a dotted path, where all dots present in a property string are preceded by a backslash when used inside the path.<br /> All JUL routines that use dotted oaths, like JUL.ns() or JUL.get(), support this syntax.</p><pre class="brush:js">var oNS = JUL.ns('NS.dotted\\.segment');
JUL.apply(oNS, {
	property: {a: 'A', b: 'B', c: 'C'},
	'dotted.method': function() {
		console.log('Dotted access');
	}
});
var fCall = JUL.get('NS.dotted\\.segment.dotted\\.method');
fCall();</pre><h3>JSON replacers and JSON prefixes</h3><p>One of the goals of JUL is the reliable serialization of the configuration objects. To achieve this, JUL converts them to an intermediate extended JSON format, before generating the final JavaScript code string.<br /> The place to control how the generated JSON looks is JUL.UI._jsonReplacer callback, which acts as the JSON.stringify() second parameter. Inside this, the user can change what objects get strigified by JUL and how they will look. By default, besides the standard JSON types, JUL is able to serialize: functions, regex objects, date objects. In addition, it&#8217;s easy to output any known constructor based objects by prefixing their call with the &#8216;new&#8217; keyword.</p><pre class="brush:js">// a constructor that stores copy of an object
var Store = function(oConfig) {
	this._config = JUL.aply({}, oConfig);
};
Store.prototype.serialize = function() {
	return JUL.UI.obj2str(this._config);
};
// a custom parser that can serialize Store objects
var oParser = new JUL.UI.Parser({
	_jsonReplacer: function(sKey, oValue) {
		if (oValue instanceof Store) {
			return 'new Store(' + oValue.serialize() + ')';
		}
		else {
			return JUL.UI._jsonReplacer(sKey, oValue);
		}
	}
});
// output the JSON form of a mixed config object
var oConfig = {
	dates: [new Date(), new Date() + 144000e3, new Date() + 288000e3],
	regexs: {begin: /^\s+/, end: /\s+$/},
	'a-method': function() {
		console.log('A method');
	},
	'a-store': new Store({
		item1: 'An item',
		item2: [0, 2, 4],
		item3: /(red|green|blue)/
	})
};
console.log(oParser.obj2str(oConfig, true));</pre><p>While the generated strings have a format correlated with their types, one cannot unequivoquely infer that a string with the same format is obtained from a serialized object. For the more advanced cases, when the control over the generated code is stricter, JUL offers the JSON prefixes concept.<br /> A JSON prefix is a unique string that precedes the serialized string of a given type of object.<br /> The JSON prefixes are activated by the JUL.UI._usePrefixes property and are stored in JUL.UI._jsonPrefixes hash (object). By default, they are: the prefix for functions, the prefix for regex syntax, the prefix for the &#8216;new&#8217; construct, but they can be added or changed as needed. The prefixes only appear in the JSON serialized form of a config tree, but not in the JavaScript serialized form, where the code is directly runable.</p><pre class="brush:js">var oConfig = {
	xclass: 'FWK.Dialog',
	autoCenter: true,
	avatar: /(hat|suit|shirt)/i,
	validity: [new Date(Date.UTC(2017, 10, 3)), new Date(Date.UTC(2018, 10, 3))],
	listeners: {
		done: function(bQuit) {
			if (bQuit) {
				this.close();
			}
		},
		show: function(nLeft, nTop) {
			this.drawAt(nLeft, nTop);
		}
	}
};
var oParser = new JUL.UI.Parser({
	_usePrefixes: true,
	_tabString: '    '
});
console.log(oParser.obj2str(oConfig, true));</pre><h3>Code references and decorators</h3><p>There are cases when we need to output a specific code section, that cannot be stored as a configuration object. A recurring example is outpouring other globally namespaced JavaScript tools or libraries that are loaded before the configuration loads.<br /> JUL.UI.obj2str() serialization tool identifies these code strings using JUL.UI.referencePrefix, and outputs them unquoted regardless of the JSON replacer and JSON prefixes settings.</p><pre class="brush:js">var oConfig = {
	tag: 'div',
	id: 'panel-tools',
	css: 'blue-panel',
	'data-control': 'Test.UI.Panel',
	'data-options': {
		instantiator: '=ref: Test.ContainerBase',
		bounding: [0, 0, 400, 200]
	}
};
var oParser = new JUL.UI.Parser({
	defaultClass: 'html',
	customFactory: 'JUL.UI.createDom',
	topDown: true,
	useTags: true
});
console.log(oParser.obj2str(oConfig));
// JUL.UI.createDom() also obeys code references in the element attributes
oParser.create(oConfig, null, window.document.body);</pre><p>Taking a closer look at JUL.UI.obj2str() method, we notice that we can change the resulting JavaScript code as we traverse the JSON string. JUL uses these access points to insert custom code before the keys of the serialized object. The first use case of these code segments, called code decorators, is for inserting comment blocks for documenting, like e.g. JCS (JUL Comment System) does.</p><pre class="brush:js">var oConfig = {
	property1: 'First name',
	property2: ['a', 'b', 'c'],
	metod1: function() {
		console.log('Method 1');
	}
};
var fDecorator = function(sContent, sPath, sIndent) {
		if (!sPath) { return sContent; }
		var nParts = sPath.split('.').length;
		if (nParts &gt; 1) { return sContent; }
		var oRef = JUL.get(sPath, this);
		var sText = '/**' + '\n' + sIndent + ' * ';
		switch (typeof oRef) {
		case 'function':
			sText = sText + 'Method description';
		break;
		default:
			sText = sText + 'Property description';
		}
		sText = sText + '\n' + sIndent + ' */';
		sText = sText + '\n' + sIndent + sContent;
		return sText;
};
var oParser = new JUL.UI.Parser();
console.log(oParser.obj2str(oConfig, false, fDecorator));</pre><h3>Members collections extensibility</h3><p>In order to parse a configuration tree, JUL must know what members of a config object are representing child component configs. This kind of information is given by the JUL.UI.childremProperty and by the JUL.UI.membersProperties of the parser. The JUL.UI.childrenProperty is a main property, while the JUL.UI.membersProperties array may contain additional names of other direct descendant members, and these members can be reduced to a &#8216;unified&#8217; form using JUL.UI.expand(). After expanding, the only children member will be that of the JUL.UI.childrenProperty value.<br /> But, there are cases when the members / children properties of a config object depend on the component class of that config. For these cases JUL offers the &#8216;JUL.UI.membersMappings hash that associates members arrays to the class names. Even more, if a config object has a special property given by the JUL.UI.instantiateProperty value, the parser takes that members property into account when parsing the respective object.</p><pre class="brush:js">var oTree = {
	xclass: 'Dialog',
	title: 'Title',
	content: [
		{xclass: 'BorderLayout', top: [
			{xclass: 'BorderLayoutArea', content: [
				{xclass: 'MenuBar', items: [
					{xclass: 'MenuItem', text: 'Menu 1', submenu: [
						{xclass: 'Menu', items: [
							{xclass: 'MenuItem', text: 'Submenu 1'}
						]}
					]},
					{xclass: 'MenuItem', text: 'Menu 2', submenu: [
						{xclass: 'Menu', items: [
							{xclass: 'MenuItem', enabled: false, text: 'Submenu 2'}
						]}
					]}
				]},
				{xclass: 'Toolbar', items: [
					{xclass: 'TextField', value: 'Value'},
					{xclass: 'Button', text: 'Button'}
				]}
			]}
		],
		begin: {
			xclass: 'BorderLayoutArea', content: [
				{xclass: 'ListBox'}
			]
		},
		center: {
			xclass: 'BorderLayoutArea', content: [
				{xclass: 'HTML', content: 'Content'}
			]
		}}
	]
};
var oParser = new JUL.UI.Parser({
	childrenProperty: 'items',
	membersMappings: {
		BorderLayout: ['top', 'bottom', 'begin', 'end', 'center'],
		BorderLayoutArea: 'content',
		Dialog: ['content', 'buttons'],
		MenuItem: 'submenu'
	},
	customFactory: function(oConfig) {
		console.log('Creating ' + oConfig.xclass);
		return oConfig;
	}
});
oParser.create(oTree);</pre><p>JUL also has a &#8216;sparse&#8217; mode, where the parser tries to traverse any child object of the current config to search for descendant configs to instantiate. In this mode, which is triggered by the fourth argument of JUL.UI.create() method, there is no default class assumed for an object that doesn&#8217;t have the class property set. In the sparse mode, any objects that are not component configs, will be copied to the output objects / instances with the sane membership structure.</p><h3>Conclusion</h3><p>Using JUL you can control many aspect of the configuration trees and their instantiation into components. This applies to the UI creation tasks, but not only to those. In fact, JUL aims to be a base for the rapid application development of a web application.<br /> The philosophy that lies behind JUL and its tool set is that <em>one should not pay to be able to express his or her positive creativity</em>.<br /> The platform that offers a free and public access to such a development is the JavaScript language. That, together with its client and server utilities, is a truly universal programming language, surpassing the obstacles faced by other free languages when they built upon a proprietary code.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Advanced JUL Concepts &#8211; part 1</title><link>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-1/</link> <comments>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-1/#comments</comments> <pubDate>Wed, 31 May 2017 18:47:34 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JUL]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=204</guid> <description><![CDATA[Defining a configuration tree for building a user interface is one of the easiest and straightest ways of rapidly developing a modern web application. JUL uses this configuration tree to create component instances and to assign parent-child membership in a controlled and automated sequence. Recap of layout and logic separation There are two properties of [&#8230;]]]></description> <content:encoded><![CDATA[<p>Defining a configuration tree for building a user interface is one of the easiest and straightest ways of rapidly developing a modern web application.<br /> JUL uses this configuration tree to create component instances and to assign parent-child membership in a controlled and automated sequence.</p><h3>Recap of layout and logic separation</h3><p>There are two properties of a configuration object that allow splitting the layout and the logic associated with that configuration:</p><ol><li>The id property &#8211; it uniquely identifies a component. Using this property, we can simplify a configuration tree into a layout tree-like configuration and a key-value mapping with additional configuration for the nodes of the tree. The keys in this second part (configuration logic) are the id values. Because the logic part is a keyed mapping object, all keys (i.e. component ids) must be unique inside it. It should be added that the id property will get passed to the actual configuration object when instantiating the component.<pre class="brush:js">var oConfig = {
	xclass: 'MyApp.widgets.Avatar',
	id: 'avatar-one',
	children: [
		{xclass: 'MyApp.widgets.Hat', id: 'hat-two'},
		{xclass: 'MyApp.widgets.Suit', id: 'suit-three'}
	]
};
var oLogic = {
	'avatar-one': {
		userId: 121,
		thumbnail: 'face1.png',
		onHover: function() {
			console.log('Avatar hint');
		}
	},
	'hat-two': {
		color: 'blue',
		size: 4
	},
	'suit-three': {
		color: 'green',
		match: /(office|meeting|trip)/
	}
};
var oParser = new JUL.UI.Parser();
var oAvatar = oParser.create(oConfig, oLogic);
// the resulting runtime calls are the equivalent of:
var oHat = new MyApp.widgets.Hat({
	id: 'hat-two',
	color: 'blue',
	size: 4
});
var oSuit = new MyApp.widgets.Suit({
	id: 'suit-three',
	color: 'green',
	match: /(office|meeting|trip)/
});
oAvatar = new MyApp.widgets.Avatar({
	id: 'avatar-one',
	children: [oHat, oSuit],
	userId: 121,
	thumbnail: 'face1.png',
	onHover: function() {
		console.log('Avatar hint');
	}
});</pre></li><li>The binding id &#8211; it serves the same scope as the id property but with several differences. The binding property is deleted after aggregating the layout and the logic parts. This property may also be an array, in that case the additional configurations referred by its elements being applied sequentially in the final configuration. Such an array is built automatically if using JUL.UI.include() method (see the <a title="API reference" href="https://zonebuilder.github.io/jul/docs/index.html" target="_blank">API reference</a>).<pre class="brush:js">var oConfig = {
	xclass: 'MyApp.widgets.Avatar',
	id: 'the-avatar',
	cid: 'c-avatar',
	children: [
		{xclass: 'MyApp.widgets.Hat', cid: 'c-hat'},
		{xclass: 'MyApp.widgets.Suit', cid: 'c-suit'}
	]
};
var oLogic = {
	'c-avatar': {
		userId: 121,
		thumbnail: 'face1.png',
		onHover: function() {
			console.log('Avatar hint');
		}
	},
	'c-hat': {
		color: 'blue',
		size: 4
	},
	'c-suit': {
			color: 'green',
		match: /(office|meeting|trip)/
}
};
var oParser = new JUL.UI.Parser();
var oAvatar = oParser.create(oConfig, oLogic);
// the resulting runtime calls are the equivalent of:
var oHat = new MyApp.widgets.Hat({
	color: 'blue',
	size: 4
});
var oSuit = new MyApp.widgets.Suit({
	color: 'green',
	match: /(office|meeting|trip)/
});
oAvatar = new MyApp.widgets.Avatar({
	id: 'the-avata',
	children: [oHat, oSuit],
	userId: 121,
	thumbnail: 'face1.png',
	onHover: function() {
		console.log('Avatar hint');
	}
});</pre></li></ol><h3>Advanced composition and inheritance</h3><p>Putting configuration objects into the tree is the simplest form of building the UI layout. But, with the help of the binding id and of the JUL.UI.include() method, the parser can combine component configurations in advanced ways.</p><ol><li>The first method is including a simpler configuration object into a more complex one. The process is split into two parts: including the base config into the destination layout and including the logic part of the base config into the configuration logic of the current config. Then, we can repeat this process of augmenting (extending) a configuration object as many times as we need. An example of this method is given below.<pre class="brush:js">var MyApp = {
	config: {},
	objects: {},
	version: '1.0'
};
MyApp.config.shapeUi = {
	xclass: 'MyLib.Shape',
	cid: 'mylib.shape',
	origin: {x: 0, y: 0}
};
MyApp.config.shapeLogic = {
	'mylib.shape': {
		color: 'grey',
		bgColor: 'white',
		getOrigin: function() {
			console.log('Shape origin');
		}
	}
};
MyApp.config.polygonUi = {
	include: MyApp.config.shapeUi,
	xclass: 'MyLib.Polygon',
	cid: 'mylib.polygon',
	corners: 0,
	sizes: []
};
MyApp.config.polygonLogic = {
	include: MyApp.config.shapeLogic,
	'mylib.polygon': {
		getArea: function() {
			console.log('Polygon area');
		}
	}
};
MyApp.config.triangleUi = {
	include: MyApp.config.polygonUi,
	xclass: 'MyLib.Triangle',
	cid: 'mylib.triangle',
	corners: 3,
	sizes: [3, 4, 5]
};
MyApp.config.triangleLogic = {
	include: MyApp.config.polygonLogic,
	'mylib.triangle': {
		draw: function() {
			console.log('Triangle draw');
		},
		getArea: function() {
			console.log('Triangle area');
		}
	}
};
var oParser = new JUL.UI.Parser();
MyApp.objects.triangle = oParser.create(MyApp.config.triangleUi, MyApp.config.triangleLogic);
// the resulting runtime calls are the equivalent of:
MyApp.objects.triangle = new MyLib.Triangle({
	origin: {x: 0, y: 0},
	corners: 3,
	sizes: [3, 4, 5],
	color: 'grey',
	bgColor: 'white',
	getOrigin: function() {
		console.log('Shape origin');
	},
	getArea: function() {
		console.log('Triangle area');
	},
	draw: function() {
		console.log('Triangle draw');
	}
});</pre><p>This kind of augmentation is called explicit inheritance as opposed to the prototypal or class based inheritance which we call implicit inheritance. Although we could use an implicit inheritance for extending a component configuration, JUL uses explicit inheritance in order to ensure a reliable serialization of the configuration objects. Because JUL.UI.obj2str() uses JSON internally to serialize the objects, a prototypal based inheritance would complicate the serialization process, given the differences in object prototypes across different runtime environments.</li><li>The second method is inserting several base configurations in various points into the configuration tree, i.e. the component composition. The process consists in referring the base configs with include property of the given node and adding the base config logic to the include array of the destination logic mapping. An example of such a process is given below.<pre class="brush:js">var MyApp = {
	config: {},
	objects: {},
	version: '1.0'
};
MyApp.config.circleUi = {
	xclass: 'MyLib.Circle',
	cid: 'mylib.circle',
	origin: {x: 0, y: 0},
	diameter: 1
};
MyApp.config.circleLogic = {
	'mylib.circle': {
		fillColor: 'white',
		draw: function() {
			console.log('Draw circle');
		}
	}
};
MyApp.config.rectangleUi = {
	xclass: 'MyLib.Rectangle',
	cid: 'mylib.rectangle',
	origin: {x: 0, y: 0},
	dimensions: {w: 0, h: 0},
};
MyApp.config.rectangleLogic = {
	'mylib.rectangle': {
		fillColor: 'blue',
		draw: function() {
			console.log('Draw rectangle');
		}
	}
};
MyApp.config.logoUi = {
	include: MyApp.config.rectangleUi,
	id: 'the-logo',
	dimensions: {w: 10, h: 7},
	children: [
		{include: MyApp.config.rectangleUi, id: 'inner-area', origin: {x: 1, y: 1},
		 dimensions: {w: 8, h: 5}, children: [
			{include: MyApp.config.circleUi, id: 'left-disc', origin: {x: 2, y: 2}, diameter: 3},
			{include: MyApp.config.circleUi, id: 'right-disc', origin: {x: 2, y: 5}, diameter: 3}
		]}
	]
};
MyApp.config.logoLogic = {
	include: [MyApp.config.circleLogic, MyApp.config.rectangleLogic],
	'the-logo': {
		draw: function() {
			console.log('Draw logo');
		}
	},
	'inner-area': {
		fillColor: 'yellow'
	},
	'left-disc': {
		fillColor: 'red'
	},
	'right-disc': {
		fillColor: 'green'
	}
};
var oParser = new JUL.UI.Parser();
MyApp.objects.logo = oParser.create(MyApp.config.logoUi, MyApp.config.logoLogic);
// the resulting runtime calls are the equivalent of:

var oLeft = new MyLib.Circle({
	id: 'left-disc',
	origin: {x: 2, y: 2},
	diameter: 3,
	fillColor: 'red',
	draw: function() {
		console.log('Draw circle');
	}
});
var oRight = new MyLib.Circle({
	id: 'right-disc',
	origin: {x: 2, y: 5},
	diameter: 3,
	fillColor: 'green',
	draw: function() {
		console.log('Draw circle');
	}
});
var oInner = new MyLib.Rectangle({
	id: 'inner-area',
	origin: {x: 1, y: 1},
	dimensions: {w: 8, h: 5},
	children: [oLeft, oRight],
	fillColor: 'yellow',
	draw: function() {
		console.log('Draw rectangle');
	}
});
MyApp.objects.logo = new MyLib.Rectangle({
	id: 'the-logo',
	origin: {x: 0, y: 0},
	dimensions: {w: 10, h: 7},
	children: [oInner],
	fillColor: 'blue',
	draw: function() {
		console.log('Draw logo');
	}
});</pre><p>The component composition may be combined with the explicit inheritance to get complex inclusions of the configuration trees.</li><li>The third method is building a new component using a constructor function to aggregate the component configuration into a component instance. This method may use the previous two methods to build the component configuration and then it calls the JUL parser to create the component instance inside the constructor function. An example is given below.<pre class="brush:js">var MyApp = {
	config: {},
	objects: {},
	widgets: {},
	vesrsion: '1.0'
};
MyApp.config.logoUi = {
	xclass: 'MyLib.Ellipse',
	cid: 'c-logo',
	dimensions: {dx: 18, dy: 12},
	children: [
		{xclass: 'MyLib.Triangle', cid: 'c-inner', origin: {x: 8, y: 1},
		 sizes: [7, 7, 7], children: [
			{xclass: 'MyLib.Circle', cid: 'c-center', origin: {x: 4, y: 2}, diamerer: 4}
		]}
	]
};
MyApp.config.logoLogic = {
	'c-logo': {
		fillColor: 'green',
		Draw: function() {
			console.log('Draw logo');
		}
	},
	'c-inner': {
		fillColor: 'red',
		draw: function() {
			console.log('draw inner');
		}
	},
	'c-center': {
		fillColor: 'blue',
		draw: function() {
			console.log('Draw center');
		}
	}
};
MyApp.parser = new JUL.UI.Parser();
MyApp.widgets.Logo = function(oConfig) {
	var oApplied = {include: MyApp.config.logoUi};
	JUL.apply(oApplied, oConfig || {});
	var oAppliedLogic = {include: MyApp.config.logoLogic};
	var sId = oApplied.id || oApplied.cid;
	if (!sId) {
		sId = 'a-random-id';
		oApplied.cid = sId;
	}
	oAppliedLogic[sId] = {};
	JUL.apply(oAppliedLogic[sId], oConfig || {});
	delete oAppliedLogic[sId].xclass;
	delete oAppliedLogic[sId].id;
	delete oAppliedLogic[sId].cid;
	oApplied.xclass = MyApp.config.logoUi.xclass || MyApp.parser.defaultClass;
	return MyApp.parser.create(oApplied, oAppliedLogic);
};
MyApp.config.ui = {
	xclass: 'MyLib.Rectangle',
	id: 'the-ui',
	dimensions: {w: 22, h: 16},
	children: [
		{xclass: 'MyApp.widgets.Logo', id: 'the-logo', origin: {x: 2, y: 2}}
	]
};
MyApp.config.logic = {
	'the-ui': {
		fillColor: 'green',
		show: function() {
			console.log('Show UI');
		}
	},
	'the-logo': {
		fillColor: 'yellow'
	}
};
MyApp.objects.ui = MyApp.parser.create(MyApp.config.ui, MyApp.config.logic);
// the resulting runtime calls are the equivalent of:
var oCenter = new MyLib.Circle({
	origin: {x: 4, y: 2},
	diamerer: 4,
	fillColor: 'blue',
	draw: function() {
		console.log('Draw center');
	}
});
var oInner = new MyLib.Triangle({
	origin: {x: 8, y: 1},
	sizes: [7, 7, 7],
	children: [oCenter],
	fillColor: 'red',
	draw: function() {
		console.log('draw inner');
	}
});
var oLogo = new MyLib.Ellipse({
	id: 'the-logo',
	origin: {x: 2, y: 2},
	dimensions: {dx: 18, dy: 12},
	children: [oInner],
	fillColor: 'yellow',
	Draw: function() {
		console.log('Draw logo');
	}
});
// next call will return the previous oLogo object
new MyApp.widgets.Logo({
	id: 'the-logo',
	origin: {x: 2, y: 2},
	fillColor: 'yellow'
});
MyApp.objects.ui = new MyLib.Rectangle({
	id: 'the-ui',
	dimensions: {w: 22, h: 16},
	children: [oLogo],
	fillColor: 'green',
	show: function() {
		console.log('Show UI');
	}
});</pre><p>For a standard way to encapsulate complex elements into a component, please consult the <a title="JWL Library" href="https://sourceforge.net/projects/jwl-library/" target="_blank">JWL Library</a> project page.</li></ol><h3>Parser circular inheritance and meta-initialization</h3><p>A JUL parser is an instance of JUL.UI.Parser() and inherits automatically all JUL.UI members. But the parser itself has a method called Parser() which can be used to build a new parser derived from the current one. The Parser() method accepts as a parameter a configuration object whose members may override the inherited members of the parser. Furthermore, changing an inherited member from one of the ancestor parents (e.g. JUL.UI object) will reflect in all descendant parsers where that member is not overridden. We call that circular inheritance.<br /> The JUL parser is set in action when calling its create() method, which in turn uses the configuration layout and logic objects to build a component tree. Typically, for each node in the layout config, the parser creates a component using the parser&#8217;s members like the class property, the children property, the id property, and so on, as meta-information. But if the currently processed node has a special property &#8211; called by default &#8216;parserConfig&#8217;, the parser starts a new derived parser based on that property to build that branch of the configuration tree. We call that parser meta-initialization.</p><pre class="brush:js">// derive a parser from the base class
var oXmlParser = new JUL.UI.Parser({
	defaultClass: 'xml',
	useTags: true,
	topDown: true
});
// derive a parser from the previous one
var oHtmlParser = new oXmlParser.Parser({
	defaultClass: 'html',
	customFactory: 'JUL.UI.createDom'
});
// set a property for the base class and all the parsers where the property is not overridden
JUL.UI.childrenProperty = 'childNodes';
// create a configuration for a mixed DOM tree
var oConfig = {
	tag: 'div',
	css: 'svg-wrap',
	childNodes: [
		{tag: 'h3', html: 'A SVG image'},
		{tag: 'div', css: 'svg-img', childNodes: [
			{
				// the next meta-info property will auto-derive a new parser for this config branch 
				parserConfig: {defaultClass: 'svg', childrenProperty: 'nodes'},
				tag: 'svg',
				width: 100,
				height: 100,
				viewBox: '0 0 100 100',
				nodes: [
					{tag: 'circle', cx: 50, cy: 50, r: 48, fill: 'none', stroke: '#000'},
		  			{tag: 'path', d: 'M50,2a48,48 0 1 1 0,96a24 24 0 1 1 0-48a24 24 0 1 0 0-48'},
		  			{tag: 'circle', cx: 50, cy: 26, r: 6},
		  			{tag: 'circle', cx: 50, cy: 74, r: 6, fill: '#FFF'}
		  		]
			}
		]}
	]
};
// create the DOM tree and attach it to the body element
oHtmlParser.create(oConfig, null, document.body);</pre><pre class="brush:html">&lt;!-- generated DOM --&gt;
&lt;div class="svg-wrap"&gt;
	&lt;h3&gt;A SVG image&lt;/h3&gt;
	&lt;div class="svg-img"&gt;
		&lt;svg:svg width="100" height="100" viewBox="0 0 100 100"&gt;
			&lt;svg:circle cx="50" cy="50" r="48" fill="none" stroke="#000"/&gt;
			&lt;svg:path d="M50,2a48,48 0 1 1 0,96a24 24 0 1 1 0-48a24 24 0 1 0 0-48"/&gt;
			&lt;svg:circle cx="50" cy="26" r="6"/&gt;
			&lt;svg:circle cx="50" cy="74" r="6" fill="#FFF"/&gt;
		&lt;/svg:svg&gt;
	&lt;/div&gt;
<code>&lt;/div&gt;
</code></pre><h3>Reliable serialization and XML to JUL conversion</h3><p>Other than building components from a configuration tree, JUL aims to persistently store and retrieve the configuration objects (i.e. serialization). The safest way to do this is to produce the JavaScript code that will build the desired config object at runtime. To fulfill this goal, JUL uses an extended serialization based on the JSON standard. In addition to the JSON rules, JUL is able to serialize several native JavaScript types like Function, RegExp, Date, or custom types with the help of the JUL.UI._jsonReplacer() utility. The target of the serialization can be either JavaScript or JSON code, but the goal is to produce equivalent JavaScript code no matter where the serialization is run. We call this reliable serialization, i.e. the process where the conversion of the configuration object produces the same runtime effect (equivalent code) when the resulting code is executed. The actual code may differ in line breaks, white spaces, floats or date formatting, but it will always get the same effects at runtime. As a side note, the serialization doesn&#8217;t imply that the serialized form should be the same as the object being serialized, although that is the goal for the configuration objects. Keep in mind that the runtime object may have different prototypal members or enhanced functionality depending on the environment the code is run in. But, JUL config objects don&#8217;t depend on prototypes and are used just to read the configuration stored in their members. More details about the serialization can be found in the JUL.UI.obj2str() method reference.</p><pre class="brush:js">var oConfig = {
	firstString: 'First\t\x22string\x22\t',
	secondString: "Second 'string'\n",
	firstNumber: parseFloat(Math.PI.toFixed(4)),
	secondNumber: 1.2e4,
	dates: {
		first: new Date(Date.UTC(2020, 5, 1)),
		second: '2030-02-10T15:00:30Z'
	},
	matches: [
		/(one|two|three)\s+times/i,
		new RegExp('&lt;h1[\\s\\S]+?\/h1&gt;', 'g')
	],
	events: [
		{name: 'click', handler: "function(oEvent) {\n\tconsole.log(oEvent.type + ' triggered');\n}"},
		{name: 'change', handler: [
			function(oEvent) {
				console.log('Before ' + oEvent.type + ' triggered');
			},
			function(oEvent) {
				console.log('After ' + oEvent.type + ' triggered');
			}
		]}
	]
};
var oParser = new JUL.UI.Parser();
console.log(oParser.obj2str(oConfig));
// previous line produces the following JavaScript code in all major runtime environments:
oConfig = {
	firstString: 'First\t"string"\t',
	secondString: 'Second \'string\'\n',
	firstNumber: 3.1416,
	secondNumber: 12000,
	dates: {
		first: new Date(/*Mon, 01 Jun 2020 00:00:00 GMT*/1590969600000),
		second: new Date(/*Sun, 10 Feb 2030 15:00:30 GMT*/1896966030000)
	},
	matches: [/(one|two|three)\s+times/i, /&lt;h1[\s\S]+?\/h1&gt;/g],
	events: [
		{name: 'click', handler: function(oEvent) {
			console.log(oEvent.type + ' triggered');
		}},
		{name: 'change', handler: [function(oEvent) {
			console.log('Before ' + oEvent.type + ' triggered');
		},
		function(oEvent) {
			console.log('After ' + oEvent.type + ' triggered');
		}]}
	]
};</pre><p>Another feature of JUL is the conversion from XML based languages to JUL config objects. This is done by the JUL.UI.xml2jul() method which transforms a XML tree (or source code) into a JUL config tree (or the equivalent source code). The conversion takes into account the meta-information of the current parser. To see it in action, please visit the <a title="XML2JUL" href="https://zonebuilder.github.io/jul/examples/xml2jul.html" target="_blank">XML2JUL</a> online example.</p><h3>The custom factory</h3><p>When building components from the configuration object, JUL aggregates the layout and the logic configs into a runtime configuration object for each component to be built. By default, the runtime config is passed to a constrictor function located by the dotted path stored in the class property of that config. There is also a default class property which applies for the nodes where the class property is not specified.<br /> But the user can change this behavior by setting a custom factory callback at the JUL.UI.customFactory property which will receive the computed runtime configuration. A typical example of such a callback is JUL.UI.createDom() method that can build several types of DOM elements (HTML, SVG, XUL, etc.) depending on the browser support.</p><pre class="brush:js">// using JUL custom factory to build a XUL window
var oConfig = {
	tag: 'window',
	id: 'window-main',
	height: 450,
	hidden: true,
	title: 'JUL News Reader',
	width: 720,
	children: [
		{tag: 'toolbox', children: [
			{tag: 'menubar', children: [
				{tag: 'toolbargrippy'},
				{tag: 'menu', label: 'File', children: [
					{tag: 'menupopup', children: [
						{tag: 'menuitem', id: 'menuitem-exit', label: 'Exit'}
					]}
				]},
				{tag: 'menu', label: 'View', children: [
					{tag: 'menupopup', children: [
						{tag: 'menuitem', id: 'menuitem-show-articles', checked: true, label: 'Show articles', type: 'checkbox'}
					]}
				]},
				{tag: 'menu', label: 'Options', children: [
					{tag: 'menupopup', children: [
						{tag: 'menuitem', id: 'menuitem-autorefresh', label: 'Autorefresh every minute', type: 'checkbox'}
					]}
				]}
			]}
		]},
		{tag: 'hbox', children: [
			{tag: 'spacer', width: 7},
			{tag: 'label', control: 'textbox-url', value: 'Address'},
			{tag: 'spacer', width: 7},
			{tag: 'textbox', id: 'textbox-url', flex: 1, value: 'http://feeds.skynews.com/feeds/rss/technology.xml'},
			{tag: 'spacer', width: 5},
			{tag: 'button', id: 'button-go', label: 'Go', tooltiptext: 'Get the news', width: 50}
		]},
		{tag: 'hbox', flex: 1, children: [
			{tag: 'vbox', id: 'vbox-articles', width: 260, children: [
				{tag: 'listbox', id: 'listbox-articles', flex: 1, children: [
					{tag: 'listhead', children: [
						{tag: 'listheader', label: 'Article', width: 500}
					]},
					{tag: 'listbody'}
				]}
			]},
			{tag: 'splitter'},
			{tag: 'vbox', width: '100%', children: [
				{tag: 'description', id: 'description-title'},
				{tag: 'description', id: 'description-date'},
				{tag: 'hbox', id: 'hbox-image', hidden: true, pack: 'center', children: [
					{tag: 'image', id: 'image-article', width: 200}
				]},
				{tag: 'description', id: 'description-content'}
			]}
		]}
	]
};
var oParser = new JUL.UI.Parser({
	customFactory: 'JUL.UI.createDom',
	defaultClass: 'xul',
	topDown: true,
	useTags: true
});
var oWindow = oParser.create(oConfig);
oWindow.show();</pre><h3>To be continued</h3><p>These were some advanced concepts of using JUL &#8211; The JavaScript UI Language. Other concepts like JSON custom replacers, serialization prefixes, code decorators, callback retrieving and scope binding, dotted path escaping, and so on, will be discussed in a future article.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/advanced-jul-concepts-part-1/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>References in JavaScript</title><link>https://the-zonebuilder.freetzi.com/references-in-javascript/</link> <comments>https://the-zonebuilder.freetzi.com/references-in-javascript/#comments</comments> <pubDate>Wed, 12 Oct 2016 17:28:46 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=187</guid> <description><![CDATA[There are several myths about JavaScript shortcomings when it comes to modern features of a programming language. One of them is the statement that you should declare the local variables at the top of a function because they span over all the local scope of that function. While local variables are not restricted to block [&#8230;]]]></description> <content:encoded><![CDATA[<p>There are several myths about JavaScript shortcomings when it comes to modern features of a programming language. One of them is the statement that you should declare the local variables at the top of a function because they span over all the local scope of that function. While local variables are not restricted to block level scope like in other OOP languages, they still exist only after the place where they are declared. So, the code where they appear at the top, and the code where they appear first where needed, although both valid, are not equivalent (scope of access is not the same as scope of existence). In fact, it is more readable to declare a counter that is used only after 20 lines of code, in that spot, than to clutter the beginning of the function with auxiliary variables. Even if you declare two times a local counter, the modern browsers won&#8217;t choke on that, and you can clean the final code with <a href="http://www.sitepoint.com/comparison-javascript-linting-tools/" target="_blank">JSLint/JSHint/ESLint</a> to avoid duplicates.<br /> Another more important myth is that because variables are always <a href="http://snook.ca/archives/javascript/javascript_pass" target="_blank">passed by value</a>, you cannot program with pointers or references in JavaScript. Although the language syntax use the dot to point to the members of an object, there is no mechanism to use their addresses (i.e. pointers). But, when passing an object to a function, the language engine makes a copy of the object, but doesn&#8217;t make copies of its members. The specification states that the members of the copy are the actual members of the original object. So, what is copied in that case?<br /> One should look to the members of an object as being linked to their parent object, instead of being included within. When the object is copied, the links to its members are the ones to get copied, and not the members. One question might arise: what are those links? The answer is related to another feature of JavaScript: garbage collection. It is stated that when a variable is not used anymore, the allocated memory for that variable is freed by the garbage collector. Furthermore, some implementations <a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management" target="_blank">specify</a> that when the count of references to an object reaches zero, that object candidates for garbage collection. This is a disclosure that those links to the object members are not mere links; they are more probably the references of the pointers encountered in other OOP languages.<br /> To exemplify the perceived shortcoming in manipulating the object members in JavaScript, below, it will be proposed two situations.</p><h3>The problem</h3><p>1. Suppose we want to swap two objects depending on one of their properties. The code below illustrates the classical solution.</p><pre class="brush:js">var data = {
	version: '0.01',
	isTest: true,
	first: {
		id: 'a11',
		weight: 1.1,
		size: 2.0
	},
	second: {
		id: 'b10',
		weight: 0.5,
		size: 1.4
	}
};
// try a generic swap; this won't work
function swap1(o1, o2, sortBy) {
	var o = null;
	if (o2[sortBy] &lt; o1[sortBy]) {
		o = o1;
		o1 = o2;
		o2 = o;
	}
}
swap1(data.first, data.second, 'weight');
alert('first: ' + data.first.id + ', second: ' + data.second.id);

// this will work, but is data structure dependent
function swap2(parent, sortBy) {
	var o = null;
	if (parent.second[sortBy] &lt; parent.first[sortBy]) {
		o = parent.first;
		parent.first = parent.second;
		parent.second = o;
	}
}
swap2(data, 'weight');
alert('first: ' + data.first.id + ', second: ' + data.second.id);</pre><p>But we can see that we need to modify the initial declaration of our swap() function, and the code inside it is dependent on the structure of the parent object.<br /> 2. A list of items is received from server-side, and must be processed for display changing several fields and adding another computed field. The qr() function that does the processing needs a code like below.</p><pre class="brush:js">// initial structure
var result1 = {
	meta: {
		weightField: 'w',
		sizeField: 's',
		qrField: 'q'
	},
	items: [
		{id: 'c20', w: 2.1, s: 0.15, q: false},
		{id: 'c21', w: 1.5, s: 1.05, q: false},
		{id: 'c22', w: 1.8, s: 2.20, q: false}
	]
};
function qr1(item, weightField, sizeField, qrField) {
	if (item[sizeField] &lt; 0.5) {
		item[qrField] = 100 * item[weightField];
	}
	else {
		item[qrField] = 25 * item[sizeField] + 75 * item[weightField];
	}
	item[weightField] = 100 * item[weightField] / item[qrField];
	item[sizeField] = 100 * item[sizeField] / item[qrField];
}

// changed structure
var result2 = {
	meta: {
		weightField: 'we',
		sizeField: 'sz',
		qrField: 'qr',
		qmField: 'qm'
	},
	items: [
		{id: 'c20', dataIn: {we: 2.1, sz: 0.15}, dataOut: {qr: false, qm: false}},
		{id: 'c21', dataIn: {we: 1.5, sz: 1.05}, dataOut: {qr: false, qm: false}},
		{id: 'c22', dataIn: {we: 1.8, sz: 2.20}, dataOut: {qr: false, qm: false}}
	]
};
function qr2(itemIn, weightField, sizeField, itemOut, qrField) {
	if (itemIn[sizeField] &lt; 0.5) {
		itemOut[qrField] = 100 * itemOut[weightField];
	}
	else {
		itemOut[qrField] = 25 * itemIn[sizeField] + 75 * itemIn[weightField];
	}
	itemIn[weightField] = 100 * itemIn[weightField] / itemOut[qrField];
	itemIn[sizeField] = 100 * itemIn[sizeField] / itemOut[qrField];
}</pre><p>But, if the name or the structure of the server-side data changes, one must modify the code inside the qr() function although the computing algorithm hasn&#8217;t changed a bit.<br /> These examples show that much of JavaScript code is dependent of the structure of the processed data, and requires continuous maintenance when changing the data source. Well &hellip; not anymore</p><h3>Introducing references in JavaScript</h3><p>A reference in JavaScript is a pair formed by an existing JavaScript object and a string/number which is used as a key for the object.<br /> The object is called the owner/referenced object, and the string is called the reference item/key. The key may be absent in the referenced object at the moment of defining the reference.<br /> The simplest implementation in JavaScript is a hash (object) with two properties that hold the owner and the item, like in the code below.</p><pre class="brush:js">var data = {
	group: 'widgets',
	control: 'Panel',
	style: {
		fonts: ['Helvetica', 'Gerorgia', 'Traffic'],
		borders: {inner: '1px', outer: '2px'},
		visible: true
	}
};
// creating references
var p1 = {ref: data.style, key: 'visible'};
var p2 = {ref: data.style.fonts, key: 2};
var p3 = {ref: data.style.borders, key: 'inner'};
// assigning a value
p1.ref[p1.key] = false;
p2.ref[p2.key] = 'Verdana';
// applying delete operator
delete p3.ref[p3.key];
// copying a reference
var p4 = {ref: p3.ref, key: p3.key};
// changing the key
p4.key = 'shadow';
p4.ref[p4.key] = '4px';
/* the resulting object will be:
data = {
	group: 'widgets',
	control: 'Panel',
	style: {
		fonts: ['Helvetica', 'Georgia', 'Verdana'],
		borders: {outer: '2px', shadow: '4px'},
		visible: false
	}
};
------------------------------ */</pre><p>As one can see, we are able to implement all basic operations with this reference concept, But what advantage could that be to the problem of the data-dependent JavaScript code?</p><h3>The solution &#8211; generics</h3><p>We call a generic, a piece of code or an algorithm that doesn&#8217;t change when the passed/processed data changes structures (field names, field membership, etc.).<br /> Using references, we can build generic functions for the two example problems mentioned before. If the data structures change, one must modify only the actual call of the generic, and not its inner code.<br /> 1.</p><pre class="brush:js">function swap(p1, p2, sortBy) {
	var o = null;
	var o1 = p1.ref[p1.key];
	var o2 = p2.ref[p2.key];
	if (o2[sortBy] &lt; o1[sortBy]) {
		o = o1;
		p1.ref[p1.key] = o2;
		p2.ref[p2.key] = o;
	}
}
// the call
swap({ref: data, key: 'first'}, {ref: data, key: 'second'}, 'weight');
alert('first: ' + data.first.id + ', second: ' + data.second.id);</pre><p>2.</p><pre class="brush:js">function qr(pWeight, pSize, pQr) {
	if (pSize.ref[pSize.key] &lt; 0.5) {
		pQr.ref[pQr.key] = 100 * pWeight.ref[pWeight.key];
	}
	else {
		pQr.ref[pQr.key] = 25 * pSize.ref[pSize.key] + 75 * pWeight.ref[pWeight.key];
	}
	pWeight.ref[pWeight.key] = 100 * pWeight.ref[pWeight.key] / pQr.ref[pQr.key];
	pSize.ref[pSize.key] = 100 * pSize.ref[pSize.key] / pQr.ref[pQr.key];
}
// let it be: var item = data.items[i]; // inside a for loop
// the call in first case:
qr({ref: item, key: 'w'}, {ref: item, key: 's'}, {ref: item, key: 'q'});
/// the call in second case:
qr({ref: item.dataIn, key: 'we'}, {ref: item.dataIn, key: 'sz'}, {ref: item.dataOut, key: 'qr'});</pre><h3>A reference class In JavaScript</h3><p><a title="JUL - The JavaScript UI Language" href="/jul-the-javascript-ui-language/">The JavaScript UI Language</a> module has an implementation of a class for working with references. Using <a title="JUL API Reference" href="https://zonebuilder.github.io/jul/docs/index.html" target="_blank">JUL.Ref</a> class, the code for basic operations can be rewritten as below.</p><pre class="brush:js">var p1 = new JUL.Ref(data.style, 'visible');
var p2 =  new JUL.Ref(data.style.fonts, 2);
var p3 =  new JUL.Ref(data.style.borders, 'inner');
// assigning a value
p1.val(false);
p2.val('Verdana');
// applying delete operator
p3.del();
// copying a reference
var p4 = new JUL.Ref(p3);
// changing the key
p4.key('shadow');
p4.val('4px');</pre><h3>Conclusion</h3><p>The reference concept in JavaScript fills the gap where pointers or references to variables are needed in the other programming languages. It also offers a way to implement generics in JavaScript, which leads to a possible existence of a standard algorithms library for JavaScript (like STL for C++).<br /> Upon a closer examination, as a programming language, JavaScript lacks nothing that the other modern languages have, and it&#8217;s a winning bet for the future of cloud-platform (web, mobile, net-pc) applications.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/references-in-javascript/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>JUL Designer &#8211; a RAD tool for JavaScript</title><link>https://the-zonebuilder.freetzi.com/jul-designer-a-rad-tool-for-javascript/</link> <comments>https://the-zonebuilder.freetzi.com/jul-designer-a-rad-tool-for-javascript/#comments</comments> <pubDate>Mon, 01 Dec 2014 20:25:57 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JUL]]></category> <category><![CDATA[Web development]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=166</guid> <description><![CDATA[Building a complete web application requires some talent and several tools. While the talent develops along with the study and testing, the required tools seem to depend especially on the chosen platform of development. When it comes to the JavaScript libraries, many authors have created the tools appropriate to their framework and to its philosophy. [&#8230;]]]></description> <content:encoded><![CDATA[<p>Building a complete web application requires some talent and several tools. While the talent develops along with the study and testing, the required tools seem to depend especially on the chosen platform of development. When it comes to the JavaScript libraries, many authors have created the tools appropriate to their framework and to its philosophy. And, after starting a wide access framework that promises freedom and productivity to its users, most authors have built proprietary tools for it, putting a price tag to their &#8216;free&#8217; library.<br /> JUL Designer offers you a powerful way to visually build an application using any of your preferred frameworks, while protecting your freedom of choice and your creativity. Its philosophy is to remain open and cost free to any creative effort.<br /> Based on <a title="JUL - The JavaScript UI Language" href="/jul-the-javascript-ui-language/">JUL</a>, the designer enhances JUL&#8217;s organizing and instantiation power with a layer of visual building, editing and testing of your project.<br /> The configuration tree specific to JUL can be now built with selecting and editing from a user interface, and the results are displayed in real time in the test panel. The selection of the components goes both ways from the component tree of the project but also from the testing application. In this manner, you always know where and what component to edit and how to change its members.<br /> Take a look at the demo version below and load the examples to see how it works. The complete and free version can be downloaded from the <a title="JUL Designer project on SourceForge" href="http://sourceforge.net/projects/jul-designer/" target="_blank">project page</a>.</p><p><a title="JUL Designer" href="https://zonebuilder.github.io/designer/index.html" target="_blank"><img class="aligncenter size-full wp-image-167" alt="JUL Designer" src="/site/wp-content/uploads/2014/12/designer.png" width="1366" height="768" /></a></p><p>The operations in the designer cover full manipulation of the component tree: copy, cut, paste, move and remove a component and its descendants, but also copy, cut, paste and remove of multiple members of a component. For each step in the editing of a project, the designer dynamically generates the JavaScript code and reflects the changes in the live testing panel.<br /> You can use any of your favorite widget libraries or component frameworks with JUL Designer by simply adding the component configurations with the &#8220;New framework&#8221; menu option. The current active framework will provide the designer the means of adding and selecting components for any active project. More information about using the designer can be found in the <a title="JUL Designer Help" href="https://zonebuilder.github.io/designer/docs/index.html" target="_blank">application&#8217;s help</a>.<br /> Let&#8217;s hope that this tool will improve your productivity and will offer you the access to building a large JavaScript application with a free visual code generator.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/jul-designer-a-rad-tool-for-javascript/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Why JavaScript?</title><link>https://the-zonebuilder.freetzi.com/why-javascript/</link> <comments>https://the-zonebuilder.freetzi.com/why-javascript/#comments</comments> <pubDate>Mon, 04 Aug 2014 13:32:34 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Web development]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=161</guid> <description><![CDATA[Modern days software migrates massively to a web platform. But, while the trend is the same throughout the world, the Implementations vary greatly. On the server side, there are the most diverse frameworks and a couple of popular programming languages such as PHP, Java, .NET. On the client side, things are a bit simpler, with [&#8230;]]]></description> <content:encoded><![CDATA[<p>Modern days software migrates massively to a web platform. But, while the trend is the same throughout the world, the Implementations vary greatly. On the server side, there are the most diverse frameworks and a couple of popular programming languages such as PHP, Java, .NET. On the client side, things are a bit simpler, with frameworks manipulating a similar DOM environment of the web browsers.<br /> A web application relies on the browser GUI and on the browser engine to run its client part. These interactions have been standardized as <a href="https://en.wikipedia.org/wiki/Document_Object_Model" target="_blank">Document Object Model</a> (DOM) 2 or 3. For the implementation of the client part, one needs knowledge of the HTML markup language for the structure, of the CSS styling language for theming and, of the JavaScript language for the behavior of the client. But, while the knowledge of these three fields is mandatory for ensuring a complete user experience, the mechanics that lie behind all come from a single component model.</p><h2>JavaScript &#8211; the language of DOM</h2><p>Developers of browses adopted the concept of an event driven GUI from the previous work of the GUI operating systems. No wonder that also the implementation of the browser development shares some previous known programming concepts like OOP, COM, RPC, event queues, event pooling and so on. If we take for example, a generic web browser written in Java, the layout, the styling and the behavior engines address the same runtime GUI components written in OOP Java. That means that all three aspects of a component can be entirely controlled using the chosen development language (i.e. Java). But from the web developer point of view, we are constraint to use standardized markup, styling and behavior languages. Analogous to <a href="https://en.wikipedia.org/wiki/Component_Object_Model" target="_blank">COM</a> interfaces, these are different languages that access the same runtime components &#8211; the browser&#8217;s GUI. Taken separately, HTML, CSS and JavaScript have a limited access level to the runtime component and, it seems that all three are required to fully control the client part of a web application. But this is not true &hellip;<br /> In the web apps world, HTML plays the role of a data structuring language like XML. It mostly describes the layout of the application components and, with a certain degree of success, their runtime properties. In the light of the previously presented browser development model, it acts as the &#8220;poor man&#8217;s&#8221; scripting language used to access the browser&#8217;s layout and rendering engines.<br /> CSS is a global styling language with extended use outside the web platform. For web browsers, it accesses the layout and rendering engines with even less control than HTML, but is essential to ensure the enterprise model of the separation of concerns, where designer and programmer tasks are clearly separated.<br /> While HTML and CSS can be regarded as scripting languages with a certain level of control over browser&#8217;s GUI, JavaScript is the closest scripting language to the GUI implementation language and plays a similar role to that of scripting languages for the COM interfaces. All three aspects of layout, styling and behavior can be controlled using JavaScript. That happens because JavaScript follows in the closest way the GUI event oriented model of the browsers implementation. With a closer look, an entire client application can be generated using JavaScript or with a higher level framework like <a href="https://en.wikipedia.org/wiki/GWT" target="_blank">GWT</a> which in turn generates the required JavaScript.</p><h2>JavaScript is power in brackets</h2><p>Modern programming languages provide high abstraction level libraries like STL to use for structures, iterators, algorithms and so on. A common task is organizing and accessing collections of heterogeneous objects. This is generally done using named pairs of key-value collections called hashes. Even the classic members of the structures or of the class instances can be regarded as named properties that point to certain values. This field of hashes is a field where JavaScript excels at. The implementation is the simplest, every object can be regarded as a hash of its properties. In JavaScript, every non-local variable can be accessed using a root object (i.e. window) and a series of strings or integers.<br /> Example:</p><pre class="brush:js">// storing a configuration
window.myConfig = {
	title: 'Sample app',
	layout: {
		align: ['left', 'top'],
		coordinates: [0, 0, 500, 200],
		doubleFrame: true
	}
};
// accessing the forth coordinate using only the bracket notation
var nForth = window['myConfig']['layout']['coordinates'][3];
// this property can be stored to and read from a text file e.g.
// myConfig.layout.coordinates.3 = 200</pre><p>This offers the language an immense power in generating and manipulating sequences of code from static data structures. For most cases of code generation, with the help of the bracket notation, the use of eval() function can be entirely avoided.<br /> Also JavaScript has for .. in construct that iterates over named and unnamed properties like other languages iterators do. For the time JavaScript was developed, the language features were revolutionary. For present days, with a little care, JavaScript can go on pair with the modern OOP languages.</p><h2>ECMA, release JavaScript!</h2><p>Compared to modern OOP scripting languages like Python or PHP5, JavaScript lacks several features that make the development cycle enterprise ready. First known problem is the lack of a class inheritance model, addressed by <a href="https://en.wikipedia.org/wiki/Ecma_International" target="_blank">ECMA</a> drafts like Harmony, but surprisingly not yet standardized. Other maturity challenge is the implementation of standard algorithms and base libraries like e.g. PHP has. But we saw in the previous topic how the bracket notation makes it easy to do hashes and collection iteration. Other required feature in nowadays environment is an architecture independent compiled form of the language, like Java or .NET have. But <a href="https://en.wikipedia.org/wiki/List_of_JavaScript_engines" target="_blank">JIT compilers for JavaScript</a> are implemented in every mainstream browser and, it&#8217;s just a matter of political coordination until the browser development teams will submit a draft regarding this feature. Although, for security reasons, JavaScript source code should be made available to the web clients, a standard compiled form will bring JavaScript to the maturity of the preferred development languages in the software business. Current methods of compression and of obfuscation of the JavaScript source code are just a way of demanding this developer requested feature. A standard compiled form adds a superior level of copyright protection compared to simply signing raw source code and it will be much faster to download and to execute.<br /> These are just a few requirements that make JavaScript to lag behind other development platforms. But the reason of the delay should be seeked out in the corporative interests of the major players in the development world. It is the voice of the united community that can go through the opacity of the standardization commission and eventually impose these popular demands. And, if ECMA cannot solve the problem, we can make the actual and useful standard in their place. Look only to the multitude of <a href="http://ajaxpatterns.org/Javascript_Inheritance" target="_blank">class systems</a> implemented for this most useful prototypal language.</p><h2>JavaScript can serve!</h2><p>A modern web application has a solid server side part which ensures the stability and the security of the data processing. The most used platforms for the server side are PHP, Java and .NET. All are mature frameworks with an up-to-date programming language and a powerful library stack. Among all, PHP has gained its popularity due to its Swiss-knife integrated libraries which seem to be the recipe of success for a useful server stack.<br /> Until recent years, JavaScript was limited to the client side world because of its absence as a useful stack on the server side. This is no longer a problem since the fast catch-up of <a href="https://en.wikipedia.org/wiki/Node.js" target="_blank">Node.js</a> which aims to bring the popularity of the PHP to the server side JavaScript. When this project succeeds, JavaScript can be used unitarily both for the client and for the server sides. The developers can concentrate on the business logic instead of learning different languages just to be able to complete an application.</p><h2>Conclusion</h2><p>JavaScript was invented as an evolutionary language with garbage collection, high level string and hash manipulation, regular expression engine and dozens of useful features not limited to web programming.<br /> It is the context of big players that hindered its way as a global programming language, but their grasp on proprietary platforms cannot go on with the current age.<br /> You should use JavaScript and support it as a free and universal programming language and the world will adhere to the evidence!</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/why-javascript/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>JUL Concepts</title><link>https://the-zonebuilder.freetzi.com/jul-concepts/</link> <comments>https://the-zonebuilder.freetzi.com/jul-concepts/#comments</comments> <pubDate>Thu, 22 May 2014 14:53:05 +0000</pubDate> <dc:creator><![CDATA[ZB]]></dc:creator> <category><![CDATA[JUL]]></category><guid isPermaLink="false">https://the-zonebuilder.freetzi.com/?p=142</guid> <description><![CDATA[As we have seen in the introductory article, the JavaScript UI language module (JUL) can be used to convert a substantial programming task into a configuration scripting. This is possible because JUL deals with the configuration and the instantiation phases in a standardized way for any component-based JavaScript framework. And, because the target of the [&#8230;]]]></description> <content:encoded><![CDATA[<p>As we have seen in the <a title="JUL - The JavaScript UI Language" href="/jul-the-javascript-ui-language/">introductory article</a>, the JavaScript UI language module (JUL) can be used to convert a substantial programming task into a configuration scripting.<br /> This is possible because JUL deals with the configuration and the instantiation phases in a standardized way for any component-based JavaScript framework. And, because the target of the most of these frameworks is a rich internet application (RIA) working in a browser, JUL provides a simple way to specify the layout and the interface logic for event-driven browser applications.<br /> In order to fully use its capabilities, we will see in the followings the concepts that JUL is based on. All discussion is in the field of JavaScript and DOM programming where otherwise not specified.</p><h2>Configuration object</h2><p>A configuration object is a JavaScript object which may have the following member types:</p><ul><li>all valid JSON types: string, number, boolean, null, object, array</li><li>a RegExp instance</li><li>a function definition (i.e. a Function instance)</li><li>a configuration object</li><li>an array of configuration objects</li></ul><p>Example:</p><pre class="brush:js">APP.codeUi = {
	tag: 'dialog',
	id: 'dialog-code',
	title: 'Code',
	hidden: true,
	width: 700,
	height: 330,
	children: [
		{tag: 'textbox', id: 'textbox-code', width: '100%', multiline: true, flex: 1}
	],
	listeners: {
		dialogaccept: function() {
			APP.saveCode();
			return false;
		},
		dialogcancel: function() {
			APP.cancelCode();
			return false;
		}
	}
};</pre><h2>Configuration tree</h2><p>A configuration tree is a hierarchy of configuration objects with the root object having certain members as (arrays of) configuration objects and so on.</p><h2>Configuration namespace</h2><p>A configuration namespace is a configuration object whose methods may be constructor functions.<br /> Example:</p><pre class="brush:js">JUL.UI = {
lassProperty: 'xclass',
	defaultClass: 'Object',
	...
	// next function is used as a constructor
	Parser: function(oConfig) { ... },
	...
};</pre><h2>Dotted path</h2><p>A dotted path or an object path is the string that represents the JavaScript variable to access the object as a member starting from the root global JavaScript object (e.g. window). A dotted path uses only dots to separate its segments (even for numeric segments).<br /> Example:</p><pre class="brush:js">APP.mainWindow = {
	xclass: 'Window',
	align: 'center',
	width: 1100,
	height: 500,
	children: [
		{xclass: 'Toolbar', items: [
			{xclass: 'Button', icon: 'img/open.png', caption: 'Open'},
			{xclass: 'Button', icon: 'img/save.png', caption: 'Save'},
			{xclass: 'List', label: 'Export', options: ['pdf', 'text', 'xml']}
		]},
		...
	]
};
// get the list options array using a dotted path
var aOptions = JUL.get('APP.mainWindow.children.0.items.2.options');</pre><h2>Reliable serialization</h2><p>Reliable serialization means the serialization of a JavaScript object that produces equivalent JavaScript code across different runtime environments (e.g. browsers). The resulting code must produce object having the same non-prototypal members across these environments. In JUL, reliable serialization must produce the same configuration object as JavaScript source code across all major browsers.<br /> Note: The object been serialized may not be necessary the same as the object produced by the serialized JavaScript code.<br /> Example:</p><pre class="brush:js">var oTest = {
	name: 'type',
	maxLength: 10,
	allowedValues: /^(boolean|numeric|string)$/i,
	listeners: {
		onBlur: function() {
			if (!this.value) { return false; }
		}
	}
};
// next line produces equivalent JavaScript code under all major browsers
var sCode = JUL.UI.obj2str(oTest);</pre><h2>Special members</h2><p>A configuration object may have, among others, certain special members as follows:</p><ul><li>class property &#8211; a string representing the name of the class of the component created by the configuration object.</li><li>children property &#8211; an array of configuration object for which JUL will create children properties.</li><li>&#8216;other members&#8217; property &#8211; serves the same purpose as the children property, allowing multiple hierarchies under the same configuration object. They also allow writing a more compact form of the configuration tree.</li><li>ID property &#8211; If present, this property provide the basis of the layout and logic separation of the configuration trees. It can be also used to identify the instantiated components.</li></ul><p>For a full list of special members, please see the next paragraph regarding JUL parser.</p><h2>JUL parser</h2><p>A JUL parser is an instance of JUL.UI.Parser used to create an entire tree of runtime components from a configuration tree. The creation process instantiates the components in a given order (e.g. from parent to children).<br /> Example:</p><pre class="brush:js">var oParser = new JUL.UI.Parser({
	defaultClass: 'xul',
	useTags: true,
	customFactory: JUL.UI.createDom,
	topDown: true
});</pre><p>The parser routine accepts a configuration object which gives the necessary information for the construction of the component tree.<br /> The configuration properties of the parser are:</p><ul><ul><li>classProperty &#8211; the name of the class property in the configuration object &#8211; defaults to &#8216;xclass&#8217;.</li><li>defaultClass &#8211; the name of the default class if the class name is not specified by the configuration object &#8211; defaults to &#8216;Object&#8217;.</li><li>childrenProperty &#8211; the name of the property of the configuration object which is an array of configuration objects &#8211; defaults to &#8216;children&#8217;.</li><li>membersProperties &#8211; is an array of names with the purpose similar to childrenProperty allowing several hierarchies under the same parent configuration &#8211; defaults to [].</li><li>IdProperty &#8211; the name of the ID property of the configuration object &#8211; defaults to &#8216;id&#8217;. It allows identification of the components, runtime publishing under given paths, and layout and logic separation for the configuration object.</li><li>bindingProperty &#8211; allows layout and logic separation similar to idProperty but it will not get passed to the component constructor &#8211; defaults to &#8216;cid&#8217;. Ii cannot be used for component identification bur provides a way for the inheritance of the included objects &#8211; see includeProperty.</li><li>topDown &#8211; boolean that specifies if the parser will initialize the components top-down or bottom-up &#8211; defaults to false. For the bottom-up instantiation, the children are created first, and for the top-down process, the parent is created first.</li><li>customFactory &#8211; a function that will be passed the configuration object. It&#8217;s used instead of the &#8216;new&#8217; constructor &#8211; defaults to null.</li><li>parentPropery &#8211; the name of a property of the configuration object that will be automatically assigned the instance of the parent component &#8211; defaults to &#8216;parent&#8217;. It is used only for the top-down instantiation.</li><li>useTags &#8211; whether to use a tag property instead of classProperty &#8211; defaults to false. For DOM languages (e.g. HTML, XML, SVG, XUL etc.), you can set the defaultClass to &#8216;html&#8217; for example, and use the tag property to specify which component to construct.</li><li>tagProperty &#8211; the name of the tag property for a DOM element to be instantiated &#8211; defaults to &#8216;tag&#8217;. JUL.UI has also a custom factory named &#8216;createDom&#8217; to help constructing DOM elements.</li><li>includeProperty &#8211; allows explicit inclusion of another configuration object in the current one &#8211; defaults to &#8216;include&#8217;. The current object is applied over the included object.</li></ul></ul><p>For the complete documentation of the parser configuration, please see the corresponding <a title="JUL API Reference" href="https://zonebuilder.github.io/jul/docs/index.html" target="_blank">API Reference </a>topic.</p><h2>Conclusion</h2><p>These were basic JUL concepts to start with. Advanced concepts and a series of tutorials will follow.</p> ]]></content:encoded> <wfw:commentRss>https://the-zonebuilder.freetzi.com/jul-concepts/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>