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/core@0.0.26/core.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@onejs-dev/core@0.0.26/core.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/**\r\n * A functional programming oriented Javascript module. It allows to write your web app or native \r\n * app using just plain functional vanilla JS.\r\n * This module provides optional features such as state management, routing, database access/storage \r\n * and style theming.\r\n * Internally it leverages the power of React, Emotion and Firestore to provide this functionality.\r\n * @module oneCore\r\n */\r\n\r\n//React Imports. Currently React does not provide ESM modules but UMD\r\nimport React from 'react';\r\n\r\n//Web vs Native specific differences\r\nimport {OSSPECIFICS} from '@onejs-dev/core/osSpecifics/osSpecifics';\r\n\r\n//Conditionally import Firestore\r\nif(OSSPECIFICS.firestore) {\r\n    var {\r\n        doc, collection, addDoc, setDoc, getDoc, deleteDoc, getDocs, onSnapshot\r\n    } = OSSPECIFICS.firestore;\r\n}\r\n\r\n/**\r\n* @description The operating system where the app is being executed: web, android or ios. \r\n* @type {String}\r\n*/\r\nexport const os = OSSPECIFICS.os;\r\n\r\n/**\r\n* @description All the module internal global variables are properties of the ONEJS object. \r\n* @type {Object}\r\n*/\r\nvar ONEJS = {\r\n    //Database Module\r\n    firestore: {},             //The firestore database to perform read/write operations\r\n    idb: {},                   //The indexedDB database to perform read/write operations\r\n\r\n    //State Module\r\n    reactState: [],            //All the React variables part of the 'useState' hook\r\n    reactSetState: [],         //All the React methods to set the state part of the 'useState' hook\r\n    url: {},                   //The current url for the app for React Native\r\n    setUrl: {},                //The set method for the url 'useState' hook\r\n    urlStateVariables: [],     //The ids of the state variables to be updated on url changes \r\n    currentState: {},          //Current state of the app, contains the value of all state variables\r\n    stateHistory: [],          //The history of modifications performed to the state\r\n    stateHistorySize: 10,      //Maximum length for the stateHistory array. Limits the amount of \r\n                               //modifications stored\r\n    stateHistoryPosition: 0,   //Newest (current) state position is 0. Rewinding the state this \r\n                               //value can be changed \r\n    fontsLoaded: false,        //Whether custom fonts have been loaded to enable first render. RN\r\n\r\n    //Components Module    \r\n    memoizedComponents: [],    //React components are stored in this array using the name as index\r\n\r\n    //App Module\r\n    appName: '',               //Name of the app. Used by indexedDB to avoid naming collisions\r\n    appText: {},               //All the app texts to provide translation functionality\r\n    os: window ? 'web' : (global ? 'native' : undefined),//Current operating system for the app\r\n    theme: {default: {}},      //Theme variable values for the different flavors\r\n    style: {},                 //Object containing all the different styles for the app\r\n    iconGradients: new Map(),  //Stores the relation between the CSS/native gradient and the SVG one\r\n};\r\n\r\n\r\n//==================================================================================================\r\n// LANGUAGE SETUP: All the app strings can be saved into a configuration object containing the \r\n// different translations for the languages supported.\r\n// The language module aims to simplify translation of the app when the user switches to a \r\n// different language.\r\n//==================================================================================================\r\n\r\n/** \r\n* @description Retrieves the user's local language based on the navigator configuration.\r\n* @returns {String} Returns the user's local language.\r\n*/\r\nexport const getLanguage = () => {\r\n    const localLanguage = localStorage.getItem('oneLanguage' + ONEJS.appName ?? '');\r\n    // const userLanguage = OSSPECIFICS.userLanguage;\r\n    const userLanguage = navigator.language || navigator.userLanguage;\r\n    return localLanguage ?? userLanguage;\r\n};\r\n/** \r\n* @description Sets the language defined by the user.\r\n* @param {String} languageISOCode - Chosen language in ISO format.\r\n* @returns {void}\r\n*/\r\nexport const setLanguage = (languageISOCode) => {\r\n    localStorage.setItem('oneLanguage' + ONEJS.appName ?? '', languageISOCode);\r\n};\r\n/** \r\n* @description It is used to update the value of the language on user input change events.\r\n* Use-case: Call function oninput or onchange events on the template.\r\n* @param {Object} event - User event containing the target value to update the language.\r\n* * @example\r\n* ```javascript\r\n* input({onchange: updateLanguage}); //Every time time the input changes updates the value of \r\n*       //'event' and therefore the language\r\n* ```\r\n*/\r\nexport const updateLanguage = (event) => {\r\n    if(event?.target) setLanguage(event.target?.value);\r\n};\r\n/** \r\n* @description Reads the text for a certain language based on the text id. \r\n* Prerequisites: Define all the texts in a single object and provide it as the \"text\" parameter to \r\n* the app() function.\r\n* @param {String} id - The id of the text to be fetched.\r\n* @param {String} [language=user's default language] - The id of the text to be fetched.\r\n* @example\r\n* App Function Text Object Example\r\n* ```javascript\r\n* appText = {title: 'My App',  home: {en: 'home', es: 'casa'}}\r\n* ```\r\n* @example\r\n* Function Call\r\n* ```javascript\r\n* readTextString('home') //Return 'home' for 'en' and 'casa' for 'es'\r\n* ```\r\n* @returns {String} Returns the text string for the corresponding language.\r\n* @todo  Create website to send JS object with text configuration: {home: 'home', button: 'your \r\n* input'} and return {home: {en: 'home', es: 'casa'}, \r\n* button: {en: 'your input', es: 'su input'}}. Use a translator API.\r\n*/\r\nexport const readTextData = (id, language = getLanguage()) => {\r\n    if(!ONEJS.appText) {\r\n        console.error('The text has not been setup in the app function.');\r\n        return;\r\n    }\r\n    if(!ONEJS.appText[id]) {console.error('No such id: ' + id); return;}\r\n    if(language) {\r\n        if(ONEJS.appText[id][language]) return readTextProperties(id, language);\r\n        //In many cases the browser uses the language + variant ISO notation while the app may only\r\n        //use the ISO two character code. E.g: browser: en-US, app: en\r\n        const isoLanguage = language.slice(0, 2);\r\n        if(ONEJS.appText[id][isoLanguage]) return readTextProperties(id, isoLanguage);;\r\n        //Return text in the default language\r\n        const defaultLanguage = ONEJS.appText['default'];\r\n        if(ONEJS.appText[id][defaultLanguage]) {\r\n            return readTextProperties(id, defaultLanguage);\r\n        }\r\n        console.error('No such language: ' + language);\r\n        return;\r\n    }\r\n\r\n    // if(typeof ONEJS.appText[id] === 'string') return ONEJS.appText[id];\r\n    return;\r\n};\r\nconst readTextProperties = (id, language) => {\r\n    //The properties to be searched\r\n    let targetProperties = ['type', 'link', 'emphasis', 'code', 'list'];\r\n    let properties = {};\r\n    let textObject = ONEJS.appText[id];\r\n    let languageObject = typeof ONEJS.appText[id][language] === 'object' ?\r\n        ONEJS.appText[id][language] : null;\r\n    properties.text = languageObject ? languageObject.text : textObject[language];\r\n    //Search properties\r\n    targetProperties.forEach(property => {\r\n        if(languageObject && languageObject[property]) {\r\n            properties[property] = languageObject[property];\r\n            if(property === 'type') properties.flavor = readFlavor(languageObject[property]);\r\n        }\r\n        else if(textObject[property]) {\r\n            properties[property] = textObject[property];\r\n            if(property === 'type') properties.flavor = readFlavor(textObject[property]);\r\n        }\r\n    });\r\n    return properties;\r\n};\r\n\r\n//==================================================================================================\r\n//TODO: Update\r\n// ROUTING SETUP: Internal methods to provide routing functionality for web. Dynamic and \r\n// declarative, just setup the url property of the View component in order to:\r\n// 1. Toggle visibility: If the actual url matches the url visible property the element is \r\n//                       displayed. \r\n// 2. Toggle active:     If the actual url matches the url active property the element is displayed.\r\n// 3. Link routing:      The element changes the actual url to match the url link property.\r\n// Example: \r\n// const template => [View({url: {visible: '/home'}})('Home Screen'),\r\n//                    View({url: {link: '/home', active: 'home'}})([\r\n//                    Button()('Redirect to home screen'))];\r\n//==================================================================================================\r\n\r\n/** \r\n* @description Checks if the target url matches the actual page url.\r\n* Principles: All url-s must start with '/' because all url-s are absolute.\r\n* Naming: '*' represents any value for a given segment. At the end of the url, e.g.'/path/to/end/*'\r\n* means any number of segments after.\r\n* Note: The page root has a url '/'. This can only be matched by target url '/' or '* /'\r\n* Note: Actual url ignores anchors (root/home/#anchor/path === root/home)\r\n* @param {String} url - The url to be compared with the actual url.\r\n* @example\r\n* Function Call for Actual Url = '/path/to/page'\r\n* ```javascript\r\n*   matchUrl('/* /* /page') //Matches\r\n*   matchUrl('/* /to')      //Does not match\r\n*   matchUrl('/* /to/*')    //Matches\r\n* ```\r\n* @returns {Boolean} Returns true if the target url matches the actual url, false otherwise.\r\n*/\r\nexport const matchUrl = (url) => {\r\n    if(!url) return false;\r\n    //Filter added to remove the empty strings after split. E.g.: Root path is \"/\" and split \r\n    //converts to ['', '']. Filter turns into []\r\n    const actualUrlString = OSSPECIFICS.os === 'web' ?\r\n        decodeURI(location.pathname + location.search) : ONEJS.url;\r\n    const actualUrl = actualUrlString.split('/').filter(Boolean); //this url always starts with '/'\r\n    const targetUrl = url.split('/').filter(Boolean);\r\n    if(targetUrl.length - actualUrl.length > 1 || (targetUrl.length - actualUrl.length === 1 &&\r\n        targetUrl[targetUrl.length - 1] !== '*')) return false;\r\n    //Return false if the target url does not match at any stage\r\n    for(let i = 0; i < actualUrl.length; i++) {\r\n        if(i === targetUrl.length - 1 && targetUrl === '*') return true;\r\n        if(actualUrl[i] !== targetUrl[i] && targetUrl[i] !== '*') return false;\r\n    }\r\n    return true;\r\n};\r\n\r\n/** \r\n* @description If the url matches the current path, returns the value from the segment with ':'.\r\n* Naming: '*' represents any value for a given segment. ':' represents the segment to extract the\r\n* data from.\r\n* Use case: Users can type any id in the url and retrieves the specific item from the database.\r\n* @param {String} url - The url to extract data from.\r\n* @example\r\n* Function Call for Actual Url = '/path/to/page'\r\n* ```javascript\r\n    readUrlData('/* /: /page') //Returns 'to' (not 'to/page')\r\n    readUrlData('/* /: ')      //Does not match, returns undefined\r\n    readUrlData('/* /: /*')    //Returns 'to'\r\n    readUrlData('/* /in/*')    //Does not match, returns undefined\r\n* ```\r\n* @returns {String} Returns the value from the segment with ':'.\r\n*/\r\nconst readUrlData = url => {\r\n    if(typeof url !== 'string') return;         //If not a string return undefined. This allows '' as a possible url.\r\n    if(url === ':') {                           //If url is ':', return the full actual url\r\n        return OSSPECIFICS.os === 'web' ?\r\n            decodeURI(location.pathname + location.search) : ONEJS.url;\r\n    }\r\n    const urlToMatch = url.replace(/:/g, '*');  //The url without the data ':' segments. RN does not support 'replaceAll' function\r\n    if(!matchUrl(urlToMatch)) {\r\n        if(urlToMatch === url) return false;    //If the url does not match returns false (does not contain : segments)\r\n        return;\r\n    }\r\n    else if(urlToMatch === url) return true;    //If the url does not contain a data ':' segment, return true if the url matches\r\n    //Matches and contains ':' segments\r\n    const actualUrlString = OSSPECIFICS.os === 'web' ?\r\n        decodeURI(location.pathname + location.search) : ONEJS.url;\r\n    const actualUrl = actualUrlString.split('/').filter(Boolean);\r\n    const targetUrl = url.split('/').filter(Boolean);\r\n    let urlData = []; //Enables inserting multiple ':' segments\r\n    for(let i = 0; i < targetUrl.length; i++) {\r\n        if(targetUrl[i] === ':') urlData.push(actualUrl[i]);\r\n    }\r\n    return urlData.join('/');\r\n};\r\n\r\n/**\r\n* @typedef  {Object}  Url - The configuration structure required by urlSetup function. It enables displaying or hiding the View based on the url, adding an\r\n* 'active' attribute or making it clickable redirecting the user to the chosen url.\r\n* Principles: All url-s must start with '/' because all url-s are absolute.\r\n* Naming: '*' represents any value for a given segment. At the end of the url, e.g.'/path/to/end/*' means any number of segments after\r\n* Note: The page root has a url '/'. This can only be matched by target url '/' or '* /'\r\n* Note: Actual url ignores anchors (root/home/#anchor/path === root/home)\r\n* ```javascript\r\n* @example\r\n*   //Actual Url = '/path/to/page'\r\n*   matchUrl('/* /* /page') //Matches\r\n*   matchUrl('/* /to')      //Does not match\r\n*   matchUrl('/* /to/*')    //Matches\r\n* @property {String}  [visible]             - The url for the component to be visible.\r\n* @property {String}  [active]              - The url for the component to be active.\r\n* @property {String}  [link]                - The url to be redirected to when clicking the component.\r\n* @example\r\n* ```javascript \r\n*   const myUrl = {visible: '/*', active: '/home/*', link: '/home'}\r\n* ```\r\n*/\r\n/** \r\n* @description Enables routing for View components. \r\n* @param {Url} url - The url configuration to enable routing.\r\n* @param {Function} onVisibleChange - Triggers the function with the 'visible' value (bool) as parameter when visbility needs to be modified due to url changes.\r\n* @param {Function} onActiveChange - Triggers the function with the 'active' value (bool) as parameter when 'active' needs to be modified due to url changes.\r\n* @param {Object} component - The DOM component to be animated.\r\n* @example\r\n* ```javascript \r\n*   View({visible: read('isVisible'), onVisibleChange: update('isVisible'), url: {visible: '/home1', link: 'home2'}})('hello world');\r\n* ```\r\n* @returns {void}\r\n*/\r\n//Web Only\r\nconst setupUrl = (url) => component => { //Setup animation on property changes\r\n    // const touchEvent = (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) ||\r\n    //     (navigator.msMaxTouchPoints > 0)) ? 'press' : 'click';\r\n    const touchEvent = 'click';\r\n\r\n    //If url is of type link. Redirects to the linked address\r\n    //If a link does not start with '/', it gets appended to the last part of the url (relative). \r\n    //If starts with '/', it replaces from the root (absolute).\r\n    if(typeof url === 'string') {\r\n        component.addEventListener(touchEvent, async (e) => {\r\n            e.preventDefault();\r\n            if(matchUrl(url)) return; //If the current url matches the target url do nothing (avoid changing url)\r\n            window.history.pushState(null, null, url); //data, title, url\r\n            window.dispatchEvent(new CustomEvent('urlChange', {detail: url}));\r\n        });\r\n        if(!window.onpopstate) { //Popstate gets activated when pressing next or back buttons on the browser or calling history.back() history.go()\r\n            window.onpopstate = (e) => {\r\n                window.dispatchEvent(new CustomEvent('urlChange',\r\n                    {detail: decodeURI(location.pathname + location.search)}));\r\n            };\r\n        }\r\n    }\r\n};\r\n\r\n/** \r\n* @description Reads the current url to set the corresponding state variable. Subscribes to url changes.\r\n* Naming: '*' represents any value for a given segment. ':' represents the segment to extract the data from.\r\n* Use case: Update the value of a state variable that uses url as source\r\n* @param {String} url - The url to extract data from.\r\n* @param {String} stateId - The state id where data will be stored.\r\n* @example\r\n* State Configuration:\r\n* ```javascript\r\n*   const state = {eventId: {source: {url: '/* /events/:'}}}\r\n* ```\r\n* Internal Function Call:\r\n* ```javascript\r\n*   //Actual url: '/path/events/event123'\r\n*   readUrl('/* /events/:')('eventId'); //Sets eventId = 'event123'\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst readUrl = (url) => (stateId) => {\r\n    write(stateId, readUrlData(url), 'url', 'update');\r\n    ONEJS.urlStateVariables.push({url: url, stateId: stateId});\r\n};\r\n\r\n/** \r\n* @description Updates the url state variable for React Native apps.\r\n* Naming convention:\r\n*   - If the url starts with '/' it will be taken as an absolute path and the actual url will be \r\n*     fully replaced.\r\n*   - If the url starts with './' or no '/' it will be taken as a relative path and will be \r\n*     appended to the actual url.\r\n* @param {String} url - The new url to update the current url.\r\n* @example\r\n* Internal Function Call:\r\n* ```javascript\r\n*   //Actual url: '/home'\r\n*   updateurl('/events'); //Actual Url = '/events'\r\n*   updateurl('./sponsor'); //Actual Url = '/home/sponsor'\r\n*   updateurl('partners'); //Actual Url = '/home/partners'\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst updateUrl = url => {\r\n    if(typeof url !== 'string') return;\r\n    let finalUrl = ONEJS.url;\r\n    if(url === '') finalUrl = '/';\r\n    else finalUrl = url;\r\n\r\n    //All urls are absolute or relative to the base url, which by default is '/'\r\n    // else if(url.slice(0, 1) === '/') finalUrl = url;\r\n    // else if(url.slice(0, 2) === './') finalUrl = finalUrl + url.slice(2 - url.length);\r\n    // else finalUrl = finalUrl + url;\r\n    ONEJS.setUrl(finalUrl);\r\n};\r\n\r\n/** \r\n* @description Reads a database path with state variables '<stateId>'. The '<stateId>' variable \r\n* holds the ID for the database item. \r\n* Use case: Return data from the database for a specific item. The <stateId> variable should only be \r\n*           used at document level, even if it may work at collection level.\r\n* Naming: '<stateId>' represents the variable to be replaced with the value.\r\n* Note: The function name says 'Path' rather than 'Url' since it reads both database paths and DOM \r\n*       http url.\r\n* Note: Discriminants have been used '< >' as the stateId encoding character since they are not \r\n*       allowed in regular http urls.\r\n* @param {String} path - The path to read <stateId> from.\r\n* @example\r\n* ```javascript \r\n*   const state = {eventId: 'event123', myEvent: source{firestore: {'events/<eventId>'}} }\r\n*   readPath('events/<eventId>') //eventId = 'event123', Returns 'events/event123'\r\n*   readPath('events/<eventId>') //eventId = undefined, Returns undefined\r\n* ``` \r\n* @returns {String} Returns the path after replacing the '<stateId>' with the corresponding value.\r\n* @todo Discarded idea: Besides @stateId, we could also implement :, to combine and retrieve the\r\n* value for both the state and url data. (Creates confusion, final decision is to only use state \r\n* variables)\r\n*/\r\nconst readPath = (path) => {\r\n    let finalPath = path;\r\n    //Path Includes State Variable\r\n    if(finalPath.includes('<') && finalPath.includes('>')) {\r\n        const stateId = (path.split('<')[1]).split('>')[0]; //Returns the stateId from in between the '<' '>' characters.\r\n        if(read(stateId) != null) {\r\n            finalPath = finalPath.replace('<' + stateId + '>', read(stateId).toString());\r\n        }\r\n        else return;//Returns undefined so that 'source/storage' functions avoid reading/writing from/to database\r\n    }\r\n    return finalPath;\r\n};\r\n\r\nconst readPathState = (path) => {\r\n    if(path.includes('<') && path.path('>')) {\r\n        return (path.split('<')[1]).split('>')[0]; //Returns the stateId from in between the '<' '>' characters.\r\n    }\r\n    return;\r\n}\r\n\r\n//=============================================================================\r\n// FIREBASE SETUP: This is an optional module that allows the user to work with\r\n// the Firebase Firestore database in a declarative way.\r\n// 1. Setup the firestore database in the index.js file\r\n// const config = {apiKey: \"---randomKey---\", authDomain: \"myApp.firebaseapp.com\",\r\n// const firebaseApp = initializeApp(config);//Initialize firebase      \r\n// const firestoreDB = getFirestore();// Initialize Cloud Firestore after Firebase\r\n// 2. Setup the state configuration to use firestore as the source or storge option\r\n// const state = {events: {default: [], source: {firestore: 'events'}, \r\n//     storage: {firestore: 'events'}}, ...};\r\n// 3. Intialize the app() function with the firestore database\r\n// app({component: App, state: state, firestore:firestoreDB});\r\n//\r\n//=============================================================================\r\n\r\n/** \r\n* @description Pull data from the firestore database on request. It can be a single document or full collection.\r\n* Use case: Triggered by firestore read to pull data for dynamic paths (depending on the state)\r\n* @param {String} path - The firestore path to read data from (even path: document, odd path: collection).\r\n* @param {String} stateId - The state id of the variable that will be updated with the data from the database.\r\n* @example\r\n* ```javascript \r\n*   const state = {eventId: 'event123', myEvent: source{firestore: {'events/@eventId'}} }\r\n*   firestoreGetDataOnce('events/@eventId')(myEvent);// If eventId = 'event123', sets myEvent = {obj} which is the database value for the path = 'events/event123'\r\n* ``` \r\n* @returns {void}\r\n*/\r\nconst firestoreGetDataOnce = async (path, stateId) => {\r\n    if(!read(readPath(path))) return; //If the state is not defined return undefined\r\n    if(path.split('/').length % 2 === 0) {\r\n        const docRef = doc(ONEJS.firestore, readPath(path));\r\n        try {\r\n            const docSnap = await getDoc(docRef);\r\n            if(docSnap.exists()) {write(stateId, docSnap.data(), 'firestore', 'update');}\r\n            else {console.error(\"No such document!\");}//doc.data() will be undefined in this case\r\n        }\r\n        catch(error) {console.error(\"Error getting document:\", error);}\r\n    }\r\n    else {\r\n        const collRef = collection(ONEJS.firestore, readPath(path));\r\n        try {\r\n            const collSnap = await getDocs(collRef);//doc.data() is never undefined for query doc snapshots\r\n            const result = [];\r\n            collSnap.forEach((doc) => {result.push({...{id: doc.id}, ...doc.data()});});//Adding the id to the result array for each document\r\n            write(stateId, result, 'firestore', 'update');\r\n        } catch(error) {console.error(\"Error reading snapshot: \", error);}\r\n    }\r\n};\r\n\r\n/** \r\n* @description Reads a document or collection of documents from Firestore database and sets the corresponding state variable.\r\n* Naming: Even number of segments in path for documents or even for collections (group of documents)\r\n* @param {String} path - The firestore path to read data from.\r\n* @param {String} stateId - The state id of the variable that will be updated with the data from the database.\r\n* @param {String} context - The context that is requesting this data. This function writes the state using the 'firestore' context, this way read/write loops can be avoided\r\n* @example\r\n* Static Path Examples:\r\n* ```javascript \r\n*    path = events           //Returns array of events []\r\n*    path = events/event123  //Returns event object with id = event123 {}\r\n* ```\r\n* Dynamic Path Examples:\r\n* ```javascript \r\n*   path = @collectionId    //Returns array of events []. This is not recommended for security reasons, state variables in the path should be at document level\r\n*   path = events/@eventId  //Replaces @eventId (calling readPath) with state variable value and returns event object\r\n* ``` \r\n* @todo Discarded idea: Besides @stateId, we could also implement :, to combine and retrieve the value for both the state and url data. (Creates confusion as paths and urls are not the same)\r\n* @returns {void}\r\n*/\r\nconst firestoreRead = (path) => (stateId, context = '') => {\r\n    if(context === 'firestore') return;\r\n    if(!path) return;\r\n    else if(path.includes('@') && context === 'initialize') {//Subscribes for state changes during 'setupState' initialization\r\n        window.addEventListener(readPath(path) + 'stateChange',\r\n            async (e) => {firestoreGetDataOnce(path, stateId);}, false);//Called on state updates\r\n        firestoreGetDataOnce(path, stateId);//Pulls data once for the first time\r\n    }\r\n    else if(context === 'initialize') {//Subscribe to firestore updates using 'onSnapshot'\r\n        //If the path is even, Firestore DOCUMENT is retrieved\r\n        if(path.split('/').length % 2 === 0) {\r\n            try {\r\n                const unsubscribe = onSnapshot(doc(ONEJS.firestore, path),\r\n                    (doc) => {write(stateId, doc.data(), 'firestore', 'update');});\r\n            }\r\n            catch(error) {console.error(\"Error reading snapshot: \", error);}\r\n        }\r\n        //If the path is odd, Firestore COLLECTION is retrieved (list of documents within a collection)\r\n        else {\r\n            try {\r\n                const unsubscribe = onSnapshot(collection(ONEJS.firestore, path), (snapshot) => {\r\n                    const result = [];\r\n                    snapshot.forEach((doc) => {result.push({...{id: doc.id}, ...doc.data()});});  //Adding the id to the result array for each document\r\n                    write(stateId, result, 'firestore', 'update'); //If storage is also set we will run into conflicts\r\n                });\r\n            } catch(error) {console.error(\"Error reading snapshot: \", error);}\r\n        }\r\n    }\r\n    else {  // Called for paths with state variables and stateId with source and storage. In these cases when the write function updates the stateId, since data\r\n        // is not synced with 'onSnapshot', the 'source' function is called to pull the just stored data again from the database.\r\n        // This is required since adding new data to the database generates a new id that needs to be retrieved for the app.\r\n        firestoreGetDataOnce(path, stateId);\r\n    }\r\n};\r\n\r\n/** \r\n* @description Writes a document to Firestore database. For document paths, updates the document value. For collections, pushes document to collection.\r\n* Naming: Even number of segments in path for documents or even for collections (group of documents)\r\n* @param {String} path - The firestore path to store data to.\r\n* @param {*} data - The data to be stored.\r\n* @param {String} context - The context that is requesting the storage. The read function can request a write with 'firestore' context. \r\n* The write function will call the storage function. Thanks to context the firestoreWrite function exits, this way read/write loops can be avoided.\r\n* @param {String} documentId - Optional for collections. If the document id is specified, rather than pushing a new document, the corresponding documentId document is updated.\r\n* @example\r\n* ```javascript \r\n*   path = events;  documentID = 'event123'  \r\n*                            data = {event}; //Updates {event123} with {event}\r\n*   path = events;           data = {event}; //Pushes {event} to [events] collection\r\n*   path = events/event123;  data = {event}; //Updates {event123} with {event}\r\n*   path = @collection       data = {event}; //Warning: Not a good pattern to use variables at collection level for security reasons. \r\n*                                            //Replaces @collection with state variable value and adds a new document to the collection.\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst firestoreWrite = (path) => async (data, context = '', documentId) => {\r\n    if(context === 'firestore') return;//This means firestore has read a value and is updating the state, no need to write to the database \r\n    if(!path) return;\r\n    const finalPath = documentId != null ?\r\n        readPath(path).concat('/', documentId.toString()) : readPath(path);\r\n    //If the path is even, modify the document\r\n    if(finalPath.split('/').length % 2 === 0) {\r\n        try {\r\n            const docRef = await setDoc(doc(ONEJS.firestore, finalPath),\r\n                {...{timestamp: new Date().getTime()}, ...data});\r\n        }\r\n        catch(error) {console.error(\"Error writing document: \", error);}\r\n    }\r\n    //If the path is odd, push document to collection. The id is automatically generate by firestore in the database\r\n    else {\r\n        try {\r\n            const docRef = await addDoc(collection(ONEJS.firestore, finalPath),\r\n                {...{timestamp: new Date().getTime()}, ...data});\r\n        }\r\n        catch(error) {console.error(\"Error purshing to collection: \", error);}\r\n    }\r\n};\r\n/** \r\n* @description Removes a document from the Firestore database. It can remove collections of documents but it is strongly not advised.\r\n* Naming: Even number of segments in path for documents or even for collections (group of documents)\r\n* @param {String} path - The firestore path to the document. Number of segments should be even. Warning: If the path is odd, it will clear the entire collection.\r\n* @param {String} documentId - Optional for collections. If the document id is specified, the corresponding document with id equal to documentId will be removed.\r\n* @example\r\n* ```javascript \r\n*   path = events;           data = {event}; //Removes entire events collection. Not advised.\r\n*   path = events/event123;  data = {event}; //Removes document with id 'event123'\r\n*   path = events/@eventId;  data = {event}; //Replaces @eventId (calling readPath) with state variable value and removes document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst firestoreRemove = (path) => async (documentId) => {\r\n    if(!path) return;\r\n    const finalPath = documentId != null ?\r\n        readPath(path).concat('/', documentId.toString()) : readPath(path);\r\n    //If the path is even, remove the document\r\n    if(finalPath.split('/').length % 2 === 0) {\r\n        try {const docRef = await deleteDoc(doc(ONEJS.firestore, finalPath));}\r\n        catch(error) {console.error(\"Error removing document: \", error);}\r\n    }\r\n    //If the path is odd, delete entire collection\r\n    else {\r\n        //To delete an entire collection or subcollection in Cloud Firestore, \r\n        //retrieve all the documents within the collection or subcollection and delete them\r\n        //Deleting collections from a Web client is not recommended.\r\n        const collRef = collection(ONEJS.firestore, readPath(path));\r\n        try {\r\n            const collSnap = await getDocs(collRef);\r\n            collSnap.forEach(async docData => await deleteDoc(doc(ONEJS.firestore,\r\n                finalPath + '/' + docData.id)));\r\n        } catch(error) {console.error(\"Error reading snapshot: \", error);}\r\n    }\r\n};\r\n\r\n\r\n//=============================================================================\r\n// INDEXED DATABASE SETUP: This is an optional module that allows the user to work\r\n// with the web-native indexedDB database in a declarative way.\r\n// 1. Setup the state configuration to use firestore as the source or storge option\r\n// const state = {events: {default: [], source: {indexedDB: 'events'}, \r\n//     storage: {indexedDB: 'events'}}, ...};\r\n// 2. Intialize the app() function with the firestore database\r\n// app({component: App, state: state, firestore: firestore});\r\n//\r\n//=============================================================================\r\n\r\n/** \r\n* @description Reads document/collection from indexedDB API.\r\n* Naming: 2 number of segments in path for documents or 1 for collections (group of documents). As opposed to firebase, there are no nested collections.\r\n* Use-case: Online storage (Firestore) is oriented to store information from all users. Local storage aims to store information from current user only (e.g: Settings).\r\n* References: \r\n* [Google Tutorial]{@link https://developers.google.com/web/ilt/pwa/working-with-indexeddb}\r\n* [W3 Tutorial]{https://www.w3.org/TR/IndexedDB-2/}\r\n* [Can I Use]{https://caniuse.com/#feat=indexeddb2}\r\n* @param {String} path - The indexedDB path to the document or collection to be retrieved.\r\n* @param {String} stateId - The id of the state variable that will store the retrieved data.\r\n* @param {String} context - The context that is requesting this data. This function writes the state using the 'indexedDB' context, \r\n* it will exit if read is called again with 'indexedDB' context. This way read/write loops can be avoided\r\n\r\n* @example\r\n* Static Path Examples:\r\n* ```javascript \r\n*    path = events           //Returns array of events []\r\n*    path = events/event123  //Returns event object with id = event123 {}\r\n* ```\r\n* Dynamic Path Examples:\r\n* ```javascript \r\n*   path = @collectionId    //Returns array of events []. This is not recommended for security reasons, state variables in the path should be at document level\r\n*   path = events/@eventId  //Replaces @eventId (calling readPath) with state variable value and returns event object\r\n* ``` \r\n* @returns {void}\r\n*/\r\nconst indexedDBRead = (path) => (stateId, context = '') => {\r\n    if(context === 'indexedDB') return;\r\n    if(!path) return;\r\n    if(path.includes('@') && context === 'initialize') {//Subscribes for state changes during 'setupState' initialization\r\n        window.addEventListener(readPath(path) + 'stateChange', async (e) => {//Note: e.detail also contains the newState\r\n            if(!read(readPath(path))) return;//If the state is not defined return.\r\n            const pathSegments = readPath(path).split('/').filter(Boolean);\r\n            try {\r\n                const transaction = ONEJS.idb.transaction(pathSegments[0], 'readonly');\r\n                const store = transaction.objectStore(pathSegments[0]);\r\n                const request = pathSegments.length > 1 ?\r\n                    store.get(pathSegments[1]) : store.getAll();//Depending of path segments, read entire collection or specific document\r\n                request.onsuccess = function(data) {\r\n                    write(stateId, request.result, 'indexedDB', 'update');\r\n                };\r\n                request.onerror = function(e) {console.error('Error: ', e.target.error.name);};\r\n            }\r\n            catch(error) {console.error(\"Error getting document:\", error);}\r\n        }, false);\r\n    }\r\n    // As opposed to Firestore's 'onSnapshot' method, there is no option to observe changes in indexedDB. Therefore the 'read' function\r\n    // is triggered everytime the 'write' function is called.\r\n    const pathSegments = readPath(path).split('/').filter(Boolean);\r\n    try {\r\n        const transaction = ONEJS.idb.transaction(pathSegments[0], 'readonly');\r\n        const store = transaction.objectStore(pathSegments[0]);\r\n        const request = pathSegments.length > 1 ? store.get(pathSegments[1]) : store.getAll();//Depending of path segments, read entire collection or specific document\r\n        request.onsuccess = function(data) {write(stateId, request.result, 'indexedDB', 'update');};\r\n        request.onerror = function(e) {console.error('Error: ', e.target.error.name);};\r\n    }\r\n    catch(error) {console.error(\"Error getting document:\", error);}\r\n};\r\n/** \r\n* @description Writes a document to indexedDB database. For document paths, updates the document value. For collections, pushes document to collection.\r\n* Naming: 2 number of segments in path for documents or 1 for collections (group of documents). As opposed to firebase, there are no nested collections.\r\n* @param {String} path - The indexedDB path to store data to.\r\n* @param {*} data - The data to be stored.\r\n* @param {String} context - The context that is requesting the storage. The read function can request a write with 'indexedDB' context. \r\n* The write function will call the storage function. Thanks to context the indexedDBWrite function exits, this way read/write loops can be avoided.\r\n* @param {String} documentId - Optional for collections. If the document id is specified, rather than pushing a new document, the corresponding documentId document is updated.\r\n* @example\r\n* ```javascript \r\n*   path = events;  documentID = 'event123'  \r\n*                            data = {event}; //Updates {event123} with {event}\r\n*   path = events;           data = {event}; //Pushes {event} to [events] collection\r\n*   path = events/event123;  data = {event}; //Updates {event123} with {event}\r\n*   path = @collection       data = {event}; //Warning: Not a good pattern to use variables at collection level for security reasons. \r\n*                                            //Replaces @collection with state variable value and adds a new document to the collection.\r\n*   path = events/@eventId;  data = {event}; //Replaces @eventId (calling readPath) with state variable value and updates document with {event}\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst indexedDBWrite = (path) => (data, context = '', documentId) => {\r\n    if(context === 'indexedDB') return;\r\n    if(!path) return;\r\n    const pathSegments = readPath(path).split('/').filter(Boolean);\r\n    if(documentId != null) {//Update specific document within collection \r\n        pathSegments[1] = documentId;\r\n        data.id = documentId;\r\n    }\r\n    try {\r\n        const transaction = ONEJS.idb.transaction(pathSegments[0], 'readwrite');\r\n        const store = transaction.objectStore(pathSegments[0]);\r\n        //Due to the { keyPath: \"id\", autoIncrement: true } configuration .put() function does not need the document id, it needs to be contained in the data object\r\n        const request = pathSegments.length > 1 ? store.put(data) : store.add(data);//To add to collection or update document\r\n        request.onerror = function(e) {console.error('Error: ', e.target.error.name);};\r\n    }\r\n    catch(error) {console.error(\"Error writing document:\", error);}\r\n};\r\n/** \r\n* @description Removes a document or collection of documents from the indexedDB database.\r\n* Naming: 2 number of segments in path for documents or 1 for collections (group of documents). As opposed to firebase, there are no nested collections.\r\n* Note: In this case, it is rather safe to clear entire collection as it is contained within the users memory and not a global database online as it is for Firestore.\r\n* @param {String} path - The indexedDB path to the document. Number of segments should be even. Warning: If the path is odd, it will clear the entire collection.\r\n* @param {String} documentId - Optional for collections. If the document id is specified, the corresponding document with id equal to documentId will be removed.\r\n* @example\r\n* ```javascript \r\n*   path = events;           //Removes entire events collection. Not advised.\r\n*   path = events/event123;  //Removes document with id 'event123'\r\n*   path = events/@eventId;  //Replaces @eventId (calling readPath) with state variable value and removes document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst indexedDBRemove = (path) => (documentId) => {\r\n    if(!path) return;\r\n    const pathSegments = readPath(path).split('/').filter(Boolean);\r\n    if(documentId != null) pathSegments[1] = parseInt(documentId);\r\n    try {\r\n        const transaction = ONEJS.idb.transaction(pathSegments[0], 'readwrite');\r\n        const store = transaction.objectStore(pathSegments[0]);\r\n        const request = pathSegments.length > 1 ?\r\n            store.delete(parseInt(pathSegments[1])) : store.clear();//To remove entire collection or specific document\r\n        request.onerror = function(e) {console.error('Error: ', e.target.error.name);};\r\n    }\r\n    catch(error) {console.error(\"Error removing document:\", error);}\r\n};\r\n\r\n//=============================================================================\r\n// LOCAL STORAGE: This is an optional module that allows the user to work\r\n// with the web-native localStorage database in a declarative way.\r\n// localStorage is similar to sessionStorage, except that while localStorage data \r\n// has no expiration time, sessionStorage data gets cleared when the page session\r\n// end. Data is internally stored in string format.\r\n// 1. Setup the state configuration to use 'local' as the source or storge option\r\n// const state = {userId: {default: '', source: {local: 'userId'}, \r\n//     storage: {local: 'userId'}}, ...};\r\n// 2. Use the read and update functions to access the data and store a new value\r\n// respectively\r\n// const template = () => [Text()('User Id: ' + read('userId')),\r\n//                         Input({type:'text', onInput: update('userId')})]              \r\n//=============================================================================\r\n\r\n/** \r\n* @description Reads document from localStorage API.\r\n* Naming: It is a flat structure, there are no collections.\r\n* Use-case: Online storage (Firestore) is oriented to store information from all users. Local storage aims to store information from current user only (e.g: Settings).\r\n* References: \r\n* [W3 Tutorial]{https://www.w3.org/jsref/prop_win_localstorage.asp}\r\n* @param {String} path - The indexedDB path to the document or collection to be retrieved.\r\n* @param {String} stateId - The id of the state variable that will store the retrieved data.\r\n* @example\r\n* ```javascript \r\n*    path = userId //Returns the stored value for userId {id: '123', name: 'user'}\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst localStorageRead = (path) => (stateId) => {\r\n    try {\r\n        const jsonValue = localStorage.getItem(path); //Note that variable paths are not accepted here. Virtually no use-case for this.\r\n        if(jsonValue === null) return;                //The Web Storage Specification requires that .getItem() returns null for an unknown key\r\n        const data = JSON.parse(jsonValue);           //Using JSON.parse and stringify() allows to store non-string data.\r\n        write(stateId, data, 'localStorage', 'update');\r\n    }\r\n    catch(error) {console.error(\"Error getting document:\", error);}\r\n};\r\n/** \r\n* @description Writes a document to localStorage.\r\n* Naming: It is a flat structure, there are no collections.\r\n* @param {String} path - The localStorage path to store data to.\r\n* @param {*} data - The data to be stored.\r\n* @param {String} context - The context that is requesting the storage. The read function can request a write with 'local' context. \r\n* The write function will call the storage function. Thanks to context the localStorageWrite function exits, this way read/write loops can be avoided.\r\n* @example\r\n* ```javascript \r\n*   path = 'userData'; data = {id: '123', name: 'user'}; //Pushes {data} in 'userData' document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst localStorageWrite = (path) => (data, context = '') => {\r\n    if(context === 'localStorage') return;\r\n    try {\r\n        const jsonData = JSON.stringify(data);\r\n        localStorage.setItem(path, jsonData);\r\n    }\r\n    catch(error) {console.error(\"Error setting document:\", error);}\r\n};\r\n/** \r\n* @description Removes a document from localStorage.\r\n* Naming: It is a flat structure, there are no collections.\r\n* @param {String} path - The localStorage path to the document.\r\n* @example\r\n* ```javascript \r\n*   path = userId; //Removes userId document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst localStorageRemove = (path) => () => {\r\n    try {\r\n        localStorage.removeItem(path);\r\n    }\r\n    catch(error) {console.error(\"Error removing document:\", error);}\r\n};\r\n\r\n//=============================================================================\r\n// NATIVE STORAGE: This is an optional module that allows the user to work\r\n// with the React Native AsyncStorage database in a declarative way.\r\n// Community Package: https://github.com/react-native-async-storage/async-storage.\r\n// 1. Setup the state configuration to use 'local' as the source or storge option\r\n// const state = {userId: {default: '', source: {local: 'userId'}, \r\n//     storage: {local: 'userId'}}, ...};\r\n// 2. Use the read and update functions to access the data and store a new value\r\n// respectively\r\n// const template = () => [Text()('User Id: ' + read('userId')),\r\n//                         Input({type:'text', onInput: update('userId')})]              \r\n//=============================================================================\r\n/** \r\n* @description Reads document from AsyncStorage API.\r\n* Naming: It is a flat structure, there are no collections.\r\n* Use-case: Online storage (Firestore) is oriented to store information from all users. Native storage aims to store information from current user only (e.g: Settings).\r\n* References: \r\n* [Async Storage Docs]{https://react-native-async-storage.github.io/async-storage/}\r\n* @param {String} path - The indexedDB path to the document or collection to be retrieved.\r\n* @param {String} stateId - The id of the state variable that will store the retrieved data.\r\n* @example\r\n* ```javascript \r\n*    path = userId //Returns the stored value for userId {id: '123', name: 'user'}\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst nativeStorageRead = (path) => async (stateId) => {\r\n    try {\r\n        const jsonValue = await OSSPECIFICS.AsyncStorage.getItem(path);   //Note that variable paths are not accepted here. Virtually no use-case for this.\r\n        if(jsonValue === null) return;                      //The Async Storage Specification requires that .getItem() returns null for an unknown key\r\n        const data = JSON.parse(jsonValue);                   //Using JSON.parse and stringify() allows to store non-string data.\r\n        write(stateId, data, 'AsyncStorage', 'update');\r\n    }\r\n    catch(error) {console.error(\"Error getting document:\", error);}\r\n};\r\n/** \r\n* @description Writes a document to AsyncStorage.\r\n* Naming: It is a flat structure, there are no collections.\r\n* @param {String} path - The AsyncStorage path to store data to.\r\n* @param {*} data - The data to be stored.\r\n* @param {String} context - The context that is requesting the storage. The read function can request a write with 'local' context. \r\n* The write function will call the storage function. Thanks to context the AsyncStorageWrite function exits, this way read/write loops can be avoided.\r\n* @example\r\n* ```javascript \r\n*   path = 'userData'; data = {id: '123', name: 'user'}; //Pushes {data} in 'userData' document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst nativeStorageWrite = (path) => async (data, context = '') => {\r\n    if(context === 'AsyncStorage') return;\r\n    try {\r\n        const jsonData = JSON.stringify(data);\r\n        await OSSPECIFICS.AsyncStorage.setItem(path, jsonData);\r\n    }\r\n    catch(error) {console.error(\"Error setting document:\", error);}\r\n};\r\n\r\n/** \r\n* @description Removes a document from AsyncStorage.\r\n* Naming: It is a flat structure, there are no collections.\r\n* @param {String} path - The AsyncStorage path to the document.\r\n* @example\r\n* ```javascript \r\n*   path = userId; //Removes userId document\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst nativeStorageRemove = (path) => async () => {\r\n    try {\r\n        await OSSPECIFICS.AsyncStorage.removeItem(path);\r\n    }\r\n    catch(error) {console.error(\"Error removing document:\", error);}\r\n};\r\n\r\n//=============================================================================\r\n// STATE: The state represents the mutable dimension of the app. Following a pure\r\n// functional programming paradigm, all the functions give the same output provided\r\n// with the same input (immutability) and do not change the state internally (no\r\n// side effects).\r\n// All the state of the app is contained in a single object and is created through\r\n// the configuration provided.\r\n// In order to modify the state, the user can use the read, add, update and remove\r\n// functions in the app template (never inside components).\r\n// 1. Define all the mutable variables required for the app and how they will be \r\n// sourced and stored. Use a single provider for each state variable (E.g.: do not\r\n// mix firestore and indexedDB)\r\n// 2. Use the read, add, update and remove functions to modify the state based on\r\n// user actions (click, input, drag, etc.).\r\n//=============================================================================\r\n\r\n/** \r\n* @summary Reads the current value of the corresponding state variable.\r\n* @description This is the main function to return the current value for the state variable of the app.\r\n* Structure functions (components) cannot access or modify state, they can only generate events and the functions input for those events can modify the state.\r\n* Use-case: Used within the template to access the variables needed to render the app. When these variables are modified, the rerender function \r\n* is called again getting the new state of the app.\r\n* @param {String} stateId - The unique name given to the state variable.\r\n* @example\r\n* ```javascript \r\n*   const state = {toWhom: {default: 'World'}};\r\n*   const template = () => Text()('Hello ' + read('toWhom') + '!');\r\n* ```\r\n* @returns {String} Returns the value for the corresponding state variable.\r\n*/\r\nexport const read = (stateId, documentId) => {\r\n    // return ONEJS.reactState[stateId];//Not reading from React directly as writing the state takes some time and when read is called the value is not updated.\r\n    // return ONEJS.currentState[stateId] != null ? ONEJS.currentState[stateId].value : undefined;\r\n    //Find documentId in array\r\n    if(documentId) {\r\n        return ONEJS.currentState[stateId]?.value[ONEJS.currentState[stateId].value.findIndex(\r\n            doc => doc.id === documentId)] \r\n    }\r\n    return ONEJS.currentState[stateId]?.value;\r\n};\r\n\r\n/** \r\n* @description Internal function to modify the state. It is the only function able to access and modify the state.\r\n* Use-case: This function is called internally to write a new value into the state variable and save the value in the storage.\r\n* @param {String} stateId - The unique name given to the state variable.\r\n* @param {*} newValue - The new value to be written in the state variable.\r\n* @param {String} context - The context that is requesting the write. Externally the 'app' context will be used. Internally: local, firestore or indexedDB.\r\n* @param {String} action - The type of action that will be performed on the state: add, remove, update or updateArray.\r\n* @param {String} documentId - For array operations, it is the element in the array that needs to be modified.\r\n* @example\r\n* ```javascript \r\n*   write('events', {id: '123', name: {'party'}}, 'app', 'arrayUpdate', '123');\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst write = (stateId, newValue, context = '', action = 'update', documentId) => {\r\n    const oldValue = ONEJS.currentState[stateId].value;\r\n    if(oldValue === newValue) return;\r\n\r\n    if(action === 'add') {//Adds value to array state variable\r\n        ONEJS.currentState[stateId].value.push(newValue);\r\n        ONEJS.reactSetState[stateId]([...ONEJS.currentState[stateId].value]);//We need to clone the array with the spread syntax, otherwise leads to unexpected behaviour.\r\n    }\r\n    else if(action === 'remove') {\r\n        if(documentId != null) {//Remove value from array state variable\r\n            const index = ONEJS.currentState[stateId].value.findIndex(doc => doc.id === documentId);\r\n            if(index === -1) return;\r\n            ONEJS.currentState[stateId].value.splice(index, 1);\r\n            ONEJS.reactSetState[stateId]([...ONEJS.currentState[stateId].value]);\r\n            \r\n        }\r\n        else {//Remove the value from the state variable\r\n            newValue = Array.isArray(oldValue) ? [] : undefined;\r\n            ONEJS.currentState[stateId].value = newValue;\r\n            ONEJS.reactSetState[stateId](newValue);//*REACT SPECIFIC: Use setState function to update the state and trigger rerender*\r\n        }\r\n    }\r\n    else if(action === 'updateArray') {//Update value from array state variable\r\n        const index = ONEJS.currentState[stateId].value.findIndex(doc => doc.id === documentId);\r\n        if(index === -1) return;\r\n        ONEJS.currentState[stateId].value[index] = newValue;\r\n        ONEJS.reactSetState[stateId]([...ONEJS.currentState[stateId].value]);\r\n    }\r\n    else if(action === 'update') {//Update value from state variable\r\n        ONEJS.currentState[stateId].value = newValue;\r\n        ONEJS.reactSetState[stateId](newValue);//*REACT SPECIFIC: Use setState function to update the state and trigger rerender*\r\n    }\r\n    else return;\r\n\r\n    if(context === 'stateHistory') return;//If the context is 'stateHistory' do not perform any actions on the database\r\n    saveState(stateId, oldValue, ONEJS.currentState[stateId].value, context, action, documentId);//Save the state configuration delta to be able to track the history of the state\r\n\r\n    if(ONEJS.currentState[stateId].removal && action === 'remove') {\r\n        ONEJS.currentState[stateId].removal(documentId);\r\n    }\r\n    if(ONEJS.currentState[stateId].storage && action !== 'remove') {\r\n        ONEJS.currentState[stateId].storage(newValue, context, documentId);\r\n    }//Context checks if the source path is equal to the target path to avoid calling storage innecessarity\r\n    if(ONEJS.currentState[stateId].onChange) {\r\n        ONEJS.currentState[stateId].onChange(oldValue, newValue, stateId);\r\n    };//Called to perform additional actions on change\r\n    if(ONEJS.currentState[stateId].alert) {\r\n        window.dispatchEvent(new CustomEvent(stateId + 'stateChange', {detail: newValue}));\r\n    }//Called when the state variable is required to alert when changes by other state var. E.g.: user: /users/@userId, userID: '1234' (watched variable)\r\n    if(ONEJS.currentState[stateId].source && action === 'add') {\r\n        ONEJS.currentState[stateId].source(stateId, context);\r\n    }//When adding a new document into a collection, source is called to retrieve from the database the id for the recently added document.\r\n};\r\n\r\n/** \r\n* @description External function to modify the state. Adds a new value into the state variable array and saves it in the storage.\r\n* Use-case: Used to add a new document to the collection in the database.\r\n* Note: The reason why the second argument 'event' is curried, is to allow to pass this function to user events (E.g: onInput, onClick), in these cases,\r\n* the event.target.value (e.target.checked in the case of checkbox) holds the new value to be updated.\r\n* @param {String} stateId - The unique name given to the state variable.\r\n* @param {*} event - The event containing the value or the value itself.\r\n* @example\r\n* ```javascript \r\n*   const template = () => [Input({ type: 'text, onInput: add('events') })];\r\n*   const template = () => [Button({ onClick: (e) => add('events')({id: '123', name: {'party'}}) })]; \r\n* ```\r\n* @returns {void}\r\n*/\r\nexport const add = (stateId) => event => {\r\n    const newValue = (event?.target) ?\r\n        (event.target.type === 'checkbox' ? event.target.checked : event.target.value) : event;\r\n    const context = 'app';//External context\r\n    const action = 'add';\r\n    write(stateId, newValue, context, action);\r\n};\r\n\r\n/** \r\n* @description External function to modify the state. Updates the value of state variables on input change events and saves it in the storage.\r\n* Use-case: React to user events updating the state.\r\n* Note: The reason why the second argument 'event' is curried, is to allow to pass this function to user events (E.g: onInput, onClick), in these cases,\r\n* the event.target.value (e.target.checked in the case of checkbox) holds the new value to be updated.\r\n* @param {String} stateId - The unique name given to the state variable.\r\n* @param {String} documentId - If the state is an array of objects, corresponds to the {id} property within the object to be matched.\r\n* @param {*} event - The event containing the value or the value itself.\r\n* @example\r\n* ```javascript \r\n*   const template = () => [Input({ type: 'text, onInput: update('userId') })]; //Every time the input changes updates the value of 'user'\r\n*   const template = () => [Button({ onClick: (e) => update('events', '123')({name: 'new party'}) })]; //Every time is clicked sets the same value\r\n* ```\r\n* @returns {void}\r\n*/\r\nexport const update = (stateId, documentId) => (event) => {\r\n    // if(typeof constValue !== 'undefined') write(stateId, constValue);//For the moment not adding this option update = (stateId, constValue) => (event), it is anti-pattern\r\n    const newValue = (event?.target) ?\r\n        (event.target.type === 'checkbox' ? event.target.checked : event.target.value) : event;\r\n    const context = 'app';//External context\r\n    const action = documentId != null ? 'updateArray' : 'update';//Set the value within an array or update the value entirely\r\n    write(stateId, newValue, context, action, documentId);\r\n};\r\n\r\n/** \r\n* @description External function to modify the state. Removes the value from the state variable on input change events and saves it in the storage.\r\n* Use-case: React to user events removing the value from the state.\r\n* @param {String} stateId - The unique name given to the state variable.\r\n* @param {String} documentId - If the state is an array of objects, corresponds to the {id} property within the object to be matched.\r\n* @example\r\n* ```javascript \r\n*   const template = () => [Button({ onClick: (e) => remove('userId') })]; //Every time is clicked sets 'userId' to undefined\r\n*   const template = () => [Button({ onClick: (e) => remove('events', '123') })]; //Every time removes event '123' from the 'events' array\r\n* ```\r\n* @returns {void}\r\n*/\r\nexport const remove = (stateId, documentId) => {\r\n    const newValue = undefined;\r\n    const context = 'app';//External context\r\n    const action = 'remove';//Set the value within an array or update the value entirely\r\n    write(stateId, newValue, context, action, documentId);\r\n};\r\n\r\n/**\r\n* @typedef  {Object}  Config - The configuration structure required by setupState function.\r\n* @property {*}       default               - The default value for the state.\r\n* \r\n* @property {Object}  [source]              - Source for the state variable. If defined, choose one and only one of the providers below for each state variable.\r\n* @property {String}  [source.url]          - The url to extract data from. The data segment is indicated with ':'\r\n* @property {String}  [source.firestore]    - The path to the firestore document or collection.\r\n* @property {String}  [source.indexedDB]    - The path to the indexedDB document or collection.\r\n* @property {Array<String>}[source.collections] - Only for indexedDB using a state variable at collection level, declare all the collections to read from.\r\n*                                                 Possibly removed in future updates, as it goes against database best practices.\r\n* @property {String}  [source.local]        - The path to the local storage document.\r\n* @property {Function}[source.function]     - A function to be called on every read (rerender). You may choose to pull data from your own database here. \r\n* \r\n* @property {Object}  [storage]             - Storage for the state variable. If defined, choose one and only one of the providers below for each state variable.\r\n* @property {String}  [storage.firestore]   - The path to the firestore document or collection.\r\n* @property {String}  [storage.indexedDB]   - The path to the indexedDB document or collection.\r\n* @property {Array<String>}[storage.collections] - Only for indexedDB using a state variable at collection level, declare all the collections to write to.\r\n*                                                 Possibly removed in future updates, as it goes against database best practices.\r\n* @property {String}  [storage.local]       - The path to the local storage document.\r\n* @property {Function}[storage.function]    - A function to be called on every write (state update). You may choose to push data to your own database here.\r\n*  \r\n* @property {Function}[onChange]            - A function to be called on every state read/write. Deprecated in favor of source.function and storage.function. \r\n*/\r\n\r\n/** \r\n* @description Sets up the state based on the configuration object. All the state variables to be used and their default values need to declared in this configuration.\r\n* @param {Config} config - The configuration required to set up the state of the app.\r\n* @example\r\n* ```javascript \r\n*   const config = {\r\n*       userId: '123',\r\n*       events: {default: [], source: {firestore: 'events'}, storage: {firestore: 'events'}},\r\n*       selectedEventId: {default: '', source: {url: '/events/:'}},\r\n*       selectedEvent: {default: {}, source: {firestore: 'events/@selectedEventId'}, storage: {firestore: 'events/@selectedEventId'}}\r\n*   }\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst setupState = (config) => {\r\n    const indexedDBCollections = [];  //All the collections required to be initialized for indexedDB \r\n    const indexedDBStateIds = {};     //All the state id-s that need to be updated with indexedDB data\r\n\r\n    //1. Create all the state variables to make sure they exist\r\n    Object.entries(config).forEach(([stateId, value]) => {\r\n        //Set default value for state variable\r\n        ONEJS.currentState[stateId] = {};\r\n        // ONEJS.currentState[stateId].value = value?.default ?? value;\r\n        if(value && typeof value === 'object' && value.hasOwnProperty('default')) {\r\n            ONEJS.currentState[stateId].value = value['default'];\r\n        }\r\n        else ONEJS.currentState[stateId].value = value;\r\n    });\r\n\r\n    //2. Set the storage functions. They need to be set before source, as source functions modify the state\r\n    Object.entries(config).forEach(([stateId, value]) => {\r\n        //If defined by the user, use Firestore as the storage option.\r\n        if(value?.storage?.firestore) {\r\n            ONEJS.currentState[stateId].storage = firestoreWrite(value.storage.firestore);\r\n            ONEJS.currentState[stateId].removal = firestoreRemove(value.storage.firestore);\r\n        }\r\n        //If defined by the user, use IndexedDB as the storage option\r\n        else if(value?.storage?.indexedDB) {\r\n            ONEJS.currentState[stateId].storage = indexedDBWrite(value.storage.indexedDB);\r\n            ONEJS.currentState[stateId].removal = indexedDBRemove(value.storage.indexedDB);\r\n            let collections = [value.storage.indexedDB.split('/').filter(Boolean)[0]];//Note: On collections better to avoid using state variables (@stateId)\r\n\r\n            if(value.storage.collections && value.storage.collections.length) {\r\n                collections = value.storage.collections;\r\n            }//Array specifying which are the collections will be accessed. Only required for collection variable path.\r\n            collections.forEach(collection => {\r\n                indexedDBCollections.indexOf(collection) === -1 ?\r\n                    indexedDBCollections.push(collection) : null;\r\n            });\r\n        }\r\n        //If defined by the user, use Local Storage as the storage option\r\n        else if(value?.storage?.local) {\r\n            if(OSSPECIFICS.os === 'web') {\r\n                ONEJS.currentState[stateId].storage = localStorageWrite(value.storage.local);\r\n                ONEJS.currentState[stateId].removal = localStorageRemove(value.storage.local);\r\n            }\r\n            else if(OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android') {\r\n                ONEJS.currentState[stateId].storage = nativeStorageWrite(value.storage.local);\r\n                ONEJS.currentState[stateId].removal = nativeStorageRemove(value.storage.local);\r\n            }\r\n        }\r\n        //If defined by the user, use any function to set the storage. It will be called on write()\r\n        else if(value?.storage?.function) {\r\n            ONEJS.currentState[stateId].storage = value.storage.function;\r\n        }\r\n    });\r\n\r\n    //3. set up the source functions and retrieve the initial values\r\n    Object.entries(config).forEach(([stateId, value]) => {\r\n        //If defined by the user, use the url as the source of data\r\n        if(value?.source?.url) {\r\n            readUrl(value.source.url)(stateId);\r\n        }\r\n        //If defined by the user, use Firestore database as the source of data.\r\n        else if(value?.source?.firestore) {\r\n            if(readPathState(value.source.firestore)) {\r\n                ONEJS.currentState[readPathState(value.source.firestore)].alert = true;//In case the path includes a state variable, alert for changes\r\n                ONEJS.currentState[stateId].source = firestoreRead(value.source.firestore);//This is required for collections, when we insert a document by querying the source we retrieve the document id\r\n            }\r\n            firestoreRead(value.source.firestore)(stateId, 'initialize');\r\n        }\r\n        //If defined by the user, use IndexedDB as the source option\r\n        else if(value?.source?.indexedDB) {\r\n            ONEJS.currentState[stateId].source = indexedDBRead(value.source.indexedDB);\r\n            if(readPathState(value.source.indexedDB)) {\r\n                ONEJS.currentState[readPathState(value.source.indexedDB)].alert = true;\r\n            }//In case the path includes a state variable, alert for changes\r\n            let collections = [value.source.indexedDB.split('/').filter(Boolean)[0]];//Note: On collections better to avoid using state variables (@stateId)\r\n            if(value.source.collections && value.source.collections.length) {\r\n                collections = value.source.collections;\r\n            }//Array specifying which are the collections will be accessed. Only required for collection variable path.\r\n            collections.forEach(collection => {\r\n                indexedDBCollections.indexOf(collection) === -1 ?\r\n                    indexedDBCollections.push(collection) : null;\r\n            });\r\n            indexedDBStateIds[stateId] = value.source.indexedDB;\r\n        }\r\n        //If defined by the user, use Local Storage as the source option\r\n        else if(value?.source?.local) {\r\n            if(OSSPECIFICS.os === 'web') localStorageRead(value.source.local)(stateId);\r\n            else if(OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android')\r\n                nativeStorageRead(value.source.local)(stateId);\r\n        }\r\n        //If defined by the user, use any function to set the storage. It will be called on write()\r\n        //Otherwise, user can use any function to source data for the state variable. It will be called once during setupState, the user should subscribe to changes to the source in this function to update the state. \r\n        else if(value?.source?.function) {\r\n            ONEJS.currentState[stateId].source = value.source.function;\r\n            ONEJS.currentState[stateId].source(stateId);\r\n        }\r\n    });\r\n\r\n    //Sets up the indexedDB tables to use as source/storage\r\n    if(Object.keys(indexedDBCollections).length > 0) {\r\n        if(!('indexedDB' in window)) {//Check for support\r\n            console.error('IndexedDB not supported.');\r\n            return;\r\n        }\r\n        //Check the current version and the collections setup in that version. If the collections change, increase the version number and store those collections\r\n        const versionString = localStorage.getItem('oneIndexedDBVersion' + ONEJS.appName);\r\n        let version = versionString ? parseInt(versionString) : undefined;\r\n        let collectionsJson = localStorage.getItem('oneIndexedDBCollections' + ONEJS.appName);\r\n        const collections = collectionsJson != null ? JSON.parse(collectionsJson) : undefined;\r\n\r\n        if(!collections) {//No collections existing: Store collections and upgrade version\r\n            collectionsJson = JSON.stringify(indexedDBCollections);\r\n            localStorage.setItem('oneIndexedDBCollections' + ONEJS.appName, collectionsJson);\r\n            if(!version) version = 1;\r\n            else version = version + 1;\r\n            localStorage.getItem('oneIndexedDBVersion' + ONEJS.appName, version);\r\n        }\r\n\r\n        //Missing collections: Store collections and upgrade version\r\n        else if(!indexedDBCollections.every(collection => collections.includes(collection))) {\r\n            collectionsJson = JSON.stringify(indexedDBCollections);\r\n            localStorage.setItem('oneIndexedDBCollections' + ONEJS.appName, collectionsJson);\r\n            if(!version) version = 1;\r\n            else version = version + 1;\r\n            localStorage.getItem('oneIndexedDBVersion' + ONEJS.appName, version);\r\n        }\r\n\r\n        // indexedDB.deleteDatabase('oneIndexedDB' + ONEJS.appName);\r\n        const openRequest = indexedDB.open('oneIndexedDB' + ONEJS.appName, version);//Open the database connection request\r\n\r\n        //Called for new database or version number increase. The collections to be used (object stores) are declared here.\r\n        //This is the only place to alter the structure of the database: create/remove object stores.\r\n        openRequest.onupgradeneeded = function(e) {\r\n            ONEJS.idb = e.target.result; //IDBDatabase object to create object stores and read/write later\r\n            indexedDBCollections.forEach(path => {\r\n                if(!ONEJS.idb.objectStoreNames.contains(path)) {\r\n                    try {//https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB go to section: 'Structuring the Database'\r\n                        ONEJS.idb.createObjectStore(path, {keyPath: 'id', autoIncrement: true}); //Can only hold JavaScript objects\r\n                    }\r\n                    catch(error) {\r\n                        console.error('IndexedDB Object Store could not be created: ' +\r\n                            error);\r\n                    }\r\n                }\r\n            });\r\n        };\r\n        //If the onupgradeneeded event exits successfully, the onsuccess function will be triggered. Reads the initial data from the database.\r\n        openRequest.onsuccess = function(e) {\r\n            ONEJS.idb = e.target.result;\r\n            Object.entries(indexedDBStateIds).forEach(([stateId, path]) => {\r\n                indexedDBRead(path)(stateId, 'initialize');\r\n            });\r\n        };\r\n        openRequest.onerror = function(e) {console.error('IndexedDB Error'); console.error(e);};\r\n    }\r\n};\r\n\r\n/** \r\n* @description Internal function to store the state modification history. Since the state is the only modifiable part of the app, it allows to go back to previous states.\r\n* Use-case: On every write() function call the modification is stored. \r\n* @param {String} stateId  - The unique name given to the state variable that is being modified.\r\n* @param {*}      newValue - The new value to be written in the state variable.\r\n* @param {*}      oldValue - The previous value to the state modification.\r\n* @param {String} context  - The context used to  is requesting the write. Externally the 'app' context will be used. Internally: local, firestore or indexedDB.\r\n* @param {String} action  - The type of action that modifies the state: add, remove, update or updateArray.\r\n* @param {String} documentId - For array operations, it is the element in the array that needs to be modified.\r\n* @example\r\n* ```javascript \r\n*   saveState('events', {id: '123', name: {'party'}}, 'app', 'arrayUpdate', '123');\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst saveState = (stateId, oldValue, newValue, context, action, documentId) => {//0 is the current state, 1 would be the previous state, ... until stateHistorySize.\r\n    if(context === 'stateHistory') return;//This occurs rewind or fastForward functions are being used, therefore no new state needs to be saved.\r\n    if(ONEJS.stateHistoryPosition > 0) {//In case the history is rewinded and the state is modified, erase the previous path.\r\n        ONEJS.stateHistory.splice(0, ONEJS.stateHistoryPosition);\r\n        ONEJS.stateHistoryPosition = 0;\r\n    }\r\n    ONEJS.stateHistory.unshift({\r\n        stateId: stateId, oldValue: oldValue, newValue: newValue, action: action,\r\n        documentId: documentId, timestamp: new Date()\r\n    });\r\n    if(ONEJS.stateHistory.length > ONEJS.stateHistorySize) ONEJS.stateHistory.pop();\r\n};\r\n\r\n/** \r\n* @description External function to go to a certain point in the state modification history. It only works for 'update' events and does not undo database storage.\r\n* @param {Number} statePosition - The unique name given to the state variable that is being modified.\r\n* @example\r\n* ```javascript \r\n*   const template = () => [Button({ onClick: (e) => goToState(4) })]; //Rewinds the state history to the slot number 4 in the array.\r\n* ```\r\n* @returns {void}\r\n* @todo Implement reversal actions: add -> removeArray, update -> update, updateArray -> updateArray, remove -> update, removeArray -> add\r\n* It is challenge to undo add action: for removeArray we need the id of the document added which is not stored. Knowing that 'add' always pushes the document \r\n* at the end of the array, it could be undone by always removing the last element.\r\n*/\r\nexport const goToState = (statePosition) => {\r\n    statePosition = parseInt(statePosition);\r\n    if(statePosition < 0 || statePosition >= ONEJS.stateHistory.length) {\r\n        console.error('Cannot rewind state to: ' + statePosition +\r\n            '. It exceeds stateHistory.length.');\r\n        return;\r\n    }\r\n    else if(statePosition === ONEJS.stateHistoryPosition) {\r\n        return;\r\n    }\r\n    else if(statePosition > ONEJS.stateHistoryPosition) {\r\n        for(let i = ONEJS.stateHistoryPosition; i < statePosition; i++) {\r\n            write(ONEJS.stateHistory[i].stateId, ONEJS.stateHistory[i].oldValue, 'stateHistory');\r\n        }\r\n    }\r\n    else {\r\n        for(let i = ONEJS.stateHistoryPosition - 1; i >= statePosition; i--) {\r\n            write(ONEJS.stateHistory[i].stateId, ONEJS.stateHistory[i].newValue, 'stateHistory');\r\n        }\r\n    }\r\n    ONEJS.stateHistoryPosition = statePosition;\r\n};\r\n/** \r\n* @description Goes to the next (more recent) point in the modification history. \r\n* @example\r\n* ```javascript \r\n*   const template = () => [Button({ onClick: (e) => nextState() })]; //Goes to the next state in the history\r\n* ```\r\n* @todo Until goToState() is fixed it is not production ready.\r\n* @returns {void}\r\n*/\r\nexport const nextState = () => {\r\n    const statePosition = ONEJS.stateHistoryPosition - 1;\r\n    goToState(statePosition);\r\n};\r\n/** \r\n* @description Goes to the previous (less recent) point in the modification history. \r\n* @example\r\n* ```javascript \r\n*   const template = () => [Button({ onClick: (e) => previousState() })]; //Goes to the previous state in the history\r\n* ```\r\n* @todo Until goToState() is fixed it is not production ready.\r\n* @returns {void}\r\n*/\r\nexport const previousState = () => {\r\n    const statePosition = ONEJS.stateHistoryPosition + 1;\r\n    goToState(statePosition);\r\n};\r\n/** \r\n* @description Returns the complete stateHistory array containing the stored modifications to the state.\r\n* @example\r\n* ```javascript \r\n*   readStateHistory().map((value, index) => View()([ View()('Id: ' + value.stateId),\r\n*                                                     View()('Old: ' + value.oldValue), \r\n*                                                     View()('New: ' + value.newValue) ]));\r\n* ```\r\n* @returns {Array} The complete stateHistory array.\r\n*/\r\nexport const readStateHistory = () => {\r\n    return ONEJS.stateHistory;\r\n};\r\n\r\n\r\n//=============================================================================\r\n// COMPONENTS: Components are functions that return a structure to be rendered.\r\n// Every component should only be dependendent upon its input and does not modify \r\n// or maintain state.\r\n// Arguments for component functions can be classified as:\r\n// 1. Parameters: List of inputs unique to our component that are used to shape\r\n//    the behaviour, structure or style.\r\n// 2. Properties: All the properties required to define the componet providing its \r\n//    state. \r\n// 3. Attributes: All the possible attributes that can be input during the execution. \r\n//    E.g: class, hidden, id, etc.\r\n// 3. Structure: Optional for components that can have an internal structure.\r\n//    This arguments is curried. \r\n// Component Definition Example: \r\n// const myComponent = Component({param1 ='default1', paramN, ...attributes}={}) => \r\n//  structure => { \r\n//     return Div(attributes)([Text()('Hello World'), ...structure]);\r\n//  }\r\n// Component Styling Ordered by Priority:\r\n// 1. Inline styles: These styles are inserted directly in the HTML tags. They are not \r\n//    compiled. As much as possible it is recommended to avoid this type.\r\n// 2. Theme and flavor: This is the way to go when customizing componets. Flavor \r\n//    encapsulate css variables that allow to change the look and feel of the component\r\n//    making it blend in with the app. One or more themes may be applied at a time.\r\n// 3. Compiled styles:  These styles can act on nested elements and tags like :hover. \r\n//    They need to be compiled by emotion css into a class that is later assigned \r\n//    to the component.\r\n//\r\n// Intrinsic CSS Priority: \r\n// Inherited styles < * < element < attribute < class < ID < Combined selectors <\r\n// < CSS properties set directly < on element, inside style attribute.\r\n//=============================================================================\r\n\r\n/** \r\n* @description Internal function to memoize component structure in a array to ensure the same reference is always returned.\r\n* For memoize components, if properties do not change, React will skip rendering the component, and reuse the last rendered result.\r\n* Memoizing components can be useful in the following scenarios:\r\n* 1. Pure functional components\r\n* 2. Renders often\r\n* 3. Rerenders with same props\r\n* 4. Medium to big size\r\n* @param {Function | String} ComponentFunction - The component function to be memoized\r\n* @param {Boolean} memoized - True: memoize the component, false: do not memoize the component\r\n* @param {String} name - In order to memoize the component, it needs to be given a unique name.\r\n* @example\r\n* ```javascript \r\n*   memoizeComponent((props)=>Div()('Hello world'), true, 'div');\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst memoizeComponent = (ComponentFunction, memoized, name) => {\r\n    let memoizedComponent = ComponentFunction;\r\n    if(name) {\r\n        if(!ONEJS.memoizedComponents[name]) {\r\n            ONEJS.memoizedComponents[name] = memoized ?\r\n                React.memo(ComponentFunction) : ComponentFunction;\r\n        }\r\n        memoizedComponent = ONEJS.memoizedComponents[name];\r\n    }\r\n    return memoizedComponent;\r\n};\r\n\r\n//=============================================================================\r\n// COMPONENTS: Creation Higher Order Components (HOC)\r\n//Whereas a component transforms props into UI, a higher-order component transforms \r\n// a component into another component: https://en.reactjs.org/docs/higher-order-components.html\r\n// A set of internal functions that take the component function and wrap it to\r\n// create a React element. This is required in order to be able to use hooks inside.\r\n// They cannot be implemented inside the Component function as they would be\r\n// generated everytime the app is rerendered generating a different memory reference.\r\n// When this happens React is unable to compare and optimize changes for every\r\n// iteration. \r\n// STEPS (wrapped components):\r\n// 1. The user writes the component function.\r\n// 2. The user creates the component by wrapping the component function with Component.\r\n// 3.BaseComponent() function calls EnhancedComponent() to wrap the component function\r\n//    in a HOC to provide more functionality.\r\n// 4. Create<...> function creates the React element for the component wrapped by the\r\n//    EnhancedComponent() function\r\n//=============================================================================\r\n\r\n/** \r\n* @description For a given component function, creates a React element that can hold children / internal structure. If the user sets the attribute\r\n* 'memoized' to true, it also memoizes the component for performance optimization. The ComponentFunction has already been wrapped by EnhancedComponent().\r\n* @param {Function | String} ComponentFunction - The component function to be created into a React element.\r\n* @param {Object} attributes - The attributes that will be passed during component instantiation.\r\n* @param {Object} structure - The internal structure that will be passed during component instatiation.\r\n* @example\r\n* ```javascript \r\n*   CreateWrappedComponentWithStructure(props=>structure=>Div(props)(structure))({id: 'myId'})(Text()('Hello World'));\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst CreateWrappedComponentWithStructure = (name, ComponentFunction) => ({...attributes} = {}) =>\r\n    structure => {\r\n        const memoized = memoizeComponent(ComponentFunction, attributes['memoized'], name);\r\n        delete attributes['memoized'];\r\n        return React.createElement(memoized, {structure: structure, ...attributes}, null);\r\n    };\r\n\r\n/** \r\n* @description For a given component function, creates a React element that cannot hold children / internal structure. If the user sets the attribute\r\n* 'memoized' to true, it also memoizes the component for performance optimization. The ComponentFunction has already been wrapped by EnhancedComponent().\r\n* @param {Function | String} ComponentFunction - The component function to be created into a React element.\r\n* @param {Object} attributes - The attributes that will be passed during component instantiation.\r\n* @example\r\n* ```javascript \r\n*   CreateWrappedComponentWithoutStructure(props=>Input(props)({style: {background: 'blue'}});\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst CreateWrappedComponentWithoutStructure = (name, ComponentFunction) =>\r\n    ({...attributes} = {}) => {//Contar por que necesitamos un wrapper para usar los hooks en las funciones\r\n        const memoized = memoizeComponent(ComponentFunction, attributes['memoized'], name);\r\n        delete attributes['memoized'];\r\n        return React.createElement(memoized, attributes); //React uses property \"children\" to setup the component internals\r\n    };\r\n\r\n/** \r\n* @description For a given component function, creates a React element that can hold children / internal structure. If the user sets the attribute\r\n* 'memoized' to true, it also memoizes the component for performance optimization.\r\n* @param {String} name - Unique name for the Component.\r\n* @param {Function | String} ComponentFunction - The component function to be created into a React element.\r\n* @param {Object} attributes - The attributes that will be passed during component instantiation.\r\n* @param {Object} structure - The internal structure that will be passed during component instantiation.\r\n* @example\r\n* ```javascript \r\n*   CreateComponentWithStructure(props=>structure=>Div(props)(structure))({id: 'myId'})(Text()('Hello World'));\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst CreateComponentWithStructure = (name, ComponentFunction) => ({...attributes} = {}) =>\r\n    structure => {\r\n        const uncurriedComponentFunction = ({structure, ...attributes} = {}) =>\r\n            ComponentFunction(attributes)(structure);\r\n        const memoized = memoizeComponent(uncurriedComponentFunction, attributes['memoized'], name);\r\n        delete attributes['memoized'];\r\n        return React.createElement(memoized, {structure: structure, ...attributes}, null);\r\n    };\r\n\r\n/** \r\n* @description For a given component function, creates a React element that cannot hold children / internal structure. If the user sets the attribute\r\n* 'memoized' to true, it also memoizes the component for performance optimization. \r\n* @param {String} name - Unique name for the Component.\r\n* @param {Function | String} ComponentFunction - The component function to be created into a React element.\r\n* @param {Object} attributes - The attributes that will be passed during component instantiation.\r\n* @example\r\n* ```javascript \r\n*   CreateComponentWithoutStructure(props=>Input(props)({style: {background: 'blue'}});\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst CreateComponentWithoutStructure = (name, ComponentFunction) => ({...attributes} = {}) => {\r\n    if(name & attributes['memoized']) {//memoizeComponent cannot be called since passing the component function and returning the same reference creates a loop\r\n        if(!ONEJS.memoizedComponents[name]) {\r\n            ONEJS.memoizedComponents[name] = React.memo(ComponentFunction);\r\n        }\r\n        return React.createElement(ONEJS.memoizedComponents[name], attributes, null);\r\n    }\r\n    return React.createElement(ComponentFunction, attributes, null);\r\n};\r\n\r\n/** \r\n* @description For a given component function or tag, creates a React element that has been previously wrapped in a HOC to provide additional functionality: theming,\r\n* style compilation and lifecycle functions. Base components are the building blocks of the app and represent the os native components.\r\n* @param {String} name - Unique name for the Component.\r\n* @param {Boolean} hasChildren - Specifies whether the Component can have user added structure.\r\n* @param {Function} ComponentFunction - The component function to be created into a React element.* @example\r\n* ```javascript \r\n*   WrappedComponent(props=>structure=>Text(props)(structure));\r\n* ```\r\n* @returns {ReactElement} - The enhanced React element.\r\n*/\r\nexport const BaseComponent = (name, hasChildren, ComponentFunctionOrTag) => {\r\n    if(hasChildren) {\r\n        return CreateWrappedComponentWithStructure(name, EnhancedComponent(ComponentFunctionOrTag));\r\n    }\r\n    return CreateWrappedComponentWithoutStructure(name, EnhancedComponent(ComponentFunctionOrTag));\r\n};\r\n\r\n/** \r\n* @description For a given component function, creates a React element. This is the main method to create your own custom components. \r\n* @todo In the future this could be renamed to 'BaseComponent' and the Div wrapping could be deprecated. Base components would be the os-native components that would\r\n* be wrapped with this functionality. By using these components in a custom one, the functionality is extended.\r\n* @param {String} name - Unique name for the Component.\r\n* @param {Boolean} hasChildren - Specifies whether the Component can have user added structure.\r\n* @param {Function} ComponentFunction - The component function to be created into a React element.\r\n* @example\r\n* ```javascript \r\n*   WrappedComponent(props=>structure=>Text(props)(structure));\r\n* ```\r\n* @returns {ReactElement} - The enhanced React element.\r\n*/\r\nexport const Component = (name, hasChildren, ComponentFunction) => {\r\n    if(hasChildren) return CreateComponentWithStructure(name, ComponentFunction);\r\n    return CreateComponentWithoutStructure(name, ComponentFunction);\r\n};\r\n\r\n/** \r\n* @description A Higher Order Component (HOC) that provides additional functionality to the wrapped component for theming, inlineStyles, and lifecycle events.\r\n* @param {Function | String} ComponentFunction - The component function to be wrapped and infused with enhanced functionality.\r\n* @param {Object} structure - The internal structure that will be passed during component instantiation.\r\n* @param {Array<String> | String} flavor - The chosen flavor(s) during instantiation. For this function only the flavor ids are required to set the corresponding\r\n* CSS classes.\r\n* @param {Array<Object> | Object} style - The style to be compiled into a css class.\r\n* @param {Object} inlineStyle - The inline style chosen during instantiation.\r\n* @param {String} url - The url to be redirected to on component click.\r\n* @param {Function} onInit - Called once and only once before the component is mounted.\r\n* @param {Function} onCreate - Called onComponentDidMount event. The function takes as inputs newValue and component.\r\n* @example\r\n* ```javascript \r\n*   const addListeners = (newValue, component) => component.addEventListener('click', async (e) => alert(newValue));\r\n*   const MyComponent = BaseComponent('MyComponent', true, () => Div()())\r\n*   const template = () => [MyComponent({onCreate: addListeners})]\r\n* ```\r\n* @param {Function} onDestroy - Called onComponentWillUnmount event. The function takes as inputs newValue and component.\r\n* @param {Object} onPropertyChange - Called after onComponentDidMount event for every change in the value of the tracked properties.\r\n* Takes an object whose keys are the properties tracked and the values the callback function. The function takes as inputs newValue and component.\r\n* @example\r\n* ```javascript \r\n*   EnhancedComponent(props=>Input(props)({style: {background: 'blue', flavor: 'danger', onCreate: addListeners}});\r\n* ```\r\n* @returns {ReactElement} - If memoized, the memoized component. Otherwise, the original component.\r\n*/\r\nconst EnhancedComponent = (ComponentFunctionOrTag) => ({structure, flavor, style, inlineStyle, url,\r\n    onInit, onCreate, onDestroy, onPropertyChange, ...attributes} = {}) => {\r\n    //START CLASS SETUP: Web Specific. No class or className in React Native\r\n    const classArray = [];\r\n    if(OSSPECIFICS.os === 'web') {\r\n        //Add instantiation class(es) to the class array\r\n        if(attributes['class']) {\r\n            Array.isArray(attributes['class']) ?\r\n                classArray.push(...attributes['class']) : classArray.push(attributes['class']);\r\n            delete attributes['class'];\r\n        }\r\n\r\n        //Add flavor class to the class array\r\n        // if(flavor?.flavorId) {\r\n        //     if(Array.isArray(flavor.flavorId)) {classArray.push(...flavor.flavorId.map(flavorId => ONEJS.emotionCSSClasses['flavor'+flavorId]));}\r\n        //     else classArray.push(ONEJS.emotionCSSClasses['flavor'+flavor.flavorId]);\r\n        // }\r\n\r\n        //Add compiled style class to the class array\r\n        if(style) {//style can of Array type. The priority is from left (least priority) to write (most priority)\r\n            classArray.push(OSSPECIFICS.css(style));\r\n        }\r\n        if(classArray.length) attributes['className'] = classArray.join(' '); //For the moment React uses className instead of class\r\n        if(inlineStyle) attributes['style'] = inlineStyle;\r\n        //END CLASS SETUP        \r\n    }\r\n    else if(OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android') attributes['style'] = style;//Stylesheet.create does not seem to provide any performance boost, only validation in dev. https://stackoverflow.com/questions/38886020/what-is-the-point-of-stylesheet-create\r\n\r\n    //*REACT SPECIFIC* Lifecycle functions\r\n    if(onInit) {//Similar to the deprecated ComponentWillMount. The limitation is that domNode is not yet available and cannot be accessed for changes. If this is needed wait until onCreate\r\n        const initialized = React.useRef();\r\n        if(!initialized.current) {\r\n            onInit();\r\n            initialized.current = true;\r\n        }\r\n    }\r\n\r\n    if((url && OSSPECIFICS.os === 'web') || onCreate || onDestroy || onPropertyChange) {\r\n        const domNode = React.useRef();\r\n        attributes['ref'] = domNode;\r\n        if(url || onCreate || onDestroy) {//onCreate is equivalent to ComponentDidMount and onDestroy is equivalent to ComponentWillUnmount\r\n            React.useEffect(() => { //React Effect: https://es.reactjs.org/docs/hooks-overview.html\r\n                if(onCreate) onCreate(domNode.current);\r\n                if(onDestroy) return onDestroy(domNode.current);\r\n                if(url && OSSPECIFICS.os === 'web') setupUrl(url)(domNode.current);\r\n            }, []);//The array is the properites for which it should trigger the change. If empty, then none. If no parameter, then all.        \r\n        }\r\n        if(onPropertyChange) {//onPropertyChange: {prop1: function1, prop2: function2};//Functions take (newValue, domNode)\r\n            Object.entries(onPropertyChange).map(([property, callback]) => {\r\n                React.useEffect(() => {\r\n                    callback(attributes[property], domNode.current); //Equivalent to componentDidMount lifecycle call\r\n                }, [attributes[property]]);\r\n            });\r\n        }\r\n    }\r\n    if(url && (OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android')) {\r\n        attributes['onPress'] = () => updateUrl(url);\r\n    }\r\n\r\n    //If the structure is an array with missing 'key' property, then destructure the input; The structure array with n objects, becomes n arguments in the function\r\n    if(Array.isArray(structure) && structure?.length > 0 && structure?.[0]?.key == null) {\r\n        return React.createElement(ComponentFunctionOrTag, attributes, ...structure);\r\n    }\r\n    return React.createElement(ComponentFunctionOrTag, attributes, structure);\r\n};\r\n\r\n//=============================================================================\r\n// APP: A function that ties together the functionality of all the other modules.\r\n// By providing the configuration objects to the app() function, the state, theme\r\n// databases and texts are setup and the app is rendered.//\r\n//=============================================================================\r\n\r\n/**\r\n* @typedef  {Object}  Text - The configuration to setup and translate all the texts inside the app.\r\n* @property {String}  textId               - The id identifying the content of the text. E.g: 'homepageTitle'.\r\n* @property {String}  textId.language      - The language for the text string.\r\n*/\r\n/** \r\n* @description Main function to set up the app and render the template in the DOM. All the configuration required to run the app is provided to this function.\r\n* @param {String} [name] - Unique name for the app. Used to set up indexedDB storage.\r\n* @param {Config} [state] - The configuration object to setup the state. Declares all the state variables along with the source and storage option.\r\n* @param {Theme} [theme] - The collection of flavors that will be used to style the app. Defines the theme variables and the values that will be used for each flavor.\r\n* It can also be a string to choose from the out-of-the-box themes provided by oneJS.\r\n* @param {Text} [text] - The translatable text strings to be used in the app. \r\n* @param {Object} - The initialized firestore database object to enable performing the read/write operations.\r\n* @param {Function} template - A function that returns the template of the app.\r\n* @example\r\n* Simple Hello World example:\r\n* ```javascript \r\n* app({component: ()=>\"Hello World\"});\r\n* ```\r\n* @example\r\n* Complete Example:\r\n* ```javascript \r\n*   const name = 'myApp';\r\n*   const App = () => [Text()(readTextString('title')), Text()(readTextString('greeting') + ': ' + read('inputText')), Input({value: read('inputText', onInput: update('inputText'))})];\r\n*   const state = {inputText: {default: 'myApp'}}\r\n*   const theme = {default: {primaryColor: 'blue'}};\r\n*   const text = {title: 'My App',  greeting: {en: 'Hello', es: 'Hola'}};\r\n*   const firestore = initializeApp(config).getFirestore();\r\n*   app({name: name, component: App, state: state, theme: theme, themeSetup: themeSetup, text: text, firestore: firestore})\r\n* ```\r\n* @returns {ReactElement} - The complete app component.\r\n*/\r\nexport const app = ({name, component, state, theme, style, text, font, firestore}) => {\r\n    ONEJS.appName = name;\r\n    ONEJS.appText = (text && typeof text === 'object') ? {...text} : undefined;\r\n    ONEJS.style = (style && typeof style === 'object') ? {...style} : undefined;\r\n    //This line is making it fail for react native!!!\r\n    // ONEJS.firestore = (firestore && typeof firestore === 'object') ? {...firestore} : undefined;\r\n    ONEJS.firestore = (firestore && typeof firestore === 'object') ? firestore : undefined;\r\n    setupTheme(theme); //Setting up before AppComponent for the css class order.\r\n\r\n    //*REACT SPECIFIC*\r\n    const appFunction = ({state = {}, component} = {}) => {//Called on every rerender\r\n        //Setup url variables\r\n        if(OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android') {\r\n            [ONEJS.url, ONEJS.setUrl] = React.useState('/');\r\n        }\r\n        //Set default value for state variables\r\n        Object.entries(state).forEach(([stateId, value]) => {\r\n            const reactInitialState = (value && typeof value === 'object' &&\r\n                value.hasOwnProperty('default')) ? value['default'] : value;\r\n            [ONEJS.reactState[stateId],\r\n            ONEJS.reactSetState[stateId]] = React.useState(reactInitialState);\r\n            /* React.useState(initialState): Returns an array with a stateful value, and a function to update it. [state, setState()]\r\n                -initialState: During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).\r\n                -setState(): The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.\r\n            */\r\n        });\r\n\r\n        const initialized = React.useRef();\r\n\r\n        //Native Initializers: \r\n        if(OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android') {\r\n            //Setup url listener for native. Called before setup state in order to avoid the first call when ONEJS.url is first set.\r\n            React.useEffect(() => {\r\n                if(initialized) {\r\n                    ONEJS.urlStateVariables.forEach(stateVariable =>\r\n                        write(stateVariable.stateId, readUrlData(stateVariable.url),\r\n                            'url', 'update'));\r\n                }\r\n            }, [ONEJS.url]);\r\n            //Setup fonts for native. Called before setup state to take advantage of the async loading while the state is being set.\r\n            if(font && typeof font === 'object') {\r\n                const [fontsLoaded] = OSSPECIFICS?.useFonts(font);\r\n                ONEJS.fontsLoaded = fontsLoaded;\r\n            }\r\n        }\r\n\r\n        //Sets up the state for the app for the first time\r\n        if(!initialized.current) {\r\n            setupState(state);\r\n\r\n            //Web Initializers\r\n            if(OSSPECIFICS.os === 'web') {\r\n                //Setup url listeners for web\r\n                window.addEventListener('urlChange', (e) => {\r\n                    ONEJS.urlStateVariables.forEach(stateVariable => write(stateVariable.stateId,\r\n                        readUrlData(stateVariable.url), 'url', 'update'));\r\n                }, false);\r\n                //Setup fonts for web\r\n                if(font) {\r\n                    let fontStyle = document.createElement('style');\r\n                    Object.entries(font).forEach(([key, value]) => {\r\n                        fontStyle.appendChild(document.createTextNode(\"@font-face {font-family: \" +\r\n                            key + \"; src: url('\" + value + \"');font-display: swap;}\"));\r\n                    });\r\n                    document.head.appendChild(fontStyle);\r\n                }\r\n            }\r\n            initialized.current = true;\r\n        }\r\n\r\n        const structure = component(); //Template needs to be a function, otherwise the code is executed and the elements are not wrapped by reactCreateElement function\r\n        if((OSSPECIFICS.os === 'ios' || OSSPECIFICS.os === 'android') && font &&\r\n            typeof font === 'object' && !ONEJS.fontsLoaded) return null; //Wait until fonts are loaded\r\n        if(Array.isArray(structure) && structure?.length > 0 && structure?.[0]?.key == null) {\r\n            return React.createElement(React.Fragment, null, ...structure);//If the structure is an array with missing 'key' property, then destructure the input\r\n        };\r\n        return structure;\r\n    };\r\n\r\n    if(OSSPECIFICS.os === 'web') {\r\n        const bodyStyle = {\r\n            margin: 0,\r\n            minHeight: '100vh',\r\n            display: 'flex',               //Flexbox is the positioning being used\r\n            flexWrap: 'nowrap',            //Items do not fall into a different column once exhausted the space on the parent\r\n            flexGrow: '0',                 //It indicates how much they expand horizontally. A value of 0 indicates they do not expand\r\n            flexShrink: '0',               //A value of 0 indicates items do not go smaller than their original width\r\n            flexDirection: 'column',       //Row or column\r\n            justifyContent: 'flex-start',  //Horizontal alignment of the items\r\n            alignItems: 'stretch',         //Vertical alignment of the items\r\n            alignContent: 'flex-start',    //Horizontal alignment of the item columns\r\n        };\r\n        document.body.classList.add(OSSPECIFICS.css(bodyStyle));\r\n    }\r\n\r\n    //Render the app in the appropiate container\r\n    const AppComponent = React.createElement(appFunction, {state: state, component: component}, null);\r\n    if(os === 'web') {\r\n        const container = document.getElementById('app'); //document.body; //Using body is discouraged by React\r\n        if(!container) {\r\n            console.error('[oneJS] App: No <div> element with \"app\" id found.');\r\n            return null;\r\n        }\r\n        /* Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions: https://reactnative.dev/docs/flexbox\r\n        The defaults are different, with flexDirection defaulting to column instead of row, alignContent defaulting to flex-start instead of stretch, \r\n        flexShrink defaulting to 0 instead of 1, the flex parameter only supporting a single number.\r\n        */\r\n        container.style.display = 'flex';\r\n        container.style.flexDirection = 'column';\r\n        container.style.alignContent = 'flex-start';\r\n        container.style.flexGrow = '1';\r\n        container.style.flexShrink = '0';\r\n\r\n        const reactRoot = OSSPECIFICS.ReactDOM.createRoot(container);\r\n        reactRoot.render(AppComponent);\r\n    }\r\n    else {\r\n        OSSPECIFICS.registerRootComponent(() => AppComponent);\r\n    }\r\n};\r\n\r\n//=============================================================================\r\n// WEB THEME: This module aims to provide a unified and predictable way to define\r\n// and inherit styles for components and setup a consistent look and feel for the\r\n// app.\r\n// The principle behind is that everything that can change or be open for customization \r\n// by the user, should be a theme variable (in web they are converted into CSS variables). \r\n// Theme variables are given representative names and clustered under 'flavors' which \r\n// are essentially a specific set of values for those variables. By providing a\r\n// flavor to components, the look and feel can be customized for the theme variables\r\n// the component is implementing.\r\n//\r\n// STEPS to setup app theme on Web:\r\n// 1. Define a theme object containing the different flavors. Always include a\r\n//    'default' flavor. Example:\r\n//    const myTheme: {default: {primaryColor: 'blue'}, error: {primaryColor: 'red'}};\r\n// 2. Define a setup object assigning the theme variables to the target dom elements.\r\n//    const myThemeSetup = {p: {color: readFlavor('default').primaryColor}};\r\n// 3. Initialize the app with these two objects and use the theme variables inside\r\n//    your custom components to inherit the look and feel.   \r\n//    app({component: App, theme:myTheme, themeSetup: myThemeSetup});\r\n//    Text({flavor: 'error'})('My Text'); //Use flavor\r\n//\r\n// Native Principles:\r\n//  React components are designed with strong isolation in mind: This is possible to \r\n//  drop a component anywhere in the application, trusting that as long as the props \r\n//  are the same, it will look and behave the same way. Text properties that could inherit\r\n//  from outside of the props would break this isolation. https://reactnative.dev/docs/0.65/text\r\n// \r\n//  Differences from Web\r\n// 1. It is a CSS-like object structure but not CSS, and not compiled to CSS.\r\n// 2. Style structure is flat and properties are limited. Therefore no styling \r\n//    attributes such as ':hover'. https://reactnative.dev/docs/text-style-props\r\n// 3. Each style must be applied to each component, they are not inherited from their \r\n//    parent. There is only inheritance from parents of the same element (E.g.: Text to \r\n//    Text) https://reactnative.dev/docs/text#limited-style-inheritance\r\n// 4. There are no global attributes (body level) and no tag styling \r\n//    Example: style: {Text: {color: 'blue'}} //This is not possible.\r\n//\r\n// STEPS to setup app theme on Native:\r\n// 1. Define a theme object containing the different flavors. Always include a\r\n//    'default' flavor. Example:\r\n//    const myTheme: {default: {textColor: 'blue'}, error: {textColor: 'red'}};\r\n// 2. Define a components to make use of the theme variables so the user can customize\r\n//    them on instantiation. setup object assigning the theme variables to the target dom elements.\r\n//    export const Text = ({flavor=readFlavor('default'), ...attributes}={}) => structure => { \r\n//          const flavorStyle = {flavor?.textColor ?? 'black', fontSize: flavor?.textSize ?? 16};\r\n//          attributes['style'] = mergeStyles(flavorStyle, attributes['style']);\r\n//          return RNText(attributes)(structure);      \r\n//    }\r\n// 3. Initialize the app providing the theme object and use the theme variables inside\r\n//    your custom component instantiation to customize the look and feel attributes\r\n//    exposed in the declaration.   \r\n//    app({component: App, theme:myTheme});\r\n//    Text({flavor: 'error'})('My Text'); //Use flavor\r\n//\r\n// Other approaches to define global and reusable theming:\r\n// 1. Create a theme object with all the variables and the values to be used (chosen one)\r\n//    https://www.reactnative.guide/8-styling/8.1-theme-variables.html\r\n// 2. Wrap existing components in a new one that provides them the desired theme  \r\n//    https://stackoverflow.com/questions/35255645/how-to-set-default-font-family-in-react-native\r\n// 3. Use context API to scope and update theme globally.\r\n//    https://medium.com/@matanbobi/react-defaultprops-is-dying-whos-the-contender-443c19d9e7f1\r\n//\r\n//=============================================================================\r\n\r\n/** \r\n* @description There are a few theme variables that in order to be applied to the style properties need to be transformed. This is due to the format allowed in \r\n* oneJS differing from CSS or native. This function compiles the theme variables to the underlying standard style (CSS or native). \r\n* @param {String} themeVariableId - The theme variable id.\r\n* @param {*} themeVariableValue - The variable value.\r\n* @example\r\n* ```javascript \r\n*   const myFlavor: {radius: 3, primaryGradient: {colors: ['red', 'blue']}};\r\n*   toStandardStyle('radius', myFlavor.radius);                   //Web output: '3px'\r\n*   toStandardStyle('primaryGradient', myFlavor.primaryGradient); //Web output: 'linear-gradient(-90, red, blue)'\r\n* ```\r\n* @returns {Object} - The css variables with their corresponding values.\r\n*/\r\nconst toStandardStyle = (themeVariableId, themeVariableValue) => {\r\n    //Create shadow style object based on elevation property\r\n    if(themeVariableId === 'shadow' && typeof themeVariableValue === 'object') {\r\n        return generateShadow(themeVariableValue);\r\n    }\r\n    //Create gradient for texts\r\n    if(themeVariableId === 'textGradient' && typeof themeVariableValue === 'object') {\r\n        return generateGradient(themeVariableValue);\r\n    }\r\n    //Create gradient for backgrounds\r\n    if(themeVariableId === 'backgroundGradient' && typeof themeVariableValue === 'object') {\r\n        return generateGradient(themeVariableValue);\r\n    }\r\n    //Create gradient for backgrounds and icons\r\n    if(themeVariableId === 'primaryGradient' && typeof themeVariableValue === 'object') {\r\n        const svgId = JSON.stringify(themeVariableValue).replace(/[^a-zA-Z0-9]/g, '');\r\n        let standardGradient = generateGradient(themeVariableValue);\r\n        standardGradient = typeof standardGradient === 'string' ?\r\n            standardGradient : {id: svgId, ...standardGradient};\r\n        const svgGradient = generateGradient({...themeVariableValue, svgId: svgId});\r\n        ONEJS.iconGradients.set(standardGradient?.id ?? standardGradient,\r\n            {id: svgId, value: svgGradient});\r\n        return standardGradient;\r\n    }\r\n    else return themeVariableValue;\r\n};\r\n\r\n/**\r\n* @typedef  {Object}  Flavor          - The configuration assigning a value to each of the theme variables.\r\n* @property {String}  themeVariableId - Assigns to the theme variable 'themeVariableId' the corresponding value.\r\n* @example\r\n*   const myFlavor: {primaryColor: 'blue', radius: '3px', shadow: null};\r\n*/\r\n/** \r\n* @description Returns the style configuration associated to the flavor(s) selected.\r\n* @param {String | Array<String>} flavorName - The name of the flavor(s) to be used from the theme.\r\n* @example\r\n* ```javascript \r\n*   const theme: {myFlavor: {primaryColor: 'blue', radius: '3px', shadow: null}};\r\n*   readFlavor('myFlavor'); //Return {primaryColor: 'blue', radius: '3px', shadow: null}\r\n* ```\r\n* @returns {Flavor} - The flavor selected.\r\n*/\r\nexport const readFlavor = (...flavorName) => {\r\n    if(!flavorName || flavorName?.length === 0) {\r\n        console.error('readFlavor: Invalid flavor name: ' +\r\n            flavor); return {};\r\n    }\r\n    if(Array.isArray(flavorName[0])) flavorName = flavorName[0]; //This way we allow three input options: String, Array and destructured\r\n    if(flavorName.length > 1) {//Flavor is an array of strings: Increasing priority from left to right\r\n        let flavorObject = {};//Used inside EnhancedComponent to read the flavor CSS and add a class with the variable values.\r\n        flavorName.forEach((flavor) => {\r\n            flavorObject = flavor ?\r\n                {...flavorObject, ...ONEJS.theme[flavor]} : flavorObject;\r\n        });\r\n        return {...ONEJS.theme['default'], ...flavorObject};\r\n    }\r\n    return ONEJS.theme[flavorName[0]] ?\r\n        {...ONEJS.theme['default'], ...ONEJS.theme[flavorName[0]]} : ONEJS.theme['default'];\r\n};\r\n/** \r\n* @description Updates the value of entire flavor or the theme variable within the flavor .\r\n* @param {String} flavorName - The name of the flavor to be updated.\r\n* @param {String} [themeVariableId] - The theme variable to be updated within the flavor.\r\n* @param {String} value - The value to be assigned to the flavor or theme variable.\r\n* @example\r\n* ```javascript \r\n*   const theme: {myFlavor: {primaryColor: 'blue', radius: '3px', shadow: null}};\r\n*   updateFlavor('myFlavor', 'primaryColor')('red'); \r\n*   updateFlavor('myFlavor')({primaryColor: 'red', radius: '0px', shadow: null}); \r\n* ```\r\n* @returns {void}\r\n*/\r\nexport const updateFlavor = (flavorName, themeVariableId) => value => {\r\n    if(!ONEJS?.theme[flavorName]) {\r\n        console.error('[oneJS] updateFlavor: Invalid flavor name: ' + flavorName);\r\n        return;\r\n    }\r\n    if(typeof themeVariableId === 'string') ONEJS.theme[flavorName][themeVariableId] = value;\r\n    else ONEJS.theme[flavorName] = value;\r\n};\r\n\r\n/** \r\n* @description Returns the style configuration associated to the style(s) selected.\r\n* @param {String | Array<String>} styleName - The name of the style(s) to be used.\r\n* @example\r\n* ```javascript \r\n*   const style: {navbar: {background: 'white', borderRadius: '3px', color: 'black'}};\r\n*   readStyle('navbar'); //Return {primaryColor: 'blue', radius: '3px', shadow: null}\r\n* ```\r\n* @returns {Object} - The resulting style of merging the different styles.\r\n*/\r\nexport const readStyle = (...styleName) => {\r\n    if(!styleName || styleName?.length === 0) {\r\n        console.error('[oneJS] readFlavor: Invalid flavor name: ' + flavor);\r\n        return {};\r\n    }\r\n    if(Array.isArray(styleName[0])) styleName = styleName[0]; //This way we allow three input options: String, Array and destructured (combining destructured and array is not possible)\r\n    if(styleName.length > 1) {//Flavor is an array of strings: Increasing priority from left to right\r\n        let styleArray = [];//Used inside EnhancedComponent to read the flavor CSS and add a class with the variable values.\r\n        styleName.forEach((name, index) => styleArray[index] = ONEJS.style[name]);\r\n        return mergeStyles(styleArray);\r\n    }\r\n    return ONEJS.style[styleName[0]];\r\n};\r\n/** \r\n* @description Updates the value of entire style or an attribute within the style .\r\n* @param {String} styleName - The name of the style to be updated.\r\n* @param {String} [attributeId] - The attribute to be updated within the style.\r\n* @param {String} value - The value to be assigned to the style or the style attribute.\r\n* @example\r\n* ```javascript \r\n*   const style: {navbar: {background: 'white', borderRadius: '3px', color: 'black'}};\r\n*   updateStyle('navbar', 'background')('red'); \r\n*   updateStyle('navbar')({background: 'red', borderRadius: '0px', color: 'black'}); \r\n* ```\r\n* @returns {void}\r\n*/\r\nexport const updateStyle = (styleName, attributeId) => value => {\r\n    if(!ONEJS.style?.styleName) {\r\n        console.error('[oneJS] updateStyle: Invalid style name: ' + styleName);\r\n        return;\r\n    }\r\n    if(typeof attributeId === 'string') ONEJS.style.styleName.attributeId = value;\r\n    ONEJS.style.styleName = value;\r\n};\r\n\r\n/** \r\n* @description Using the theme and themeSetup configuration objects creates the css classes and applies then to the DOM objects. \r\n* The default flavor values are set at body level.\r\n* @param {Theme | String} theme - If it is a string, the oneJS theme to be used. If a theme object, the collection of flavors with the theme variables.\r\n* @param {Object} themeSetup - The CSS in JS object applying the theme variables to the DOM objects.\r\n* @param {Object} themeCollection - The collection of preset themes provided.\r\n* @example\r\n* ```javascript \r\n*   const theme = {default: {primaryColor: 'blue'}};\r\n*   const themeSetup = {p: {color: themeVariable('primaryColor')}};\r\n*   setupTheme({theme: theme, themeSetup: themeSetup});\r\n* ```\r\n* @returns {void}\r\n*/\r\nconst setupTheme = themeConfig => {\r\n    /*There are three options: \r\n        theme = null/undefined -> No theme is used\r\n        theme = <string value> -> User wants to select one of the collection of themes from the theme collection\r\n        theme = <object value> -> User wants to setup their own themes based on the relevant parameters\r\n    */\r\n    if(!themeConfig) return; //No theme is used\r\n    const theme = themeGenerator(themeConfig);\r\n\r\n    //Setup the ONEJS.theme object\r\n    Object.entries(theme).forEach(([flavorId, flavorValue]) => { //Transform each of the themes in css variables stored in a class. This can now be applied to any component\r\n        ONEJS.theme[flavorId] = {flavorId: flavorId};\r\n        Object.entries(flavorValue).forEach(([key, value]) => {\r\n            ONEJS.theme[flavorId][key] = value === null ? null : toStandardStyle(key, value);\r\n        });\r\n    });\r\n};\r\n\r\n/** \r\n* @description Reads the SVG icon gradient that has been stored in the ONEJS.iconGradients variable. For web, icon gradients are stored by 'setupTheme' function\r\n* already transformed to SVG gradient. For native, icon gradients are generated and stored on the first call to this function, transforming the input gradient\r\n* object into the SVG gradient and storing it in the ONEJS.iconGradients variable.\r\n* @param {String} gradientId - For web, this is the string representing the CSS gradient variable. For native, it is the gradient object.\r\n* @example\r\n* ```javascript \r\n*   //Web\r\n*   const gradientId = 'var(--one-primaryGradient, linear-gradient(0deg, red, blue))';\r\n* \r\n*   //Native\r\n*   const gradientId = {angle: 0, colors: ['red', 'blue']};\r\n* \r\n*   //Output for Web and Native: readIconGradient(gradientId)\r\n*   <linearGradient id=\"grad1\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\">\r\n*      <stop offset=\"0%\" stop-color=\"red\" />\r\n*      <stop offset=\"100%\" stop-color=\"blue\"/>\r\n*   </linearGradient>\r\n* ```\r\n* @returns {String} - The stored SVG gradient.\r\n*/\r\nexport const readIconGradient = gradientId => {\r\n    return ONEJS?.iconGradients?.get(typeof gradientId === 'string' ? gradientId : gradientId?.id);\r\n};\r\n\r\n/** \r\n* @description Given a set of parameters generates a gradient for both web, native and SVG icons.\r\n* Web Gradient: Follows the linear-gradient CSS specifications. [W3 Schools]{@link https://www.w3schools.com/css/css3_gradients.asp}\r\n*   Syntax: linear-gradient(angle, color-stop1, color-stop2, ...);\r\n* Native Gradient: Follows the expo LinearGradient component specification. [Expo]{@link https://docs.expo.dev/versions/latest/sdk/linear-gradient/}\r\n*   Component Properties: colors, start, end, locations\r\n* SVG Gradient: Follows the SVG Linear Gradient specificication. [W3 Schools]{@link https://www.w3schools.com/graphics/svg_grad_linear.asp}\r\n*   Syntax: The syntax is similar to expo Linear Gradient, where the direction is specified by coordinates and the location by the offset.\r\n* ```svg\r\n*   <linearGradient id=\"grad1\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\">\r\n*      <stop offset=\"0%\" stop-color=\"red\" />\r\n*      <stop offset=\"100%\" stop-color=\"blue\"/>\r\n*   </linearGradient>\r\n* ```\r\n* @param {Array<String>} colors - The array of colors to generate the gradient.\r\n* @param {Number} [angle] - Angle in degrees. Follows the unit circle angular convention ([Wikipedia]{@link https://en.wikipedia.org/wiki/Unit_circle}). The direction\r\n* of the gradient is derived * solely by the angle, represented by the vector whose origin is the center of the circle and the heap  on the perimeter. \r\n* An angle of 0deg would correspond * to a left to right gradient while an angle of 90deg would correspond to bottom to top gradient.\r\n* @param {Array<Number>} [start] - In a squared space where the coordinates' origin is located in the top left corner and x and y are the horizontal and vertical axis \r\n* respectively, start is the pair of x and y coordinates that locate the origin of the gradient direction vector. [0, 0] would correspond to the origin (top-left corner)\r\n* and [1, 1] would correspond to the bottom-bottom right corner.\r\n* @param {Number} [end] - Following the same spacial convention, it is the pair of x and y coordinates that locate the heap of the gradient direction vector.\r\n* @param {Array<Number>} [locations] - From 0 to 1, it represents how the colors are split across the direction vertor formed by the angle or the start and \r\n* end coordinates. 0 would correspond to the origin and 1 to the heap. The number of locations has to match the number of colors. If it is not provided, the colors\r\n* are evenly split.\r\n* @param {Boolean} [svgId] - If provided, the function will create an SVG gradient with this id. Used for both web and native.\r\n* @example\r\n* ```javascript \r\n*   const theme = {default: {primaryColor: 'blue'}};\r\n*   const themeSetup = {p: {color: themeVariable('primaryColor')}};\r\n*   setupTheme({theme: theme, themeSetup: themeSetup});\r\n* ```\r\n* @returns {String | Object} - Generated gradient in string or object format, depending on the platform.\r\n*/\r\nexport const generateGradient = ({colors, angle = 0, start, end, locations, svgId}) => {\r\n    if(!colors || !Array.isArray(colors) || colors.length < 2) {\r\n        console.error('generateGradient: \"colors\" array must contain at least two items');\r\n        return;\r\n    }\r\n    if(!locations) {\r\n        locations = colors.map((color, index) => Number((index / (colors.length - 1)).toFixed(2)));\r\n    }\r\n    else if(locations && locations.length !== colors.length) {\r\n        console.error('generateGradient: \"colors\" and \"locations\" arrays must be the same length.');\r\n        return;\r\n    }\r\n\r\n    //CSS linear-gradient\r\n    if(OSSPECIFICS.os === 'web' && !svgId) {\r\n        return 'linear-gradient(' + (90 - angle) + 'deg, ' + colors.join(', ') + ')';\r\n    }//Following the unit circle where the first color is in the origin and the rest in the direction of the angle\r\n\r\n    //For native and SVG, transforms the angle into the start and end pair of [x,y] coordinates.\r\n    if(start == null || end == null) {\r\n        const a = angle * Math.PI / 180;//Input angle is in degrees need to convert to radians\r\n        const k = Math.ceil(Math.sin(45 * Math.PI / 180) * 10000) / 10000;//Sin(45) = cos(45). Rounding up to avoid obtaining x and y greater than 1.\r\n        start = {x: Math.cos(a) > 0 ? 0 : 1, y: Math.sin(a) > 0 ? 1 : 0};\r\n        end = {\r\n            x: Math.abs(Math.cos(a)) < k ?\r\n                +Math.abs(start.x - Math.abs(Math.cos(a)) / k).toFixed(2) : Math.abs(start.x - 1),\r\n            y: Math.abs(Math.sin(a)) < k ?\r\n                +Math.abs(start.y - Math.abs(Math.sin(a)) / k).toFixed(2) : Math.abs(start.y - 1)\r\n        };\r\n        //Reposition start and end, so that the vector that goes from start to end crosses the center of the square\r\n        if(start.x + end.x !== 1) {\r\n            const dif = start.x - end.x; start.x = 0.5 + dif / 2; end.x = 0.5 - dif / 2;\r\n        }; //Reposition to the center\r\n        if(start.y + end.y !== 1) {\r\n            const dif = start.y - end.y; start.y = 0.5 + dif / 2; end.y = 0.5 - dif / 2;\r\n        }; //Reposition to the center\r\n    }\r\n\r\n    //SVG Gradient\r\n    if(svgId) return '<defs><linearGradient id=\"' + svgId + '\" x1=\"' + start.x + '\" y1=\"' +\r\n        start.y + '\" x2=\"' + end.x + '\" y2=\"' + end.y + '\">' +\r\n        locations.map((location, index) => '<stop offset=\"' + location + '\" stop-color=\"' +\r\n            colors[index] + '\"></stop>').join('') + '</linearGradient></defs>';\r\n    //Expo LinearGradient\r\n    return {colors: colors, locations: locations, start: start, end: end};\r\n};\r\n\r\n/** \r\n* @description Generates a shadow that looks consistent across web and native given the component's elevation.\r\n* @param {Number} elevation - A number that represents the component's elevation with respect to its parent. \r\n* The minimum elevation is 0 (no shadow) and the maximum is 24 (greatest shadow).\r\n* @example\r\n* ```javascript \r\n*   const theme = {dark: {primaryColor: '#ffffff', backgroundColor: '#333333', shadow: generateShadow(4)}};\r\n* ```\r\n* @returns {String | Object} - For web, returns the box-shadow CSS string. For Android, the elevation object. For iOS, the object with the shadow properties.\r\n*/\r\nexport const generateShadow = ({elevation}) => {//min elevation 0, max elevation 24. Remove os as input and use internally\r\n    if(!elevation) return {}; //If elevation is 0 or null/undefined\r\n    if(typeof elevation !== 'number') {\r\n        console.error('generateShadow: elevation must be a number.');\r\n        return {};\r\n    }\r\n\r\n    if(OSSPECIFICS.os === 'android') return {elevation: elevation};\r\n    else if(OSSPECIFICS.os === 'ios') return {\r\n        shadowColor: 'black',\r\n        shadowOffset: {\r\n            width: 0,\r\n            height: elevation / 2,\r\n        },\r\n        shadowOpacity: 0.01739 * elevation + 0.1626,//[1-24] => [0.18, 0.58]\r\n        shadowRadius: 0.6956 * elevation + 0.3043,//[1-24] => [1, 16]\r\n    };\r\n    //CSS box-shadow: horizontal offset, vertical offset, blur, spread, color\r\n    else if(OSSPECIFICS.os === 'web')\r\n        return {\r\n            boxShadow: '0 ' + elevation / 2 + 'px ' + elevation + 'px ' + elevation / 2 +\r\n                'px rgba(0, 0, 0, 0.1)'\r\n        };\r\n    return {};\r\n};\r\n\r\n/** \r\n* @description The styles to be merged are input separated by a comma and they are combined applying left to right increasing priority. This is specially\r\n* useful when creating a custom Component and providing a set of internal styles but enabling the user as well to use their own style at instantiation.\r\n* @param {Object | Array<Object>} style - The list of styles to be merged. \r\n* @example\r\n* ```javascript \r\n*   //Object merge\r\n*   const style1 = {primaryColor: 'blue', backgroundColor: 'white', radius: '1px'};\r\n*   const style2 = {primaryColor: 'red', border: '1px solid green'};\r\n*   mergeStyles(style1, style2); //Output: {primaryColor: 'red', backgroundColor: 'white', radius: '1px', border: '1px solid green'}\r\n* \r\n*   //Array merge\r\n*   const styleArray = [{primaryColor: 'blue', backgroundColor: 'white', radius: '1px'}, {primaryColor: 'red', border: '1px solid green'}];\r\n*   mergeStyles(styleArray); //Output: {primaryColor: 'red', backgroundColor: 'white', radius: '1px', border: '1px solid green'}\r\n* ```\r\n* @returns {Object} - The result of merging the input styles.\r\n*/\r\nexport const mergeStyles = (...styles) => {\r\n    let finalStyle = {};\r\n    styles?.forEach((style) => {\r\n        if(Array.isArray(style)) style.forEach(styleObj => {\r\n            if(styleObj && typeof styleObj === 'object') finalStyle = {...finalStyle, ...styleObj};\r\n        });\r\n        else if(style && typeof style === 'object') finalStyle = {...finalStyle, ...style};\r\n    });\r\n    return finalStyle;\r\n};\r\n\r\n/**\r\n* @typedef  {Object}  Content     - The configuration specifying the positioning of the component's content. It is used in the View component only.\r\n* @property {String}  [direction] - The direction in which children are positioned with respect to the component.\r\n*   row:            Default value. Places children components in a row from left to right.\r\n*   row-reverse:    Places children components in a row from right to left.\r\n*   column:         Places children components in a column from top to bottom.\r\n*   column-reverse: Places children components in a column from bottom to top.\r\n* @property {String}  [h]         - The horizontal distribution and positioning of the children. When the content is positioned in columns and it overflows spanning\r\n*                                   several columns, it is also used to set how these columns are distributed (as if they were single horizontal blocks).\r\n*   left:           Default value. Places children components aligned to the left.\r\n*   right:          Places children components aligned to the right.\r\n*   center:         Places children components aligned to the center.\r\n*   distribute:     Distributes children equidistantly with respect to each other and the edges of the parent.\r\n*   space:          Distributes children so that they are as spaced from each other as possible and pushes them towards the parent's edges.\r\n*   stretch:        Stretches children components across the transversal (horizontal direction) to fill the component. Similar to expand, but expand is set on the\r\n*                   each of the children and works in the content direction. \r\n* @property {String}  [v]         - The vertical distribution and positioning of the children. When the content is positioned in rows and it overflows spanning\r\n*                                   several rows, it is also used to set how these rows are distributed (as if they were single vertical blocks).\r\n*   top:            Default value. Places children components aligned to the top.\r\n*   bottom:         Places children components aligned to the bottom.\r\n*   center:         Places children components aligned to the center.\r\n*   distribute:     Distributes children equidistantly with respect to each other and the edges of the parent.\r\n*   space:          Distributes children so that they are as spaced from each other as possible and pushes them towards the parent's edges.\r\n*   stretch:        Stretches children components across the transversal (vertical direction) to fill the component. Similar to expand, but expand is set on the\r\n*                   each of the children and works in the content direction. \r\n* @property {Boolean} [wrap]      - Specifies whether children components are allowed to overflow into extra rows/columns once the space in the first row/column is\r\n*                                   exhausted. True by default.\r\n* @example\r\n* ```javascript \r\n*   const content: {direction: 'column', h: 'center', v: 'top', wrap: false};\r\n*   View({style: view1Style, content: content, key: 'view1'})(Text()('Hello World!'));\r\n* ```\r\n*/\r\n/** \r\n* @description Generates the Flexbox CSS properties to be applied to the View component, given the Content custom object configuration. \r\n* Reference: [W3 Schools]{@link https://www.w3schools.com/css/css3_flexbox.asp}\r\n* @param {Content} content - The The configuration specifying the positioning of the component's children.\r\n* @example\r\n* ```javascript \r\n*   const content: {direction: 'column', h: 'center', v: 'top', wrap: false};\r\n*   View({style: view1Style, content: content, key: 'view1'})(Text()('Hello World!'));\r\n* ```\r\n* @returns {Object} - The CSS properties for the Flexbox.\r\n* @todo Create a 'positons' object, similar to 'animations', with a set of predefined positions to choose from (rather than parsing the text).\r\n*/\r\nexport const positionContent = (content) => {\r\n    let direction = 'row';          //Direction of the content. Row: Content flows along the x-axis (horizontal). Column: Content flows along the y-axis (vertical).\r\n    let wrap = 'nowrap';            //Wraps the content adding new lines if it exceeds the space in the longitudinal direction.\r\n    let longitudinal = 'flex-start';//Positioning in the content direction\r\n    let transversal = 'flex-start'; //Positioning in the cross direction, perpendicular to the content\r\n    let overflow = 'flex-start';    //Positioning of the different rows and columns of content that overflow how are they aligned to each other.\r\n    let gap = {};            //Gap between content items\r\n\r\n    if(content) {\r\n        wrap = (content.wrap ?? false) ? 'wrap' : 'nowrap';\r\n        direction = content.direction ?? 'row';\r\n        const reverse = direction.search('reverse') > -1 ? true : false; //True if direction is 'row-reverse' or 'column-reverse'\r\n        gap = content.gap ? {gap: content.gap} : {}; //Gap property is not yet implemented in React Native: https://github.com/facebook/yoga/issues/812\r\n        longitudinal = direction === 'row' || direction === 'row-reverse' ?\r\n            content.h ?? 'left' : content.v ?? 'top';  //In the content direction\r\n        transversal = direction === 'row' || direction === 'row-reverse' ? \r\n            content.v ?? 'top' : content.h ?? 'left'; //Transversal to the content direction\r\n\r\n        //Options for longitudinal alignment in CSS (justify-content): flex-start | flex-end | center | space-between | space-around | space-evenly | start | end | left | right\r\n        //Options for longitudinal alignment in oneJS: left, center, right (for rows). top, center, bottom (for cols). space, distribute (for both)\r\n        if(longitudinal === 'center') longitudinal = longitudinal;\r\n        else if(longitudinal === 'bottom' || longitudinal === 'right') {\r\n            longitudinal = reverse ? 'flex-start' : 'flex-end';\r\n        }\r\n        else if(longitudinal === 'distribute') longitudinal = 'space-around';\r\n        else if(longitudinal === 'space') longitudinal = 'space-between';\r\n        else if(reverse) longitudinal = 'flex-end';\r\n        else longitudinal = 'flex-start';\r\n\r\n        //Options for transversal alignemnt in CSS (align-items): stretch | flex-start | flex-end | center | baseline | first baseline | last baseline | start | end | self-start | self-end\r\n        //Options for transversal alignment in oneJS: left, center, right (for cols). top, center, bottom (for rows). stretch?\r\n        //Options for transversal alignment of the contet overflow in CSS (align-content): flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline\r\n        //These options are also used to align the content overflow:\r\n        if(transversal === 'center') {transversal = transversal; overflow = 'center';}\r\n        else if(transversal === 'bottom' || transversal === 'right') {\r\n            transversal = 'flex-end'; overflow = 'flex-end';\r\n        }\r\n        else if(transversal === 'distribute') {transversal = 'center'; overflow = 'space-around';}\r\n        else if(transversal === 'space') {transversal = 'center'; overflow = 'space-between';}\r\n        else if(transversal === 'stretch') {transversal = 'stretch'; overflow = 'stretch';} //Stretch: If the transversal dimension is not known, stretches the element. To be able to stretch the element 'align-content' also needs to be set to stretch.\r\n        else {transversal = 'flex-start'; overflow = 'flex-start';}\r\n    }\r\n    return {\r\n        flexDirection: direction, justifyContent: longitudinal, alignItems: transversal,\r\n        alignContent: overflow, flexWrap: wrap, ...gap\r\n    };\r\n};\r\n\r\n/** \r\n* @description Creates a CSS media query for the device specified. It works both on web and native.\r\n* @param {String} range - Indicates the type of range to generate the media query.\r\n*   - min: The minimum width to trigger the query will be the width the selected device.\r\n*   - max: The maximum width to trigger the query will be the width the selected device. Default.\r\n*   - match: The query will match the width range of the device or devices provided.\r\n* @param {String | Array<String>} device - Indicates the target device for the query.\r\n*   - phone: Any devices whose screen width ranges from 0 to 767.\r\n*   - tablet: Any device whose screen width ranges from 768 to 991.\r\n*   - laptop: Any device whose screen width ranges from 992 to 1199.\r\n*   - monitor: Any device whose screen width ranges from 1200 to 9999.\r\n* @param {Object} style - The style to be applied in the query.\r\n* @example\r\n* ```javascript \r\n*   //Min width\r\n*   const textStyle = {\r\n*       color: 'black',\r\n*       ...media({range: 'min', device: 'table'})({color: 'pink'});\r\n*       //Devices with minimum a tablet's width will display a pink color\r\n*   }\r\n* ```\r\n* @returns {String} - The generated CSS media query.\r\n*/\r\nexport const media = ({range = 'max', device} = {}) => style => {\r\n    if(!device) return {};\r\n    const deviceWidthRange = {\r\n        phone: [0, 767], tablet: [768, 991], laptop: [992, 1199], monitor: [1200, 9999]\r\n    };\r\n    if(!deviceWidthRange[device]) {\r\n        console.error('[oneJS] media: No such device: ' + device);\r\n        return {};\r\n    }\r\n    let mediaQuery = {};\r\n    if(range === 'min') {\r\n        mediaQuery[`@media (min-width: ${deviceWidthRange[device][0]}px)`] = style;\r\n        return mediaQuery;\r\n    }\r\n    if(range === 'max') {\r\n        mediaQuery[`@media (max-width: ${deviceWidthRange[device][1]}px)`] = style;\r\n        return mediaQuery;\r\n    }\r\n    if(range === 'match') {\r\n        if(!Array.isArray(device)) device = [device];\r\n        device.forEach(d => {\r\n            mediaQuery[`@media (min-width: ${deviceWidthRange[d][0]}px)`] = style;\r\n            mediaQuery[`@media (max-width: ${deviceWidthRange[d][0]}px)`] = style;\r\n        });\r\n        return mediaQuery;\r\n    }\r\n    return mediaQuery;\r\n};\r\n\r\n/**\r\n* @typedef  {Theme}   Theme                    - A collection of flavors, assigning a value to each of the theme variables.\r\n* @property {Object}  default                  - The default flavor to be applied if none are specified. It is required for every theme.\r\n* @property {String}  default.themeVariable    - For the default flavor, assigns to the theme variable 'themeVariableId' the corresponding value.\r\n* @property {Object}  [flavorId]               - The configuration assigning a value to each of the theme variables.\r\n* @property {String}  [flavorId.themeVariable] - Assigns to the theme variable 'themeVariableId' the corresponding value.\r\n* @example\r\n*   const myTheme: {default: {primaryColor: 'blue'}, success: {primaryColor: 'green'}, error: {primaryColor: 'red'}};\r\n*/\r\n/**\r\n* @description The object containing the preset bundle of themes. These define a set of theme variables and their values for each flavor.\r\n*   -Root Level (Theme): Defines themes (flavor collection). This is only used by one to provide multiple themes, users must skip this level.\r\n*   -Level 1 (Flavor): Defines flavors. \"default\" flavor always has to be provided. E.g: warning, success, default\r\n*   -Level 2 (Variable): Assigns to the theme variable a value. E.g: primaryColor: 'blue'.\r\n* \r\n* Note: The main advantage of using theme variables contained in flavors over CSS classes, is that is allows to theme the app using language agnostic \r\n* styling terms rather than CSS or React Native specific attributes. These values can also be reused inside components to define the style object. In the case of\r\n* Web, the implementation uses CSS variables which improve performance and allow the user to swiftly change theme variables.\r\n* \r\n* These are the theme variables suggested by oneJS to customize the look and feel of the app:\r\n*   - backgroundColor:      Color to be applied in the background of container components, such as a View or a Button.\r\n*   - primaryColor:         Primary color of the app, used to style Icons and Buttons. Tip: rather than creating a 'secondaryColor' theme variable create \r\n*                           another flavor named 'secondary' storing this value in 'primaryColor'. If secondary color is used heavily and in combination with the\r\n*                           primary color in components, then it may be needed to add 'secondaryColor' theme variable.\r\n*   - neutralColor:         Neutral color that can be used in combination with the primary color.\r\n*   - primaryGradient:      Defines a gradient that can be used to style buttons and icons.\r\n*   - textGradient:         Defines a gradient that can be used to style texts.\r\n*   - backgroundGradient:   Defines a gradient that can be used to style backgrounds of Views.\r\n* \r\n*   - textFont:             Font family for the text strings.\r\n*   - textColor:            Text color.\r\n*   - textSize:             Font size. Preferably defined in % values.\r\n* \r\n*   - radius:               Border radius for container components.\r\n*   - borderWidth:          Border width for container components.\r\n*   - borderStyle:          Border style for container components.\r\n*   - borderColor:          Border color for container components.\r\n*   - inputBorderWidth:     Border width for input components.\r\n*   - inputBorderStyle:     Border style for input components.\r\n*   - inputBorderColor:     Border color for input components.\r\n* \r\n*   - shadow:               Backdrop shadow. It is generated by specifying the elevation of the component (from 0, closest to 24, furthest).\r\n* @type {Object}\r\n*/\r\nconst themeGenerator = ({preset = 'oneJS', variables = {}, flavors = {}} = {}) => {\r\n    /* Best practice: Try to have as few theme variables as possible to and create as many flavors as needed giving values to these variables.\r\n        E.g. Rather than creating a color variable for every color in the app, create flavors giving different values to the 'primaryColor'.\r\n    */\r\n    const presetThemes = {\r\n        oneJS: {//Theme name\r\n            //Color\r\n            backgroundColor: '#ffffff',\r\n            primaryColor: '#094DFF',\r\n            neutralColor: '#b1b0c5',\r\n            acceptColor: '#60b33a',\r\n            rejectColor: '#ff5100',\r\n            warnColor: '#f7df00',\r\n            lightColor: '#e9e8ee',\r\n            darkColor: '#4c4b66',\r\n\r\n            //Text\r\n            textFont: OSSPECIFICS.os === 'web' ? 'Avenir Next, Arial, sans-serif' :\r\n                OSSPECIFICS.os === 'ios' ? 'Avenir Next' : 'Roboto',\r\n            textColor: '#666488',\r\n            textSize: 18,\r\n            textWeight: 'normal',\r\n\r\n            //Border\r\n            radius: 10,\r\n            borderWidth: 1,\r\n            borderStyle: 'solid',\r\n            borderColor: '#e9e8ee',\r\n\r\n            //Shadow\r\n            shadow: {elevation: 0},\r\n        }\r\n    };\r\n    const themeVariables = {...presetThemes[preset], ...variables};\r\n    const theme = {\r\n        default: {//Flavor Name\r\n            //Color\r\n            backgroundColor: themeVariables?.backgroundColor,\r\n            primaryColor: themeVariables?.primaryColor,\r\n            neutralColor: themeVariables?.neutralColor,\r\n            acceptColor: themeVariables?.acceptColor,\r\n            rejectColor: themeVariables?.rejectColor,\r\n            warnColor: themeVariables?.warnColor,\r\n            lightColor: themeVariables?.lightColor,\r\n            darkColor: themeVariables?.darkColor,\r\n\r\n            //Text\r\n            textFont: themeVariables?.textFont,\r\n            textColor: themeVariables?.textColor,\r\n            textSize: themeVariables?.textSize,\r\n            textWeight: themeVariables?.textWeight,\r\n\r\n            //Border\r\n            radius: themeVariables?.radius,\r\n            borderWidth: themeVariables?.borderWidth,\r\n            borderStyle: themeVariables?.borderStyle,\r\n            borderColor: themeVariables?.borderColor,\r\n\r\n            //Shadow\r\n            shadow: themeVariables?.shadow,\r\n        },\r\n        //Shadow\r\n        shadow: {\r\n            shadow: {elevation: 10},\r\n        },\r\n        noShadow: {\r\n            shadow: {elevation: 0},\r\n        },\r\n        //Border\r\n        border: {\r\n            borderWidth: 1,\r\n            borderStyle: 'solid',\r\n            borderColor: themeVariables?.borderColor,\r\n        },\r\n        noBorder: {\r\n            borderWidth: 0,\r\n            borderStyle: 'none',\r\n            borderColor: 'transparent',\r\n        },\r\n        flat: {\r\n            shadow: {elevation: 0},\r\n            borderWidth: 0,\r\n            borderColor: 'transparent',\r\n            radius: 0\r\n        },\r\n        //Text     \r\n        bold: {\r\n            textWeight: 'bold'\r\n        },\r\n        normal: {\r\n            textWeight: 'normal'\r\n        },\r\n        title: {\r\n            textWeight: 'bold',\r\n            textColor: themeVariables?.darkColor,\r\n            textSize: typeof themeVariables?.textSize === 'number' ?\r\n                themeVariables?.textSize * 3 : '300%'\r\n        },\r\n        header: {\r\n            textWeight: 'bold',\r\n            textColor: themeVariables?.darkColor,\r\n            textSize: typeof themeVariables?.textSize === 'number' ?\r\n                themeVariables?.textSize * 2 : '200%'\r\n        },\r\n        section: {\r\n            textWeight: 'bold',\r\n            textColor: themeVariables?.darkColor,\r\n            textSize: typeof themeVariables?.textSize === 'number' ?\r\n                Math.round(themeVariables?.textSize * 1.5) : '200%'\r\n        },\r\n        subsection: {\r\n            textWeight: 'bold',\r\n            textColor: themeVariables?.darkColor\r\n        },\r\n        summary: {\r\n            textSize: typeof themeVariables?.textSize === 'number' ?\r\n                Math.round(themeVariables?.textSize * 1.3) : '200%'\r\n        },\r\n        //Color \r\n        reverse: {\r\n            primaryColor: themeVariables?.backgroundColor,\r\n            textColor: themeVariables?.backgroundColor,\r\n            backgroundColor: themeVariables?.primaryColor,\r\n        },\r\n        selected: {\r\n            primaryColor: themeVariables?.primaryColor, //primary color\r\n            textColor: themeVariables?.primaryColor,    //text color\r\n        },\r\n        unselected: {\r\n            primaryColor: themeVariables?.neutralColor, //neutral color\r\n            textColor: themeVariables?.neutralColor,    //neutral color\r\n        },\r\n        primary: {\r\n            primaryColor: themeVariables?.primaryColor,\r\n            textColor: themeVariables?.primaryColor\r\n        },\r\n        primaryBackground: {\r\n            backgroundColor: themeVariables?.primaryColor,\r\n        },\r\n        // primaryGradient: {\r\n        //     primaryGradient: {colors: ['#0099ff', '#1100ff'], angle: 45},\r\n        //     backgroundGradient: {colors: ['#0099ff', '#1100ff'], angle: 45},\r\n        //     textGradient: {colors: ['#0099ff', '#1100ff'], angle: 45},\r\n        // },\r\n        // primaryGradientBackground: {\r\n        //     backgroundGradient: {colors: [themeVariables?.primaryColor, '#1100ff'], angle: 45},\r\n        // },\r\n        white: {\r\n            primaryColor: '#fff',\r\n            textColor: '#fff'\r\n        },\r\n        whiteBackground: {\r\n            backgroundColor: '#fff',\r\n        },\r\n        light: {\r\n            primaryColor: themeVariables?.lightColor,\r\n            textColor: themeVariables?.lightColor\r\n        },\r\n        lightBackground: {\r\n            backgroundColor: themeVariables?.lightColor\r\n        },\r\n        neutral: {\r\n            primaryColor: themeVariables?.neutralColor,\r\n            textColor: themeVariables?.neutralColor\r\n        },\r\n        neutralBackground: {\r\n            backgroundColor: themeVariables?.neutralColor,\r\n        },\r\n        dark: {\r\n            primaryColor: themeVariables?.darkColor,\r\n            textColor: themeVariables?.darkColor\r\n        },\r\n        darkBackground: {\r\n            backgroundColor: themeVariables?.darkBackground,\r\n        },\r\n        accept: {\r\n            primaryColor: themeVariables?.acceptColor,\r\n            textColor: themeVariables?.acceptBackground\r\n        },\r\n        acceptBackground: {\r\n            backgroundColor: themeVariables?.acceptBackground,\r\n        },\r\n        reject: {\r\n            primaryColor: themeVariables?.rejectColor,\r\n            textColor: themeVariables?.rejectColor\r\n        },\r\n        rejectBackground: {\r\n            backgroundColor: themeVariables?.rejectColor,\r\n        },\r\n        warn: {\r\n            primaryColor: themeVariables?.warnColor,\r\n            textColor: themeVariables?.warnColor\r\n        },\r\n        warnBackground: {\r\n            backgroundColor: themeVariables?.warnColor,\r\n        },\r\n        ...flavors\r\n    };\r\n    const colors = [\r\n        'primaryColor', 'neutralColor', 'acceptColor', 'rejectColor', 'warnColor', 'lightColor',\r\n        'darkColor',\r\n    ];\r\n    Object.keys(themeVariables).filter(v => {return colors.indexOf(v) > -1}).forEach(variableId => {\r\n        const colorName = variableId.replace('Color', '');\r\n        const color = themeVariables[variableId];\r\n        theme[colorName] = {\r\n            primaryColor: color,\r\n            textColor: color\r\n        };\r\n        theme[colorName + 'Background'] = {\r\n            backgroundColor: color\r\n        };\r\n        const color1 = transformColor(color, 15);\r\n        const color2 = transformColor(color, -15);\r\n        theme[colorName + 'Gradient'] = {\r\n            primaryGradient: {colors: [color1, color2], angle: 45},\r\n            backgroundGradient: {colors: [color1, color2], angle: 45},\r\n            textGradient: {colors: [color1, color2], angle: 45},\r\n        };\r\n    });\r\n    return {...theme, ...flavors};\r\n};\r\n\r\nconst transformColor = (hex, delta = 0) => {\r\n    if(!hex || !delta) return '';\r\n    //Transform Hex into RGB\r\n    hex = hex.split('#').filter(Boolean).join('');\r\n    if(hex.length === 3) hex = [...hex].map(x => x + x).join('');\r\n    let r = parseInt(hex.slice(0, 2), 16);\r\n    let g = parseInt(hex.slice(2, 4), 16);\r\n    let b = parseInt(hex.slice(4, 6), 16);\r\n\r\n    //Transform RGB into HSL (rgb from 0 to 1 and h from 0 to 360 and s, l from 0 to 1)\r\n    r /= 255; g /= 255; b /= 255;\r\n    let v = Math.max(r, g, b), c = v - Math.min(r, g, b), f = (1 - Math.abs(v + v - c - 1));\r\n    let h = c && ((v == r) ? (g - b) / c : ((v == g) ? 2 + (b - r) / c : 4 + (r - g) / c));\r\n    h = 60 * (h < 0 ? h + 6 : h); const s = f ? c / f : 0; let l = (v + v - c) / 2;\r\n\r\n    //Transform Hue and Brightness\r\n    if(s > 0.1) h = Math.abs(h + delta);\r\n    else {\r\n        l *= 100;\r\n        l = ((l + delta) > 100) ? 100 : ((l + delta) < 0 ? 0 : l + delta);\r\n        l /= 100;\r\n    }\r\n\r\n    //HSL to RGB (rgb from 0 to 1 and h from 0 to 360 and s, l from 0 to 1)\r\n    const a = s * Math.min(l, 1 - l);\r\n    const d = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\r\n    r = d(0) * 255; g = d(8) * 255; b = d(4) * 255;\r\n\r\n    //RGB to hex\r\n    hex = '#' +\r\n        (Math.round(r << 16) + Math.round(g << 8) + Math.round(b)).toString(16).padStart(6, '0');\r\n    return hex;\r\n};"]}