2
0
mirror of https://github.com/esiur/iui.git synced 2026-04-04 06:58:22 +00:00

Add the ability to specify the router base

This commit is contained in:
Mohammed Salman
2022-02-13 19:34:09 +03:00
parent e52b89fb4d
commit 40ef645954
45 changed files with 5255 additions and 5829 deletions

View File

@@ -5784,9 +5784,8 @@ var _default = _IUI.IUI.module( /*#__PURE__*/function (_IUIElement) {
window.router.on("route", function (e) { window.router.on("route", function (e) {
self.textContent = ''; // clear everything self.textContent = ''; // clear everything
var html = ""; let route = e.route;
var route = e.route; let current = document.createElement("div");
var current = document.createElement("div");
current.innerHTML = route.caption; current.innerHTML = route.caption;
self.append(current); self.append(current);

View File

@@ -1,6 +1,6 @@
{ {
"name": "@esiur/iui", "name": "@esiur/iui",
"version": "1.1.2", "version": "1.1.3",
"description": "Interactive User Interface", "description": "Interactive User Interface",
"main": "iui.js", "main": "iui.js",
"type": "module", "type": "module",

View File

@@ -2,29 +2,28 @@
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import RefsCollection from "./RefsCollection.js"; import RefsCollection from "./RefsCollection.js";
export default IUI.module(class App extends IUIElement { export default IUI.module(
class App extends IUIElement {
constructor() { constructor() {
super(); super();
this.refs = new RefsCollection(this); this.refs = new RefsCollection(this);
} }
create() { create() {
this._register("load"); this._register("load");
window.app = this; window.app = this;
} }
created() { created() {
IUI.bind(this, this, "/", { app: this, refs: this.refs });
IUI.bind(this, this, "/", {app: this, refs: this.refs}); // update referencing
this.refs._build();
// update referencing //IUIElement._make_bindings(this);
this.refs._build(); this.render();
this._emit("load", { app: this });
//IUIElement._make_bindings(this); this.loaded = true;
this.render();
this._emit("load", { app: this });
this.loaded = true;
} }
}
}); );

View File

@@ -2,382 +2,357 @@
import { IUI } from "./IUI.js"; import { IUI } from "./IUI.js";
export const BindingType = { export const BindingType = {
IUIElement: 0, // this will never happen ! IUIElement: 0, // this will never happen !
TextNode: 1, TextNode: 1,
ContentAttribute: 2, ContentAttribute: 2,
Attribute: 3, Attribute: 3,
HTMLElementDataAttribute: 4, HTMLElementDataAttribute: 4,
IUIElementDataAttribute: 5, IUIElementDataAttribute: 5,
IfAttribute: 6, IfAttribute: 6,
RevertAttribute: 7 RevertAttribute: 7,
}; };
export const AttributeBindingDestination = { export const AttributeBindingDestination = {
Field: 0, Field: 0,
Attribute: 1 Attribute: 1,
}; };
const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
export class Binding { export class Binding {
static create(nodeOrAttributeOrIUIElement, scope) { static create(nodeOrAttributeOrIUIElement, scope) {
var code, isAsync, type, attrType, attrKey, func, script; var code, isAsync, type, attrType, attrKey, func, script;
//if (nodeOrAttributeOrIUIElement.created) //if (nodeOrAttributeOrIUIElement.created)
// debugger; // debugger;
if (nodeOrAttributeOrIUIElement instanceof IUIElement) { if (nodeOrAttributeOrIUIElement instanceof IUIElement) {
isAsync = nodeOrAttributeOrIUIElement.hasAttribute("async"); isAsync = nodeOrAttributeOrIUIElement.hasAttribute("async");
type = BindingType.IUIElement; type = BindingType.IUIElement;
} else if (nodeOrAttributeOrIUIElement instanceof Text) {// nodeOrAttribute.nodeType == 3) { } else if (nodeOrAttributeOrIUIElement instanceof Text) {
if (!nodeOrAttributeOrIUIElement.wholeText.match(/\${.*}/)) // nodeOrAttribute.nodeType == 3) {
return null; if (!nodeOrAttributeOrIUIElement.wholeText.match(/\${.*}/)) return null;
type = BindingType.TextNode; type = BindingType.TextNode;
isAsync = nodeOrAttributeOrIUIElement.parentElement.hasAttribute("async"); isAsync = nodeOrAttributeOrIUIElement.parentElement.hasAttribute("async");
//code = "return `" + nodeOrAttributeOrIUIElement.wholeText + "`;"; //code = "return `" + nodeOrAttributeOrIUIElement.wholeText + "`;";
script = nodeOrAttributeOrIUIElement.wholeText; script = nodeOrAttributeOrIUIElement.wholeText;
code = `try {\r\n context.value = \`${script}\`\r\n}\r\n catch(ex) { context.error = ex; }` code = `try {\r\n context.value = \`${script}\`\r\n}\r\n catch(ex) { context.error = ex; }`;
nodeOrAttributeOrIUIElement.data = "";
nodeOrAttributeOrIUIElement.created = true;
} else if (nodeOrAttributeOrIUIElement instanceof Attr) {
if (nodeOrAttributeOrIUIElement.name.startsWith("async::")) {
isAsync = true;
attrType = AttributeBindingDestination.Attribute;
attrKey = nodeOrAttributeOrIUIElement.name.substr(7);
} else if (nodeOrAttributeOrIUIElement.name.startsWith("::")) {
isAsync = false;
attrType = AttributeBindingDestination.Attribute;
attrKey = nodeOrAttributeOrIUIElement.name.substr(2);
} else if (nodeOrAttributeOrIUIElement.name.startsWith("async:")) {
isAsync = true;
attrType = AttributeBindingDestination.Field;
attrKey = nodeOrAttributeOrIUIElement.name.substr(6);
nodeOrAttributeOrIUIElement.data = ""; // skip scope
nodeOrAttributeOrIUIElement.created = true; // if (attrKey == "scope")
} else if (nodeOrAttributeOrIUIElement instanceof Attr) { // return null;
} else if (nodeOrAttributeOrIUIElement.name.startsWith(":")) {
isAsync = false;
attrType = AttributeBindingDestination.Field;
attrKey = nodeOrAttributeOrIUIElement.name.substr(1);
if (nodeOrAttributeOrIUIElement.name.startsWith("async::")) { // skip scope
isAsync = true; // if (attrKey == "scope")
attrType = AttributeBindingDestination.Attribute; // return null;
attrKey = nodeOrAttributeOrIUIElement.name.substr(7); } else {
} return null;
else if (nodeOrAttributeOrIUIElement.name.startsWith("::")) { }
isAsync = false;
attrType = AttributeBindingDestination.Attribute;
attrKey = nodeOrAttributeOrIUIElement.name.substr(2);
}
else if (nodeOrAttributeOrIUIElement.name.startsWith("async:")) {
isAsync = true;
attrType = AttributeBindingDestination.Field;
attrKey = nodeOrAttributeOrIUIElement.name.substr(6);
// skip scope // isAsync = nodeOrAttributeOrIUIElement.value.search("await");
// if (attrKey == "scope")
// return null;
}
else if (nodeOrAttributeOrIUIElement.name.startsWith(":")) {
isAsync = false;
attrType = AttributeBindingDestination.Field;
attrKey = nodeOrAttributeOrIUIElement.name.substr(1);
// skip scope // code = "return " + nodeOrAttributeOrIUIElement.value + ";";
// if (attrKey == "scope")
// return null;
}
else {
return null;
}
// isAsync = nodeOrAttributeOrIUIElement.value.search("await"); script = nodeOrAttributeOrIUIElement.value;
code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }`;
// code = "return " + nodeOrAttributeOrIUIElement.value + ";"; let sentence = attrKey.split("-");
for (var i = 1; i < sentence.length; i++)
sentence[i] =
sentence[i].charAt(0).toUpperCase() + sentence[i].slice(1);
attrKey = sentence.join("");
script = nodeOrAttributeOrIUIElement.value if (attrKey == "content") type = BindingType.ContentAttribute;
code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }` else if (attrKey == "if") {
type = BindingType.IfAttribute;
//displayMode =
} else if (attrKey == "revert") type = BindingType.RevertAttribute;
else if (attrKey != "data") type = BindingType.Attribute;
else if (nodeOrAttributeOrIUIElement.ownerElement instanceof IUIElement)
type = BindingType.IUIElementDataAttribute;
else type = BindingType.HTMLElementDataAttribute;
}
let sentence = attrKey.split("-"); // test the function
for (var i = 1; i < sentence.length; i++)
sentence[i] = sentence[i].charAt(0).toUpperCase() + sentence[i].slice(1);
attrKey = sentence.join("");
if (attrKey == "content") let scopeKeys = Object.keys(scope);
type = BindingType.ContentAttribute; let scopeValues = Object.values(scope);
else if (attrKey == "if") {
type = BindingType.IfAttribute; try {
//displayMode = let args = ["data", "d", "context", "_test", ...scopeKeys];
}
else if (attrKey == "revert") if (isAsync) func = new AsyncFunction(...args, code);
type = BindingType.RevertAttribute; else func = new Function(...args, code);
else if (attrKey != "data") } catch (ex) {
type = BindingType.Attribute; console.log("Test failed: " + ex, code);
else if (nodeOrAttributeOrIUIElement.ownerElement instanceof IUIElement) return null;
type = BindingType.IUIElementDataAttribute; }
else
type = BindingType.HTMLElementDataAttribute; let rt = new Binding();
Object.assign(rt, {
isAsync,
type,
attrType,
attrKey,
func,
target: nodeOrAttributeOrIUIElement,
checked: false,
script,
scopeKeys,
scopeValues,
});
return rt;
}
constructor() {
this.watchList = [];
let self = this;
this.listener = function (name, value) {
self.render(self.data);
};
}
_findMap(thisArg) {
// @TODO: Map thisArg too
let map = {};
let detector = {
get: function (obj, prop) {
if (typeof prop == "string") {
obj[prop] = {};
return new Proxy(obj[prop], detector);
} }
},
};
this.checked = true;
// test the function let proxy = new Proxy(map, detector);
let scopeKeys = Object.keys(scope); try {
let scopeValues = Object.values(scope); let d = this.func.apply(thisArg, [
proxy,
proxy,
{},
true,
...this.scopeValues,
]);
this.map = map;
return d;
} catch (ex) {
//console.log("Proxy failed", ex);
this.map = map;
}
}
async _execute(thisArg, data) {
if (!this.checked) this._findMap(thisArg);
let context = {};
var rt = this.func.apply(thisArg, [
data,
data,
context,
false,
...this.scopeValues,
]);
//console.log(rt);
if (rt instanceof Promise) await rt;
if (context.error != undefined) {
console.log(
"Execution failed",
context.error.name + ": " + context.error.message,
this.script,
this.target
);
return;
} else if (context.value == undefined) {
return;
} else if (context.value instanceof Promise) {
try {
return await context.value;
} catch (ex) {
console.log(
"Execution failed",
ex.name + ": " + ex.message,
this.script,
this.target
);
}
} else {
return context.value;
}
}
unbind() {
this.data = null;
for (var i = 0; i < this.watchList.length; i++)
this.watchList[i].data.off(this.watchList[i].event, this.listener);
this.watchList = [];
}
bind(data, map) {
if (data == null) return;
if (data?.on) {
for (var p in map) {
let event = ":" + p;
data.on(":" + p, this.listener);
this.watchList.push({ data, event });
this.bind(data[p], map[p]);
}
//if (this.watchList.includes(data))
// this.watchList.push({ data, event : });
} else {
for (var p in map) {
this.bind(data[p], map[p]);
}
}
}
async render(data) {
// @TODO: Checking properties bindings moved here
if (data != this.data) this.unbind();
try {
if (this.type === BindingType.IUIElement) {
//let d = this.func.apply(this.target, [data, data]);
//if (d instanceof Promise)
// d = await d;
let d = await this._execute(this.target, data);
await this.target.setData(d);
} else if (this.type === BindingType.TextNode) {
try { try {
let args = ["data", "d", "context", "_test", let d = await this._execute(this.target.parentElement, data);
...scopeKeys]
if (isAsync) if (d === undefined) return false;
func = new AsyncFunction(...args, code); //if (d instanceof Promise)
else // d = await d;
func = new Function(...args, code);
this.target.data = d; // (d === undefined) ? "" : d;
if (data != this.data) {
this.data = data;
this.bind(data, this.map);
}
} catch (ex) {
this.target.data = "";
} }
catch (ex) { }
console.log("Test failed: " + ex, code); // Content Attribute
return null; else if (this.type == BindingType.ContentAttribute) {
let targetElement = this.target.ownerElement;
let d = await this._execute(targetElement, data);
if (d === undefined) return false;
//if (d instanceof Promise)
// d = await d;
targetElement.innerHTML = d;
if (window?.app?.loaded) {
await IUI.create(targetElement);
IUI.bind(
targetElement,
true,
"content",
targetElement.__i_bindings?.scope
);
// update references
targetElement.__i_bindings?.scope?.refs?._build();
await IUI.created(targetElement);
await IUI.render(targetElement, targetElement._data, true);
} }
//await IUI.updateTree(targetElement);
} else if (this.type == BindingType.IfAttribute) {
let d = await this._execute(this.target.ownerElement, data);
//if (d === undefined)
// return false;
let rt = new Binding(); this.target.ownerElement.style.display = d ? "" : "none";
Object.assign(rt, { isAsync, type, attrType, attrKey, func, target: nodeOrAttributeOrIUIElement, checked: false, script, scopeKeys, scopeValues }); } else if (this.type == BindingType.RevertAttribute) {
return rt; let d = await this._execute(this.target.ownerElement, data);
if (d === undefined) return false;
//if (d instanceof Promise)
// d = await d;
}
// Attribute
else if (this.type === BindingType.Attribute) {
//if (this.target.ownerElement.hasAttribute("debug"))
// debugger;
let d = await this._execute(this.target.ownerElement, data);
if (d === undefined) return false;
//if (d instanceof Promise)
// d = await d;
if (this.attrType == AttributeBindingDestination.Field)
this.target.ownerElement[this.attrKey] = d;
else this.target.ownerElement.setAttribute(this.attrKey, d);
if (data != this.data) {
this.data = data;
this.bind(data, this.map);
}
}
// Data Attribute of IUI Element
else if (this.type === BindingType.IUIElementDataAttribute) {
let d = await this._execute(this.target.ownerElement, data);
//if (d === undefined)
// return false;
//if (d instanceof Promise)
// d = await d;
await this.target.ownerElement.setData(d);
}
// Data Attribute of HTML Element
else if (this.type == BindingType.HTMLElementDataAttribute) {
let d = await this._execute(this.target.ownerElement, data);
if (d === undefined) return false;
//if (d instanceof Promise)
// d = await d;
this.target.ownerElement.data = d;
}
return true;
} catch (ex) {
// console.log(ex);
return false;
} }
}
constructor() {
this.watchList = [];
let self = this;
this.listener = function (name, value) {
self.render(self.data);
};
}
_findMap(thisArg) {
// @TODO: Map thisArg too
let map = {};
let detector = {
get: function (obj, prop) {
if (typeof prop == "string") {
obj[prop] = {};
return new Proxy(obj[prop], detector);
}
}
};
this.checked = true;
let proxy = new Proxy(map, detector);
try {
let d = this.func.apply(thisArg, [proxy, proxy, {}, true
, ...this.scopeValues]);
this.map = map;
return d;
}
catch (ex) {
//console.log("Proxy failed", ex);
this.map = map;
}
}
async _execute(thisArg, data) {
if (!this.checked)
this._findMap(thisArg);
let context = {};
var rt = this.func.apply(thisArg, [data, data, context, false,
...this.scopeValues]);
//console.log(rt);
if (rt instanceof Promise)
await rt;
if (context.error != undefined)
{
console.log("Execution failed", context.error.name + ": " + context.error.message, this.script, this.target);
return;
}
else if (context.value == undefined)
{
return;
}
else if (context.value instanceof Promise)
{
try
{
return await context.value;
} catch(ex) {
console.log("Execution failed", ex.name + ": " + ex.message, this.script, this.target);
}
}
else
{
return context.value;
}
}
unbind() {
this.data = null;
for (var i = 0; i < this.watchList.length; i++)
this.watchList[i].data.off(this.watchList[i].event, this.listener);
this.watchList = [];
}
bind(data, map) {
if (data == null)
return;
if (data?.on) {
for (var p in map) {
let event = ":" + p;
data.on(":" + p, this.listener);
this.watchList.push({ data, event});
this.bind(data[p], map[p]);
}
//if (this.watchList.includes(data))
// this.watchList.push({ data, event : });
}
else {
for (var p in map) {
this.bind(data[p], map[p]);
}
}
}
async render(data) {
// @TODO: Checking properties bindings moved here
if (data != this.data)
this.unbind();
try {
if (this.type === BindingType.IUIElement) {
//let d = this.func.apply(this.target, [data, data]);
//if (d instanceof Promise)
// d = await d;
let d = await this._execute(this.target, data);
await this.target.setData(d);
}
else if (this.type === BindingType.TextNode) {
try {
let d = await this._execute(this.target.parentElement, data);
if (d === undefined)
return false;
//if (d instanceof Promise)
// d = await d;
this.target.data = d;// (d === undefined) ? "" : d;
if (data != this.data) {
this.data = data;
this.bind(data, this.map);
}
}
catch (ex) {
this.target.data = "";
}
}
// Content Attribute
else if (this.type == BindingType.ContentAttribute) {
let targetElement = this.target.ownerElement;
let d = await this._execute(targetElement, data);
if (d === undefined)
return false;
//if (d instanceof Promise)
// d = await d;
targetElement.innerHTML = d;
if (window?.app?.loaded)
{
await IUI.create(targetElement);
IUI.bind(targetElement, true, "content", targetElement.__i_bindings?.scope);
// update references
targetElement.__i_bindings?.scope?.refs?._build();
await IUI.created(targetElement);
await IUI.render(targetElement, targetElement._data, true);
}
//await IUI.updateTree(targetElement);
}
else if (this.type == BindingType.IfAttribute)
{
let d = await this._execute(this.target.ownerElement, data);
//if (d === undefined)
// return false;
this.target.ownerElement.style.display = d ? "" : "none";
}
else if (this.type == BindingType.RevertAttribute)
{
let d = await this._execute(this.target.ownerElement, data);
if (d === undefined)
return false;
//if (d instanceof Promise)
// d = await d;
}
// Attribute
else if (this.type === BindingType.Attribute) {
//if (this.target.ownerElement.hasAttribute("debug"))
// debugger;
let d = await this._execute(this.target.ownerElement, data);
if (d === undefined)
return false;
//if (d instanceof Promise)
// d = await d;
if (this.attrType == AttributeBindingDestination.Field)
this.target.ownerElement[this.attrKey] = d;
else
this.target.ownerElement.setAttribute(this.attrKey, d);
if (data != this.data) {
this.data = data;
this.bind(data, this.map);
}
}
// Data Attribute of IUI Element
else if (this.type === BindingType.IUIElementDataAttribute) {
let d = await this._execute(this.target.ownerElement, data);
//if (d === undefined)
// return false;
//if (d instanceof Promise)
// d = await d;
await this.target.ownerElement.setData(d);
}
// Data Attribute of HTML Element
else if (this.type == BindingType.HTMLElementDataAttribute) {
let d = await this._execute(this.target.ownerElement, data);
if (d === undefined)
return false;
//if (d instanceof Promise)
// d = await d;
this.target.ownerElement.data = d;
}
return true;
}
catch (ex) {
// console.log(ex);
return false;
}
}
} }

View File

@@ -1,37 +1,32 @@
export default class BindingList extends Array { export default class BindingList extends Array {
constructor(target, scope) {
super();
this.target = target;
this.scope = scope;
this.events = [];
}
constructor(target, scope) { destroy() {
super(); for (var i = 0; i < this.length; i++) this[i].unbind();
this.target = target; this.scope = {};
this.scope = scope; this.target = null;
this.events = []; for (var i = 0; i < this.events.length; i++)
} this.target.removeEventListener(
this.events[i].name,
this.events[i].handle
);
}
destroy(){ addEvent(name, handle) {
for(var i = 0; i < this.length; i++) this.target.addEventListener(name, handle);
this[i].unbind(); this.events.push({ name, handle });
this.scope = {}; }
this.target = null;
for(var i = 0; i < this.events.length; i++)
this.target.removeEventListener(this.events[i].name, this.events[i].handle);
}
addEvent(name, handle)
{
this.target.addEventListener(name, handle);
this.events.push({name, handle})
}
getArgumentsNames(){
if (this.scope == null)
return [];
let rt;
for (var i in this.scope.length)
rt.push(i);
return rt;
}
getArgumentsNames() {
if (this.scope == null) return [];
let rt;
for (var i in this.scope.length) rt.push(i);
return rt;
}
} }

View File

@@ -1,68 +1,56 @@
import IUIElement from "./IUIElement.js"; import IUIElement from "./IUIElement.js";
import { Binding, BindingType } from "./Binding.js"; import { Binding, BindingType } from "./Binding.js";
//import Route from '../Router/Route.js'; //import Route from '../Router/Route.js';
import BindingList from "./BindingList.js"; import BindingList from "./BindingList.js";
export class IUI { export class IUI {
static _menus = [];
static views = [];
static modules = {};
static registry = [];
static _menus = []; static format(input) {
static views = []; if (typeof input == "string" || input instanceof String) {
static modules = {}; let template = document.createElement("template");
static registry = []; template.innerHTML = input;
let nodes = template.content.cloneNode(true).childNodes;
return nodes;
} else if (input instanceof HTMLCollection) return input;
else if (input instanceof HTMLElement) return [input];
else return [];
}
static format(input) { static observer = new IntersectionObserver(
if (typeof input == "string" || input instanceof String) { function (entries) {
let template = document.createElement("template"); // isIntersecting is true when element and viewport are overlapping
template.innerHTML = input; // isIntersecting is false when element and viewport don't overlap
let nodes = template.content.cloneNode(true).childNodes; for (var i = 0; i < entries.length; i++) {
return nodes; if (entries[i].isIntersecting) {
if (entries[i]._require_update) entries[i].update();
} }
else if (input instanceof HTMLCollection) }
return input; },
else if (input instanceof HTMLElement) { threshold: [0] }
return [input]; );
else
return []; static async created(element) {
for (var i = 0; i < element.children.length; i++) {
let e = element.children[i];
if (e instanceof IUIElement) await e.created();
await IUI.created(e);
} }
}
static observer = new IntersectionObserver(function(entries) { static async create(element) {
// isIntersecting is true when element and viewport are overlapping for (let i = 0; i < element.children.length; i++) {
// isIntersecting is false when element and viewport don't overlap let e = element.children[i];
for(var i = 0; i < entries.length; i++) if (e instanceof IUIElement) {
{ await e.create();
if (entries[i].isIntersecting) }
{
if (entries[i]._require_update)
entries[i].update();
}
}
}, { threshold: [0] }); await IUI.create(e);
static async created (element) {
for (var i = 0; i < element.children.length; i++) {
let e = element.children[i];
if (e instanceof IUIElement)
await e.created();
await IUI.created(e);
}
} }
/*
static async create(element)
{
for (let i = 0; i < element.children.length; i++) {
let e = element.children[i];
if (e instanceof IUIElement) {
await e.create();
}
await IUI.create(e);
}
/*
let router = document.getElementsByTagName("i-router")[0]; let router = document.getElementsByTagName("i-router")[0];
await router.create(); await router.create();
@@ -75,284 +63,254 @@ export class IUI {
} }
*/ */
//for(var i = 0; i < IUI.registry.length; i++) //for(var i = 0; i < IUI.registry.length; i++)
//{ //{
// IUI.extend(IUI.registry[i], IUI.registry[i].properties); // IUI.extend(IUI.registry[i], IUI.registry[i].properties);
// await IUI.registry[i].create(); // await IUI.registry[i].create();
// //await IUI.registry[i].updateAttributes(); // //await IUI.registry[i].updateAttributes();
//} //}
//return; //return;
} }
static get(o) static get(o) {
{ return document.getElementById(o);
return document.getElementById(o);
//for(var i = 0; i < IUI.registry.length; i++) //for(var i = 0; i < IUI.registry.length; i++)
// if (IUI.registry[i].id == o) // if (IUI.registry[i].id == o)
// return IUI.registry[i]; // return IUI.registry[i];
//return null; //return null;
} }
static put(o) static put(o) {
{ IUI.registry.push(o);
IUI.registry.push(o); }
}
static remove(id) static remove(id) {
{ for (var i = 0; i < IUI.registry.length; i++)
for(var i = 0; i < IUI.registry.length; i++) if (IUI.registry[i].el.id == id) {
if (IUI.registry[i].el.id == id) IUI.registry.splice(i, 1);
{ break;
IUI.registry.splice(i, 1); }
break; }
}
}
static module(objectClass) static module(objectClass) {
{ let moduleName = objectClass.moduleName;
let moduleName = objectClass.moduleName;
if (IUI.modules[moduleName] === undefined) { if (IUI.modules[moduleName] === undefined) {
customElements.define("i-" + moduleName, objectClass); customElements.define("i-" + moduleName, objectClass);
IUI.modules[moduleName] = { IUI.modules[moduleName] = {
cls: objectClass, init: function (properties) { cls: objectClass,
return new objectClass(properties); init: function (properties) {
} return new objectClass(properties);
}; },
} };
}
return objectClass; return objectClass;
} }
static extend(properties, defaults, overwrite) static extend(properties, defaults, overwrite) {
{ if (properties == null) properties = defaults;
if (properties == null) else
properties = defaults; for (var i in defaults)
else if (overwrite) properties[i] = defaults[i];
for(var i in defaults) else if (properties[i] === undefined) properties[i] = defaults[i];
if (overwrite) return properties;
properties[i] = defaults[i]; }
else if (properties[i] === undefined)
properties[i] = defaults[i];
return properties;
}
static bind(element, skipAttributes, sourcePath, scope) {
// ::Attribute
// : Field
// async:: Async Attribute
// async: Async Field
// @ Event
static bind(element, skipAttributes, sourcePath, scope) { // skip element ?
if (
element.hasAttribute("skip") ||
element.hasAttribute("i-skip") ||
element instanceof HTMLTemplateElement
)
return;
// ::Attribute // tags to skip
// : Field //if (element instanceof HTMLScriptElement )
// async:: Async Attribute //return;
// async: Async Field
// @ Event
// skip element ? let bindings;
if (element.hasAttribute("skip")
|| element.hasAttribute("i-skip")
|| element instanceof HTMLTemplateElement)
return;
// tags to skip if (scope == null) scope = {};
//if (element instanceof HTMLScriptElement )
//return;
let bindings; // get refs before they get overwritten
//let refs = scope?.refs;
// some element extended or overwritten the binding arguments
if (element.scope != null) IUI.extend(scope, element.scope, true);
else if (element.hasAttribute(":scope")) {
let script = element.getAttribute(":scope");
let code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }`;
let func = new Function("context", code);
let context = {};
if (scope == null) func.call(element, context);
scope = {};
// get refs before they get overwritten if (context.error != undefined)
//let refs = scope?.refs; console.log(
"Scope binding failed",
context.error.name + ": " + context.error.message,
this.script,
this.target
);
else if (context.value != undefined && context.value instanceof Object)
IUI.extend(scope, context.value, true);
}
// some element extended or overwritten the binding arguments let scopeArgs = Object.keys(scope);
if (element.scope != null) let scopeValues = Object.values(scope);
IUI.extend(scope, element.scope, true);
else if (element.hasAttribute(":scope"))
{
let script = element.getAttribute(":scope");
let code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }`
let func = new Function("context", code);
let context = {};
func.call(element, context); bindings = new BindingList(element, scope);
if (context.error != undefined) if (skipAttributes) {
console.log("Scope binding failed", context.error.name + ": " + context.error.message, this.script, this.target); // copy attributes bindings
else if (context.value != undefined if (element.__i_bindings != null)
&& context.value instanceof Object) for (var i = 0; i < element.__i_bindings.length; i++)
IUI.extend(scope, context.value, true); if (element.__i_bindings[i].type != BindingType.TextNode)
} bindings.push(element.__i_bindings[i]);
} else {
element.__i_bindings?.destroy();
let scopeArgs = Object.keys(scope); // compile attributes
let scopeValues = Object.values(scope); for (var i = 0; i < element.attributes.length; i++) {
// skip scope
if (element.attributes[i].name == ":scope") continue;
if (element.attributes[i].name.startsWith("@")) {
// make events
let code = element.attributes[i].value;
//let code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }`
let func = new Function("event", ...scopeArgs, code);
let handler = event => {
func.call(element, event, ...scopeValues);
};
bindings = new BindingList(element, scope); bindings.addEvent(element.attributes[i].name.substr(1), handler);
} else {
let b = Binding.create(element.attributes[i], bindings.scope);
if (skipAttributes) if (b != null) {
{ if (
// copy attributes bindings b.type == BindingType.HTMLElementDataAttribute ||
if (element.__i_bindings != null) b.type == BindingType.IUIElementDataAttribute
for(var i = 0; i < element.__i_bindings.length; i++) )
if (element.__i_bindings[i].type != BindingType.TextNode) element.dataMap = b;
bindings.push(element.__i_bindings[i]); else if (b.type == BindingType.RevertAttribute)
} element.revertMap = b;
else else bindings.push(b);
{ }
element.__i_bindings?.destroy();
// compile attributes
for (var i = 0; i < element.attributes.length; i++) {
// skip scope
if (element.attributes[i].name == ":scope")
continue;
if (element.attributes[i].name.startsWith("@")){
// make events
let code = element.attributes[i].value;
//let code = `try {\r\n context.value = ${script}; \r\n}\r\n catch(ex) { context.error = ex; }`
let func = new Function("event", ...scopeArgs, code);
let handler = (event) => {
func.call(element, event, ...scopeValues);
}
bindings.addEvent(element.attributes[i].name.substr(1), handler);
}
else
{
let b = Binding.create(element.attributes[i],
bindings.scope);
if (b != null) {
if (b.type == BindingType.HTMLElementDataAttribute
|| b.type == BindingType.IUIElementDataAttribute)
element.dataMap = b;
else if (b.type == BindingType.RevertAttribute)
element.revertMap = b;
else
bindings.push(b);
}
}
}
// add reference
// if (element.hasAttribute("ref")) {
// let ref = element.getAttribute("ref");
// if (refs[ref] == null)
// refs[ref] = element;
// else if (refs[ref] == element){
// // do nothing
// }
// else if (refs[ref] instanceof Array){
// refs[ref].push(element);
// } else {
// var firstRef = refs[ref];
// refs[ref] =[firstRef, element];
// }
// }
} }
}
// get new refs (scope might been overwritten) // add reference
//refs = scope?.refs; // if (element.hasAttribute("ref")) {
// let ref = element.getAttribute("ref");
// if (refs[ref] == null)
// refs[ref] = element;
// else if (refs[ref] == element){
// // do nothing
// }
// else if (refs[ref] instanceof Array){
// refs[ref].push(element);
// } else {
// var firstRef = refs[ref];
// refs[ref] =[firstRef, element];
// }
// }
}
// compile nodes // get new refs (scope might been overwritten)
for (var i = 0; i < element.childNodes.length; i++) { //refs = scope?.refs;
let el = element.childNodes[i];
if (el instanceof IUIElement) {
// @TODO: check if the IUI element handles the binding
IUI.bind(el, false, sourcePath, scope);
}
else if (el instanceof HTMLScriptElement)
{
try // compile nodes
{ for (var i = 0; i < element.childNodes.length; i++) {
// this because HTML parser don't evaluate script tag let el = element.childNodes[i];
/// let func = new Function("//# sourceURL=iui://" + sourcePath + "-" + Math.round(Math.random() * 10000) + "\r\n return " + el.text.trim()); if (el instanceof IUIElement) {
let func = new Function(...scopeArgs, // @TODO: check if the IUI element handles the binding
"//# sourceURL=iui://" + sourcePath + "-" IUI.bind(el, false, sourcePath, scope);
+ Math.round(Math.random() * 10000) } else if (el instanceof HTMLScriptElement) {
+ "\r\n" + el.text.trim()); try {
// this because HTML parser don't evaluate script tag
/// let func = new Function("//# sourceURL=iui://" + sourcePath + "-" + Math.round(Math.random() * 10000) + "\r\n return " + el.text.trim());
let func = new Function(
...scopeArgs,
"//# sourceURL=iui://" +
sourcePath +
"-" +
Math.round(Math.random() * 10000) +
"\r\n" +
el.text.trim()
);
let rt = func.apply(el.parentElement, scopeValues); let rt = func.apply(el.parentElement, scopeValues);
console.log("rt", rt); console.log("rt", rt);
if (typeof (rt) === "object") { if (typeof rt === "object") {
for (var k in rt) for (var k in rt) el.parentElement[k] = rt[k];
el.parentElement[k] = rt[k]; }
} } catch (ex) {
} console.log(ex);
catch (ex) {
console.log(ex);
}
}
else if (el instanceof HTMLElement) {
IUI.bind(el, false, sourcePath, scope);
}
else if (el instanceof Text) {
let b = Binding.create(el, bindings.scope);
if (b != null)
bindings.push(b);
}
} }
} else if (el instanceof HTMLElement) {
IUI.bind(el, false, sourcePath, scope);
} else if (el instanceof Text) {
let b = Binding.create(el, bindings.scope);
if (b != null) bindings.push(b);
}
}
element.__i_bindings = bindings; element.__i_bindings = bindings;
} }
static async render(element, data, textNodesOnly = false) { static async render(element, data, textNodesOnly = false) {
if (!element.__i_bindings) {
return;
}
if (!element.__i_bindings) { let bindings = element.__i_bindings;
return;
}
let bindings = element.__i_bindings; if (textNodesOnly) {
for (var i = 0; i < bindings.length; i++)
if (bindings[i].type == BindingType.TextNode)
await bindings[i].render(data);
} else {
// render attributes & text nodes
for (var i = 0; i < bindings.length; i++) await bindings[i].render(data);
}
if (textNodesOnly) { // render children
for (var i = 0; i < bindings.length; i++) for (var i = 0; i < element.children.length; i++) {
if (bindings[i].type == BindingType.TextNode) let el = element.children[i];
await bindings[i].render(data); if (el instanceof IUIElement)
} else { if (el.dataMap != null) {
// render attributes & text nodes // @TODO should check if the element depends on parent or not
for (var i = 0; i < bindings.length; i++) // if map function failed to call setData, we will render without it
await bindings[i].render(data); if (!(await el.dataMap.render(data))) await el.render();
} } else await el.setData(data);
else {
if (el.dataMap != null) await el.dataMap.render(data);
else el.data = data;
// render children //let data = e.mapData(data);
for (var i = 0; i < element.children.length; i++) { await IUI.render(el, el.data);
let el = element.children[i]; }
if (el instanceof IUIElement) }
// @TODO should check if the element depends on parent or not }
if (el.dataMap != null) { }
// if map function failed to call setData, we will render without it
if (!(await el.dataMap.render(data)))
await el.render();
}
else
await el.setData(data);
else {
if (el.dataMap != null)
await el.dataMap.render(data);
else
el.data = data;
//let data = e.mapData(data); export function iui(selector) {
await IUI.render(el, el.data); return IUI.get(selector);
}
}
}
};
export function iui(selector) /*
{
return IUI.get(selector);
/*
if ((typeof selector === 'string' || selector instanceof String) && selector.length > 0) if ((typeof selector === 'string' || selector instanceof String) && selector.length > 0)
{ {
var els = document.querySelectorAll(selector); var els = document.querySelectorAll(selector);
@@ -365,64 +323,58 @@ export function iui(selector)
} }
*/ */
if (typeof(this) == "undefined" || this == window) if (typeof this == "undefined" || this == window) {
{ var o = IUI.get(selector);
var o = IUI.get(selector); if (o) return o;
if (o) else {
return o; var el;
else
{
var el;
if (typeof Node === "object" ? o instanceof Node : ( if (
selector && typeof selector === "object" && typeof selector.nodeType === "number" && typeof selector.nodeName==="string") || selector === window) typeof Node === "object"
{ ? o instanceof Node
el = selector; : (selector &&
} typeof selector === "object" &&
else if (typeof selector === 'string' || selector instanceof String) typeof selector.nodeType === "number" &&
{ typeof selector.nodeName === "string") ||
if (selector[0] == ".") selector === window
el = document.getElementsByClassName(selector.substr(1)); ) {
else el = selector;
el = document.getElementById(selector); } else if (typeof selector === "string" || selector instanceof String) {
} if (selector[0] == ".")
el = document.getElementsByClassName(selector.substr(1));
else el = document.getElementById(selector);
}
if (el) if (el) {
{ var rt = {};
var rt = {}; var makeFunc = function (module) {
var makeFunc = function(module){ return function () {
return function(){ if (el instanceof HTMLCollection) {
if (el instanceof HTMLCollection) let rt = [];
{ for (var i = 0; i < el.length; i++) {
let rt = []; var args = [el[i]];
for(var i = 0; i < el.length; i++) for (var j = 0; j < arguments.length; j++)
{ args.push(arguments[j]);
var args = [el[i]]; rt.push(IUI.modules[module].init.apply(this, args));
for(var j = 0; j < arguments.length; j++) }
args.push(arguments[j]); return rt;
rt.push(IUI.modules[module].init.apply(this, args)); } else {
} var args = [el];
return rt; for (var i = 0; i < arguments.length; i++)
} args.push(arguments[i]);
else return IUI.modules[module].init.apply(this, args);
{ }
var args = [el]; };
for(var i = 0; i < arguments.length; i++) };
args.push(arguments[i]);
return IUI.modules[module].init.apply(this, args);
}
}
};
for(var m in IUI.modules) for (var m in IUI.modules) rt[m] = makeFunc(m);
rt[m] = makeFunc(m);
return rt; return rt;
} }
} }
} }
/* /*
IUI.registry.push(this); IUI.registry.push(this);
@@ -486,7 +438,6 @@ iui.prototype.ne = function(tag)
} }
*/ */
/* /*
iui.prototype.destroy = function() iui.prototype.destroy = function()
{ {

View File

@@ -1,178 +1,154 @@
import { IUI } from "./IUI.js"; import { IUI } from "./IUI.js";
import { Binding, BindingType, AttributeBindingDestination } from "./Binding.js"; import {
Binding,
BindingType,
AttributeBindingDestination,
} from "./Binding.js";
export default class IUIElement extends HTMLElement { export default class IUIElement extends HTMLElement {
constructor(defaults) { constructor(defaults) {
super(); super();
this._events = []; this._events = [];
this._data = null; this._data = null;
this._defaults = defaults; this._defaults = defaults;
for (var i in defaults) for (var i in defaults)
if (this[i] == undefined) if (this[i] == undefined)
try { try {
this[i] = defaults[i]; this[i] = defaults[i];
} catch { } catch {
// mostly because modifying dom attributes are not allowed in custom elements creation // mostly because modifying dom attributes are not allowed in custom elements creation
}
this._register("data");
}
static get moduleName(){
return this.name.toLowerCase();
}
get cssClass(){
if (this.hasAttribute("css-class"))
return this.getAttribute("css-class");
//else
// return this.constructor.moduleName;
}
set cssClass(value)
{
this.classList.remove(this.cssClass);
this.setAttribute("css-class", value);
this.classList.add(value);
}
async render() {
await IUI.render(this, this._data);
}
_getParentData() {
var p = this.parentElement;
do {
if (p.data !== undefined)
return p.data;
} while (p = p.parentElement);
return undefined;
}
async setData(value) {
this._data = value;
this._emit("data", {data: value});
await IUI.render(this, value);
}
get data() {
return this._data;
}
async revert(){
let e = this;
do {
var p = e.parentElement;
if (e.revertMap != null)
await e.revertMap.render(p?.data);
} while (e = p);
}
async update(data) {
if (data == undefined) {
// get parent data
if (this.dataMap != null) {
await this.dataMap.render(this._getParentData());
} else
await this.setData(this.data);
}
else {
// apply specified data
if (this.dataMap != null) {
await this.dataMap.render(data);
} else
await this.setData(data);
}
}
// bindings arguments
get scope(){
return null;
}
// this meant to be inherited
modified() {
}
connectedCallback() {
if (this.hasAttribute("css-class"))
{
this.classList.add(this.getAttribute("css-class"));
}
else
{
let className = this.constructor.moduleName;
this.setAttribute("css-class", className);
this.classList.add(className);
}
}
disconnectedCallback() {
// console.log("removed", this);
}
adoptedCallback() {
//console.log("adopted", this);
}
//appendChild(node) {
// // do some bindings
// super.appendChild(node);
//}
created() {
}
create() {
}
destroy() {
IUI.registry.splice(IUI.registry.indexOf(this), 1);
if (this.parentNode)
this.parentNode.removeChild(this);
}
_emit(event, values) {
//var args = Array.prototype.slice.call(arguments, 1);
var e = new CustomEvent(event, values);
for (let i in values) {
if (e[i] === undefined)
e[i] = values[i];
} }
try this._register("data");
{ }
return this.dispatchEvent(e);
} static get moduleName() {
catch(ex) return this.name.toLowerCase();
{ }
console.log(ex);
} get cssClass() {
if (this.hasAttribute("css-class")) return this.getAttribute("css-class");
//else
// return this.constructor.moduleName;
}
set cssClass(value) {
this.classList.remove(this.cssClass);
this.setAttribute("css-class", value);
this.classList.add(value);
}
async render() {
await IUI.render(this, this._data);
}
_getParentData() {
var p = this.parentElement;
do {
if (p.data !== undefined) return p.data;
} while ((p = p.parentElement));
return undefined;
}
async setData(value) {
this._data = value;
this._emit("data", { data: value });
await IUI.render(this, value);
}
get data() {
return this._data;
}
async revert() {
let e = this;
do {
var p = e.parentElement;
if (e.revertMap != null) await e.revertMap.render(p?.data);
} while ((e = p));
}
async update(data) {
if (data == undefined) {
// get parent data
if (this.dataMap != null) {
await this.dataMap.render(this._getParentData());
} else await this.setData(this.data);
} else {
// apply specified data
if (this.dataMap != null) {
await this.dataMap.render(data);
} else await this.setData(data);
}
}
// bindings arguments
get scope() {
return null;
}
// this meant to be inherited
modified() {}
connectedCallback() {
if (this.hasAttribute("css-class")) {
this.classList.add(this.getAttribute("css-class"));
} else {
let className = this.constructor.moduleName;
this.setAttribute("css-class", className);
this.classList.add(className);
}
}
disconnectedCallback() {
// console.log("removed", this);
}
adoptedCallback() {
//console.log("adopted", this);
}
//appendChild(node) {
// // do some bindings
// super.appendChild(node);
//}
created() {}
create() {}
destroy() {
IUI.registry.splice(IUI.registry.indexOf(this), 1);
if (this.parentNode) this.parentNode.removeChild(this);
}
_emit(event, values) {
//var args = Array.prototype.slice.call(arguments, 1);
var e = new CustomEvent(event, values);
for (let i in values) {
if (e[i] === undefined) e[i] = values[i];
} }
try {
_encapsulateEvent(code){ return this.dispatchEvent(e);
return `try {\r\n ${code} \r\n}\r\n catch(ex) { console.log(ex.name + ":" + ex.message, this); }`; } catch (ex) {
console.log(ex);
} }
}
_register(event) { _encapsulateEvent(code) {
this._events.push(event); return `try {\r\n ${code} \r\n}\r\n catch(ex) { console.log(ex.name + ":" + ex.message, this); }`;
}
/* _register(event) {
this._events.push(event);
/*
if (this.hasAttribute("@" + event)) { if (this.hasAttribute("@" + event)) {
let handler = this.getAttribute("@" + event); let handler = this.getAttribute("@" + event);
if (handler.match(/^[A-Za-z\$_]+(?:[\$_][A-Za-z0-9]+)*$/g) === null) { if (handler.match(/^[A-Za-z\$_]+(?:[\$_][A-Za-z0-9]+)*$/g) === null) {
@@ -198,15 +174,15 @@ export default class IUIElement extends HTMLElement {
} }
} }
*/ */
} }
off(event, func) { off(event, func) {
this.removeEventListener(event, func); this.removeEventListener(event, func);
return this; return this;
} }
on(event, func) { on(event, func) {
this.addEventListener(event, func, false); this.addEventListener(event, func, false);
return this; return this;
} }
} }

12
src/Core/Path.js Normal file
View File

@@ -0,0 +1,12 @@
export default class Path {
/**
* Similar to `os.path.join` in nodejs.
* @param {...String} args
* @returns {String}
*/
static join() {
return Array.from(arguments)
.join("/")
.replace(/\/{1,}/g, "/");
}
}

View File

@@ -1,46 +1,35 @@
export default class RefsCollection {
constructor(rootElement) {
this._rootElement = rootElement;
}
export default class RefsCollection _build(element, append) {
{ if (element == undefined) element = this._rootElement;
constructor(rootElement){ if (!append)
this._rootElement = rootElement; for (var i in this)
} if (i != "_rootElement" && i != "_build") delete this[i];
_build(element, append) { for (var i = 0; i < element.children.length; i++) {
let child = element.children[i];
if (element == undefined) if (child.hasAttribute("ref")) {
element = this._rootElement; let ref = child.getAttribute("ref");
if (this[ref] == null) this[ref] = child;
if (!append) else if (this[ref] == child) {
for(var i in this) // do nothing
if (i != "_rootElement" && i != "_build") } else if (this[ref] instanceof Array) {
delete this[i]; this[ref].push(child);
} else {
for(var i = 0; i < element.children.length; i++) var firstRef = this[ref];
{ this[ref] = [firstRef, child];
let child = element.children[i];
if (child.hasAttribute("ref"))
{
let ref = child.getAttribute("ref");
if (this[ref] == null)
this[ref] = child;
else if (this[ref] == child){
// do nothing
}
else if (this[ref] instanceof Array){
this[ref].push(child);
} else {
var firstRef = this[ref];
this[ref] =[firstRef, child];
}
}
if (child.refs != undefined)
// opt out if the element handles referencing
break;
else
this._build(child, true);
} }
}
if (child.refs != undefined)
// opt out if the element handles referencing
break;
else this._build(child, true);
} }
}
} }

View File

@@ -1,14 +1,13 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
export default IUI.module(class DataList extends IUIElement export default IUI.module(
{ class DataList extends IUIElement {
constructor(properties) constructor(properties) {
{ super(properties);
super(properties); }
}
create() create() {
{ this.style.display = "none";
this.style.display = "none"; }
} }
}); );

View File

@@ -1,62 +1,56 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(
export default IUI.module(class Field extends HTMLElement class Field extends HTMLElement {
{ constructor() {
constructor() super();
{
super();
}
static get moduleName(){
return this.name.toLowerCase();
} }
create() static get moduleName() {
{ return this.name.toLowerCase();
// if (this.formatter === undefined) { }
// // load script
// for (var i = 0; i < this.children.length; i++)
// if (this.children[i] instanceof HTMLScriptElement) {
// //this.formatter = new Function this.children[i].
// }
// }
//this.style.display = "none"; create() {
// if (this.formatter === undefined) {
// // load script
// for (var i = 0; i < this.children.length; i++)
// if (this.children[i] instanceof HTMLScriptElement) {
// //this.formatter = new Function this.children[i].
// }
// }
//this.style.display = "none";
} }
get name() { get name() {
return this.getAttribute("name"); return this.getAttribute("name");
} }
set name(value) { set name(value) {
this.setAttribute("name", value); this.setAttribute("name", value);
} }
serialize(tag) { serialize(tag) {
let template = document.createElement("template");
let node = document.createElement(tag ?? "div");
let width = null,
name = null,
type = null;
let template = document.createElement("template"); // copy attributes
let node = document.createElement(tag ?? "div"); for (var i = 0; i < this.attributes.length; i++) {
let width = null, name = null, type = null; let attr = this.attributes[i];
if (attr.name == "width") width = attr.value;
else if (attr.name == "name") name = attr.value;
else if (attr.name == "type") type = attr.value;
else node.setAttribute(attr.name, attr.value);
}
// copy attributes // copy html
for (var i = 0; i < this.attributes.length; i++) {
let attr = this.attributes[i];
if (attr.name == "width")
width = attr.value;
else if (attr.name == "name")
name = attr.value;
else if (attr.name == "type")
type = attr.value;
else
node.setAttribute(attr.name, attr.value);
}
// copy html node.innerHTML = this.innerHTML;
node.innerHTML = this.innerHTML; return { node, width, name, type };
return { node, width, name, type };
} }
}); }
);

View File

@@ -2,70 +2,62 @@
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Modifiable from "./Modifiable.js"; import Modifiable from "./Modifiable.js";
export default IUI.module(class Form extends IUIElement { export default IUI.module(
class Form extends IUIElement {
constructor() { constructor() {
super(); super();
} }
static _copy(val){ static _copy(val) {
if (typeof val === 'object' && val !== null) if (typeof val === "object" && val !== null) {
{ let rt = {};
let rt = {}; for (var i in val)
for(var i in val) if (val[i] instanceof Array)
if (val[i] instanceof Array) // copy array
// copy array rt[i] = [...val[i]];
rt[i] = [...val[i]]; else rt[i] = val[i];
else
rt[i] = val[i];
return rt; return rt;
} } else return val;
else
return val;
} }
async create() { async create() {
//var elements = this.querySelectorAll("*[field]"); //var elements = this.querySelectorAll("*[field]");
//for (var i = 0; i < elements.length; i++) //for (var i = 0; i < elements.length; i++)
// this.form[elements[i].getAttribute("field")] = elements[i]; // this.form[elements[i].getAttribute("field")] = elements[i];
} }
async setData(value) { async setData(value) {
this.original = value; this.original = value;
//var copy = {}; //var copy = {};
//Object.assign(copy, value); //Object.assign(copy, value);
super.setData(new Modifiable(this.original));// Form._copy(this.original)); super.setData(new Modifiable(this.original)); // Form._copy(this.original));
//super.setData({ ...this.original }); //super.setData({ ...this.original });
} }
async reset() { async reset() {
//super.setData({ ...this.original }); //super.setData({ ...this.original });
super.setData(new Modifiable(this.original));//Form._copy(this.original)); super.setData(new Modifiable(this.original)); //Form._copy(this.original));
return this; return this;
} }
get diff() { get diff() {
return this._data._diff;
return this._data._diff; if (this.original == null) return this._data;
if (this.original == null) var rt = {};
return this._data; for (var i in this._data)
if (this._data[i] != this.original[i]) {
if (
this._data[i] instanceof Array &&
Form._areEqual(this._data[i], this.original[i])
)
continue;
else rt[i] = this._data[i];
}
return rt;
var rt = {};
for (var i in this._data)
if (this._data[i] != this.original[i])
{
if (this._data[i] instanceof Array && Form._areEqual(this._data[i], this.original[i]))
continue;
else
rt[i] = this._data[i];
}
return rt;
} }
}
}); );

View File

@@ -2,114 +2,110 @@ import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import RefsCollection from "../Core/RefsCollection.js"; import RefsCollection from "../Core/RefsCollection.js";
export default IUI.module(class Include extends IUIElement export default IUI.module(
{ class Include extends IUIElement {
constructor() constructor() {
{ super();
super(); this.refs = new RefsCollection();
this.refs = new RefsCollection();
} }
get src(){ get src() {
return this.getAttribute("src"); return this.getAttribute("src");
} }
set src(value){ set src(value) {
this.setAttribute("src", value); this.setAttribute("src", value);
this._load(value); this._load(value);
} }
get scope() { get scope() {
return {view: this, refs: this.refs}; return { view: this, refs: this.refs };
} }
async _load(url) async _load(url) {
{ if (this._loading) return;
if (this._loading)
return;
this._loading = true; this._loading = true;
let src = url.replace(/^\/+|\/+$/g, ''); let src = url.replace(/^\/+|\/+$/g, "");
this.classList.add(this.cssClass + "-loading"); this.classList.add(this.cssClass + "-loading");
let x = await fetch(src); let x = await fetch(src);
if (x.status == 200) if (x.status == 200) {
{ let t = await x.text();
let t = await x.text();
this.innerHTML = t; this.innerHTML = t;
//let xeval = (code) => eval(code); //let xeval = (code) => eval(code);
if (window?.app?.loaded) if (window?.app?.loaded) {
{ await IUI.create(this);
await IUI.create(this); IUI.bind(
IUI.bind(this, true, "include:" + src, this,
IUI.extend(this._i__bindings.scope, this.scope, true)); true,
"include:" + src,
IUI.extend(this._i__bindings.scope, this.scope, true)
);
this.refs._build(); this.refs._build();
await IUI.created(this); await IUI.created(this);
await IUI.render(this, this._data, true); await IUI.render(this, this._data, true);
}
// // call create for the new elements
// var newElements = this.querySelectorAll("*");
// for (var i = 0; i < newElements.length; i++) {
// var el = newElements[i];
// // set route for all elements
// //newElements[i].route = this.route;
// el.route = this.route;
// el.view = this;
// if (el.hasAttribute("ref")) {
// this.refs[el.getAttribute("ref")] = el;
// }
// if (el instanceof HTMLScriptElement) {
// // this because HTML parser don't evaluate script tag
// let func = new Function("//# sourceURL=iui://" + src + "-" + Math.round(Math.random() * 10000) + "\r\n return " + el.text.trim());// "return " + el.text + ";");
// let rt = func.call(el.parentElement);
// //let rt = xeval.call(el.parentElement, "//# sourceURL=iui://" + src + Math.round(Math.random() * 10000) + "\r\n (" + el.text + ")");
// if (typeof (rt) === "object") {
// for (var k in rt)
// el.parentElement[k] = rt[k];
// }
// }
// }
} }
this.classList.remove(this.cssClass + "-loading"); // // call create for the new elements
// var newElements = this.querySelectorAll("*");
// for (var i = 0; i < newElements.length; i++) {
// var el = newElements[i];
// if (window?.app?.loaded) // // set route for all elements
// { // //newElements[i].route = this.route;
// await IUI.create(this); // el.route = this.route;
// await IUI.created(this); // el.view = this;
// if (el.hasAttribute("ref")) {
// this.refs[el.getAttribute("ref")] = el;
// }
// for(let i = 0; i < this.children.length; i++) // if (el instanceof HTMLScriptElement) {
// { // // this because HTML parser don't evaluate script tag
// let el = this.children[i]; // let func = new Function("//# sourceURL=iui://" + src + "-" + Math.round(Math.random() * 10000) + "\r\n return " + el.text.trim());// "return " + el.text + ";");
// IUIElement._make_bindings(el);
// await IUIElement._renderElement(el, el._data); // let rt = func.call(el.parentElement);
// //let rt = xeval.call(el.parentElement, "//# sourceURL=iui://" + src + Math.round(Math.random() * 10000) + "\r\n (" + el.text + ")");
// if (typeof (rt) === "object") {
// for (var k in rt)
// el.parentElement[k] = rt[k];
// }
// } // }
// } // }
}
this._loading = false; this.classList.remove(this.cssClass + "-loading");
// if (window?.app?.loaded)
// {
// await IUI.create(this);
// await IUI.created(this);
// for(let i = 0; i < this.children.length; i++)
// {
// let el = this.children[i];
// IUIElement._make_bindings(el);
// await IUIElement._renderElement(el, el._data);
// }
// }
this._loading = false;
} }
async create() async create() {
{ if (this.hasAttribute("src")) await this._load(this.getAttribute("src"));
if (this.hasAttribute("src"))
await this._load(this.getAttribute("src"));
} }
async created() { async created() {
this.refs._build(); this.refs._build();
} }
}
}); );

View File

@@ -1,64 +1,60 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import Field from './Field.js'; import Field from "./Field.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Layout extends HTMLElement// IUIElement export default IUI.module(
{ class Layout extends HTMLElement {
constructor() // IUIElement
{ constructor() {
super(); super();
}
static get moduleName(){
return this.name.toLowerCase();
} }
//create() static get moduleName() {
//{ return this.name.toLowerCase();
// for (var i = 0; i < this.children.length; i++)
// if (this.children[i] instanceof Field) {
// this[this.children[i].name] = this.children[i];
// this.fields.push(this.children[i]);
// }
// this.style.display = "none";
//}
static getHTML(el, removeSelf = false) {
for (var i = 0; i < el.children.length; i++)
if (el.children[i] instanceof Layout) {
let layout = el.children[i];
let rt = layout.innerHTML;
if (removeSelf)
el.removeChild(layout);
return rt;
}
return null;
}
static get(el, tag, removeSelf = false, collection = false) {
for (var i = 0; i < el.children.length; i++)
if (el.children[i] instanceof Layout) {
let layout = el.children[i];
let rt = collection ? {} : [];
for (var j = 0; j < layout.children.length; j++) {
if (layout.children[j] instanceof Field) {
let fd = layout.children[j].serialize(tag);
if (collection)
rt[fd.name] = fd;
else
rt.push(fd);
}
}
if (removeSelf)
layout.parentElement.removeChild(layout);
return rt;
}
return null;
} }
});
//create()
//{
// for (var i = 0; i < this.children.length; i++)
// if (this.children[i] instanceof Field) {
// this[this.children[i].name] = this.children[i];
// this.fields.push(this.children[i]);
// }
// this.style.display = "none";
//}
static getHTML(el, removeSelf = false) {
for (var i = 0; i < el.children.length; i++)
if (el.children[i] instanceof Layout) {
let layout = el.children[i];
let rt = layout.innerHTML;
if (removeSelf) el.removeChild(layout);
return rt;
}
return null;
}
static get(el, tag, removeSelf = false, collection = false) {
for (var i = 0; i < el.children.length; i++)
if (el.children[i] instanceof Layout) {
let layout = el.children[i];
let rt = collection ? {} : [];
for (var j = 0; j < layout.children.length; j++) {
if (layout.children[j] instanceof Field) {
let fd = layout.children[j].serialize(tag);
if (collection) rt[fd.name] = fd;
else rt.push(fd);
}
}
if (removeSelf) layout.parentElement.removeChild(layout);
return rt;
}
return null;
}
}
);

View File

@@ -1,139 +1,111 @@
export default class Modifiable export default class Modifiable {
{ static _copy(val) {
static _copy(val){ if (typeof val === "object" && val !== null) {
if (typeof val === 'object' && val !== null) let rt = {};
{ for (var i in val)
let rt = {}; if (val[i] instanceof Array)
for(var i in val) // copy array
if (val[i] instanceof Array) rt[i] = [...val[i]];
// copy array else rt[i] = val[i];
rt[i] = [...val[i]];
else
rt[i] = val[i];
return rt; return rt;
} } else return val;
else }
return val;
// @TODO: Remove this when esiur adds suport to partially modified arrays with modified flag
static _areEqual(ar1, ar2) {
if (!(ar1 instanceof Array) || !(ar2 instanceof Array)) return false;
if (ar1.length != ar2.length) return false;
for (var i = 0; i < ar1.length; i++) if (ar1[i] != ar2[i]) return false;
return true;
}
constructor(original) {
this._events = {};
this._data = Modifiable._copy(original);
this._original = original;
for (let p in this._data) {
if (p.startsWith("_")) continue;
this._register(":" + p);
Object.defineProperty(this, p, {
get() {
return this._data[p];
},
set(value) {
this._data[p] = value;
this._emit(":" + p, value);
},
});
} }
}
// @TODO: Remove this when esiur adds suport to partially modified arrays with modified flag get _diff() {
static _areEqual(ar1, ar2) if (this._original == null) return this._data;
{
if (!(ar1 instanceof Array) || !( ar2 instanceof Array))
return false;
if (ar1.length != ar2.length) var rt = {};
return false; for (var i in this._data)
if (this._data[i] != this._original[i]) {
if (
this._data[i] instanceof Array &&
Modifiable._areEqual(this._data[i], this._original[i])
)
continue;
else rt[i] = this._data[i];
}
for(var i = 0; i < ar1.length; i++) return rt;
if (ar1[i] != ar2[i]) }
return false;
return true; _register(event) {
} this._events[event] = [];
}
constructor(original){ _emit(event) {
event = event.toLowerCase();
var args = Array.prototype.slice.call(arguments, 1);
if (this._events[event])
for (var i = 0; i < this._events[event].length; i++)
if (this._events[event][i].f.apply(this._events[event][i].i, args))
return true;
this._events = {}; return false;
this._data = Modifiable._copy(original); }
this._original = original;
for(let p in this._data) _emitArgs(event, args) {
{ event = event.toLowerCase();
if (p.startsWith("_")) if (this._events[event])
continue; for (var i = 0; i < this._events[event].length; i++)
if (this._events[event][i].f.apply(this._events[event][i].i, args))
return true;
return this;
}
this._register(":" + p); on(event, fn, issuer) {
if (!(fn instanceof Function)) return this;
Object.defineProperty(this, p, { event = event.toLowerCase();
get() { // add
return this._data[p]; if (!this._events[event]) this._events[event] = [];
}, this._events[event].push({ f: fn, i: issuer == null ? this : issuer });
set(value) { return this;
this._data[p] = value; }
this._emit(":" + p, value);
}
});
}
} off(event, fn) {
event = event.toLowerCase();
if (this._events[event]) {
get _diff() { if (fn) {
if (this._original == null) for (var i = 0; i < this._events[event].length; i++)
return this._data; if (this._events[event][i].f == fn)
this._events[event].splice(i--, 1);
var rt = {}; } else {
for (var i in this._data)
if (this._data[i] != this._original[i])
{
if (this._data[i] instanceof Array && Modifiable._areEqual(this._data[i], this._original[i]))
continue;
else
rt[i] = this._data[i];
}
return rt;
}
_register(event)
{
this._events[event] = []; this._events[event] = [];
}
} }
}
_emit(event)
{
event = event.toLowerCase();
var args = Array.prototype.slice.call(arguments, 1);
if (this._events[event])
for(var i = 0; i < this._events[event].length; i++)
if (this._events[event][i].f.apply(this._events[event][i].i, args))
return true;
return false;
}
_emitArgs(event, args)
{
event = event.toLowerCase();
if (this._events[event])
for(var i = 0; i < this._events[event].length; i++)
if (this._events[event][i].f.apply(this._events[event][i].i, args))
return true;
return this;
}
on(event, fn, issuer)
{
if (!(fn instanceof Function))
return this;
event = event.toLowerCase();
// add
if (!this._events[event])
this._events[event] = [];
this._events[event].push({f: fn, i: issuer == null ? this: issuer});
return this;
}
off(event, fn)
{
event = event.toLowerCase();
if (this._events[event])
{
if (fn)
{
for(var i = 0; i < this._events[event].length; i++)
if (this._events[event][i].f == fn)
this._events[event].splice(i--, 1);
}
else
{
this._events[event] = [];
}
}
}
} }

View File

@@ -1,65 +1,56 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Repeat extends IUIElement export default IUI.module(
{ class Repeat extends IUIElement {
constructor() constructor() {
{ super({ _data: [] });
super({ _data: [] }); this.list = [];
this.list = [];
} }
_isDirectDecedent(x){ _isDirectDecedent(x) {
while(x = x.parentElement) while ((x = x.parentElement))
if (x == this) if (x == this) return true;
return true; else if (x instanceof Repeat && x != this) return false;
else if (x instanceof Repeat && x != this)
return false;
} }
create() create() {
{ //////////////
////////////// /// Create ///
/// Create /// //////////////
//////////////
if (this._created) if (this._created) debugger;
debugger;
this._created = true; this._created = true;
// create template to speed avoid HTML parsing each time. // create template to speed avoid HTML parsing each time.
let repeatables = this.querySelectorAll("*[repeat]"); let repeatables = this.querySelectorAll("*[repeat]");
repeatables = Array.from(repeatables).filter(x=>this._isDirectDecedent(x)); repeatables = Array.from(repeatables).filter(x =>
this._isDirectDecedent(x)
);
if (repeatables.length > 0) if (repeatables.length > 0) {
{ this._repeatNode = repeatables[0].cloneNode(true);
this._container = repeatables[0].parentElement;
this._beforeNode = repeatables[0].nextSibling;
repeatables[0].parentElement.removeChild(repeatables[0]);
} else {
if (this.children.length > 0)
this._repeatNode = this.children[0].cloneNode(true);
else this._repeatNode = document.createElement("div");
this._repeatNode = repeatables[0].cloneNode(true); this.innerHTML = "";
this._container = repeatables[0].parentElement; this._container = this;
this._beforeNode = repeatables[0].nextSibling; }
repeatables[0].parentElement.removeChild(repeatables[0]);
}
else
{
if (this.children.length > 0)
this._repeatNode = this.children[0].cloneNode(true);
else
this._repeatNode = document.createElement("div");
this.innerHTML = ""; // var newElements = this.querySelectorAll("*");
this._container = this; // for (var i = 0; i < newElements.length; i++)
} // newElements[i].repeat = this;
// var self = this;
// var newElements = this.querySelectorAll("*"); /*
// for (var i = 0; i < newElements.length; i++)
// newElements[i].repeat = this;
// var self = this;
/*
this._repeatModified = function(propertyName, value) this._repeatModified = function(propertyName, value)
{ {
@@ -86,83 +77,72 @@ export default IUI.module(class Repeat extends IUIElement
*/ */
} }
clear() {
clear() for (var i = 0; i < this.list.length; i++)
{ this._container.removeChild(this.list[i]);
for (var i = 0; i < this.list.length; i++) this.list = [];
this._container.removeChild(this.list[i]); this._data = [];
this.list = [];
this._data = [];
} }
get data() { get data() {
return super.data; return super.data;
} }
get length() { get length() {
return this._data.length; return this._data.length;
} }
async setData(value) {
// this to avoid interruption by an event
if (this._busy) {
console.log("Busy", this);
return false;
}
async setData(value) this._busy = true;
{
// clear
this.clear();
// this to avoid interruption by an event if (value?.toArray instanceof Function) value = value.toArray();
if (this._busy) else if (
{ value == null ||
console.log("Busy", this); !(value instanceof Array || value instanceof Int32Array)
return false; )
} value = [];
this._busy = true; //debugger;
await super.setData(value);
for (let i = 0; i < value.length; i++) {
let e = this._repeatNode.cloneNode(true);
// clear this.list.push(e);
this.clear();
if (value?.toArray instanceof Function) await IUI.create(e);
value = value.toArray();
else if (value == null || !(value instanceof Array || value instanceof Int32Array))
value = [];
IUI.bind(
e,
false,
"repeat",
IUI.extend(this.__i_bindings?.scope, { index: i, repeat: this }, true)
);
//debugger; this._container.insertBefore(e, this._beforeNode);
await super.setData(value);
// update referencing
this.__i_bindings?.scope?.refs?._build();
for (let i = 0; i < value.length; i++) { await IUI.created(e);
let e = this._repeatNode.cloneNode(true); await IUI.render(e, value[i], false);
}
this.list.push(e); // @TODO: check if this works for event names starting with ":"
this._emit(":data", { data: value });
// this._emit("modified", { data: value, property: "data" });
await IUI.create(e); this._busy = false;
IUI.bind(e, false, "repeat",
IUI.extend(this.__i_bindings?.scope,
{index: i, repeat: this}, true));
this._container.insertBefore(e, this._beforeNode);
// update referencing
this.__i_bindings?.scope?.refs?._build();
await IUI.created(e);
await IUI.render(e, value[i], false);
}
// @TODO: check if this works for event names starting with ":"
this._emit(":data", { data: value });
// this._emit("modified", { data: value, property: "data" });
this._busy = false;
} }
}
}); );

View File

@@ -1,15 +1,16 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(
export default IUI.module(class TableRow extends IUIElement { class TableRow extends IUIElement {
constructor() { constructor() {
super(); super();
} }
create() { create() {
//this.style.display = "none"; //this.style.display = "none";
this.style.display = "table-row"; this.style.display = "table-row";
console.log("TR"); console.log("TR");
} }
}); }
);

View File

@@ -1,70 +1,65 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Link extends IUIElement export default IUI.module(
{ class Link extends IUIElement {
constructor() constructor() {
{ //debugger;
//debugger; super({ cssClass: "link" });
super({ cssClass: 'link' });
// super({ cssClass: 'link' }); // super({ cssClass: 'link' });
this._register("route"); this._register("route");
this.addEventListener("click", this.addEventListener("click", e => {
(e) => { var r = this.getBoundingClientRect();
this.style.setProperty("--x", e.x - r.x + "px");
this.style.setProperty("--y", e.y - r.y + "px");
var r = this.getBoundingClientRect(); this.style.setProperty("--w", r.width + "px");
this.style.setProperty("--x", (e.x - r.x) + "px"); this.style.setProperty("--h", r.height + "px");
this.style.setProperty("--y", (e.y - r.y) + "px");
this.style.setProperty("--w", r.width + "px"); this.classList.remove(this.cssClass + "-clicked");
this.style.setProperty("--h", r.height + "px"); void this.offsetWidth;
this.classList.add(this.cssClass + "-clicked");
this.classList.remove(this.cssClass + "-clicked"); let url = this.getAttribute("href");
void this.offsetWidth;
this.classList.add(this.cssClass + "-clicked");
let url = this.getAttribute("href"); let ok = this._emit("route", {
url,
cancelable: true,
query: this.query,
});
if (!ok) return;
let ok = this._emit("route", { url, cancelable: true, query: this.query}); //if (url == "#")
if (!ok) // url = router.current.link;
return; // return;
let target = this.hasAttribute("target")
? document.getElementById(this.getAttribute("target"))
: null;
//if (url == "#") if (url == ":back") {
// url = router.current.link; window.router.back();
// return; return;
}
let target = this.hasAttribute("target") ? document.getElementById(this.getAttribute("target")) : null; if (this.query)
// || this.hasAttribute(":data"))
window.router.navigate(url || router.current.url, this.query, target);
else if (url != null) window.router.navigate(url, undefined, target);
});
//this._register("click");
if (url == ":back") {
window.router.back();
return;
}
if (this.query)// || this.hasAttribute(":data"))
window.router.navigate(url || router.current.url, this.query, target);
else if (url != null)
window.router.navigate(url, undefined, target);
}
);
//this._register("click");
} }
get link() { get link() {
return this.getAttribute("href"); return this.getAttribute("href");
} }
set link(value) { set link(value) {
this.setAttribute("href", value); this.setAttribute("href", value);
} }
create() create() {}
{ }
);
}
});

View File

@@ -2,183 +2,136 @@ import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Router from "./Router.js"; import Router from "./Router.js";
import RefsCollection from "../Core/RefsCollection.js"; import RefsCollection from "../Core/RefsCollection.js";
import Path from "../Core/Path.js";
export default IUI.module(class Route extends IUIElement { export default IUI.module(
class Route extends IUIElement {
constructor() { constructor() {
super(); super();
this.routes = []; this.routes = [];
this.refs = new RefsCollection(this); this.refs = new RefsCollection(this);
this._register("show"); this._register("show");
this._register("hide"); this._register("hide");
} }
async setData(value) { async setData(value) {
if (this.hasAttribute("debug")) if (this.hasAttribute("debug")) debugger;
debugger;
return await super.setData(value); return await super.setData(value);
} }
get scope(){ get scope() {
return {route: this, view: this}; return { route: this, view: this };
} }
_updateLinks() { _updateLinks() {
for (var i = 0; i < this.children.length; i++) { for (var i = 0; i < this.children.length; i++) {
if (this.children[i] instanceof Route) { if (this.children[i] instanceof Route) {
this.routes.push(this.children[i]); this.routes.push(this.children[i]);
window.router.add(this.children[i], this); window.router.add(this.children[i], this);
i--; i--;
}
} }
}
} }
get link() { base = "";
var link = this.name;
var parent = this.parent;
while (parent != null) {
link = parent.name + "/" + link;
parent = parent.parent;
}
return link; get link() {
var link = this.name;
var parent = this.parent;
while (parent != null) {
link = parent.name + "/" + link;
parent = parent.parent;
}
return this.base + "/" + link;
} }
get name() { get name() {
return this.getAttribute("name"); return this.getAttribute("name");
} }
get src() { get src() {
return this.getAttribute("src"); return this.getAttribute("src");
} }
get dst() { get dst() {
return this._dst || this.getAttribute("dst"); return this._dst || this.getAttribute("dst");
} }
set dst(value){ set dst(value) {
this._dst = value; this._dst = value;
} }
get caption() { get caption() {
return this.getAttribute("caption"); return this.getAttribute("caption");
} }
get private() { get private() {
return this.hasAttribute("private"); return this.hasAttribute("private");
} }
get icon() { get icon() {
return this.getAttribute("icon"); return this.getAttribute("icon");
} }
_getParent() { _getParent() {
let e = null;//this.parentElement; let e = null; //this.parentElement;
while (e = this.parentElement) { while ((e = this.parentElement)) {
if (e instanceof Route || e instanceof Router) if (e instanceof Route || e instanceof Router) return e;
return e; }
}
return null; return null;
} }
// get route() {
// return this;
// }
// get view() {
// return this;
// }
async create() { async create() {
//window.router.add(this);
this._updateLinks();
//window.router.add(this); if (this.hasAttribute("src")) {
this._updateLinks(); let src = this.getAttribute("src").replace(/^\/+|\/+$/g, "");
let x = await fetch(src);
if (x.status != 200) return;
if (this.hasAttribute("src")) { let t = await x.text();
let src = this.getAttribute("src").replace(/^\/+|\/+$/g, ''); this.innerHTML = t;
let x = await fetch(src); }
if (x.status != 200)
return;
let t = await x.text(); if (window?.app?.loaded) {
await IUI.create(this);
this.innerHTML = t; IUI.bind(this, true, "route:" + src, this.scope);
this.refs._build();
//let xeval = (code) => eval(code); await IUI.created(this);
} await IUI.render(this, this._data, true);
}
if (window?.app?.loaded)
{
await IUI.create(this);
IUI.bind(this, true, "route:" + src, this.scope);
this.refs._build();
await IUI.created(this);
await IUI.render(this, this._data, true);
}
// // call create for the new elements
// var newElements = this.querySelectorAll("*");
// for (var i = 0; i < newElements.length; i++) {
// // set route for all elements
// var el = newElements[i];
// // newElements[i].route = this;
// el.view = this;
// el.route = this;
// if (el.hasAttribute("ref")) {
// this.refs[el.getAttribute("ref")] = el;
// }
// if (el instanceof HTMLScriptElement) {
// // this because HTML parsers don't evaluate script tag
// // xeval.call(el.parentElement, "//# sourceURL=iui://" + src + "\r\n" + el.text);
// //let func = new Function("//# sourceURL=iui://" +
// // src + "-" + Math.round(Math.random() * 10000) + "\r\n return " + el.text.trim());
// let func = new Function("//# sourceURL=iui://" + this.link
// + "\r\n return " + el.text.trim());
// let rt = func.call(el.parentElement);
// if (typeof (rt) === "object") {
// for (var k in rt)
// el.parentElement[k] = rt[k];
// }
// }
// }
} }
created() created() {
{ this.refs._build();
this.refs._build();
} }
set(value) { set(value) {
if (value == this.visible) if (value == this.visible) {
return; return;
}
if (value) { if (value) {
this.setAttribute("selected", "");
this.setAttribute("selected", ""); this._emit("show");
this._emit("show"); } else {
this.removeAttribute("selected");
this._emit("hide");
} }
else
{
this.removeAttribute("selected");
this._emit("hide");
}
} }
get visible() { return this.hasAttribute("selected"); } get visible() {
set visible(value) { this.set(value); } return this.hasAttribute("selected");
}
}); set visible(value) {
this.set(value);
}
}
);

View File

@@ -1,338 +1,273 @@
import IUIElement from "../Core/IUIElement.js"; import Route from "./Route.js";
import Route from "./Route.js"
import Target from "./Target.js"; import Target from "./Target.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import path from "../Core/Path.js";
export default IUI.module(
class Router extends Target {
constructor() {
super({
routes: [],
_states: new Map(),
active: null,
cssClass: "router",
});
export default IUI.module(class Router extends Target this._history = [];
{
constructor()
{
super({routes: [], _states: new Map(), active: null, cssClass: "router"});
this._history = [];
//IUI._router = this;
//Object.defineProperty(window, "router", {
// get() {
// if (!IUI._router.isConnected)
// IUI._router = document.getElementsByTagName("i-router")[0];
// return IUI._router;
// }
//});
} }
_getRouteParent(route) { _getRouteParent(route) {
let e = null; let e = null;
while (e = route.parentElement) { while ((e = route.parentElement)) {
if (e instanceof Route || e instanceof Router) if (e instanceof Route || e instanceof Router) return e;
return e; }
}
return null; return null;
} }
add(route, parent = null) { add(route, parent = null) {
if (parent == null) { route.base = this._base;
this.routes.push(route);
} if (!parent) {
else { this.routes.push(route);
route.parent = parent; return;
this.appendChild(route); }
//parent.routes.push(route);
} route.parent = parent;
this.appendChild(route);
} }
_routeInPath(name, routes) _routeInPath(name, routes) {
{ for (let i = 0; i < routes.length; i++)
for (var i = 0; i < routes.length; i++) if (routes[i].name == name) return routes[i];
if (routes[i].name == name) return null;
return routes[i];
return null;
} }
getRoute(url, data) { getRoute(url, data) {
let p = url.split("/"); /**
* @type {String[]}
*/
const p = url.split("/");
if (p[0] == this._base) p.shift();
let searchRoutes = this.routes;
for (let i = 0; i < p.length; i++) {
const route = this._routeInPath(p[i], searchRoutes);
let searchRoutes = this.routes; if (route == null) return [null, null];
for (var i = 0; i < p.length; i++) { if (i == p.length - 1) {
var route = this._routeInPath(p[i], searchRoutes); // return [destination state route (link, icon,..etc) , actual route to view]
if (route.dst == null) return [route, route];
if (route == null) const dst =
return [null, null]; route.dst instanceof Function ? route.dst(data) : route.dst;
const url = dst.replace(/^[/]*(.*?)[/]*$/g, "$1").trim();
if (i == p.length - 1) { return [route, this.getRoute(url)[1]];
// return [destination state route (link, icon,..etc) , actual route to view]
if (route.dst == null)
return [route, route];
else {
let dst = route.dst instanceof Function ? route.dst(data) : route.dst;
let url = dst.replace(/^[/]*(.*?)[/]*$/g, '$1').trim();
return [route, this.getRoute(url)[1]];
}
}
searchRoutes = route.routes;
} }
searchRoutes = route.routes;
}
} }
back() { back() {
//if (this._history.length > 1) { window.history.back();
// let last = this._history[this._history.length - 2]; }
// this.navigate(last.url, last.data, last.target);
//}
window.history.back();
}
_toQuery(o) { _toQuery(o) {
let rt = []; return Object.keys(o)
for (let i in o) .map(i =>
if (o[i] == undefined) !i ? i : `${i}=${encodeURI(o[i].toString().replace("&", "&&"))}`
rt.push(i); )
else .join("&");
rt.push(i + "=" + encodeURI(o[i].toString().replace("&", "&&")));///encodeURIComponent(o[i]));
return rt.join("&");
} }
_fromQuery(q) { _fromQuery(q) {
let kv = q.replace("&&", "\0").split('&'); const kv = q.replace("&&", "\0").split("&");
let rt = {}; const rt = {};
for (let i = 0; i < kv.length; i++) { for (let i = 0; i < kv.length; i++) {
let d = kv[i].replace("\0", "&").split('=', 2); const d = kv[i].replace("\0", "&").split("=", 2);
let v = decodeURI(d[1] || ''); //decodeURIComponent(d[1] || ''); const v = decodeURI(d[1] || "");
if (v != null && v.trim() != '' && !isNaN(v)) if (v != null && v.trim() != "" && !isNaN(v)) v = new Number(v);
v = new Number(v); rt[d[0]] = v;
rt[d[0]] = v; }
} return JSON.parse(JSON.stringify(rt));
return JSON.parse(JSON.stringify(rt));
} }
async navigate(url, data, target, state, dataToQuery = true) async navigate(url, data, target, state, dataToQuery = true) {
{ let q = url.match(/^\/*(.*?)\?(.*)$|^\/*(.*)$/);
let q = url.match(/^\/*(.*?)\?(.*)$|^\/*(.*)$/);
//debugger; let path;
var path; // Do we have a query string ?
if (q[2] !== undefined) {
path = q[1];
data = this._fromQuery(q[2]);
url = path + "?" + q[2];
}
// Do we have data?
else if (data !== undefined) {
path = q[3];
url = dataToQuery ? path + "?" + this._toQuery(data) : path;
} else {
path = q[3];
url = path;
}
// do we have a query string ? const [stateRoute, viewRoute] = this.getRoute(path, data);
if (q[2] !== undefined) {
path = q[1];
data = this._fromQuery(q[2]);
url = path + "?" + q[2];
}
// do we have data ?
else if (data !== undefined) {
path = q[3];
url = dataToQuery ? path + "?" + this._toQuery(data) : path;
}
else {
path = q[3];
url = path;
}
if (stateRoute == null) {
console.warn("State not found ", path);
return;
}
let [stateRoute, viewRoute] = this.getRoute(path, data); let ok = this._emit("navigate", {
url,
stateRoute,
viewRoute,
base: path,
data,
cancelable: true,
});
if (stateRoute == null) if (!ok) {
{ console.warn("Route not allowed", path);
console.warn("State not found ", path); return;
return; }
}
let ok = this._emit("navigate", { url, stateRoute, viewRoute, base: path, data, cancelable: true }); // destination view not found
if (viewRoute == null) {
console.log(`Destination route not found ${stateRoute.dst}`);
viewRoute = stateRoute;
}
if (!ok) if (!(target instanceof Target)) target = this;
{
console.warn("Route not allowed", path);
return;
}
// destination view not found if (state == null) {
if (viewRoute == null) { const id = Math.random().toString(36).substring(2, 12);
console.log(`Destination route not found ${stateRoute.dst}`); state = { id, url, data, target, stateRoute, viewRoute };
viewRoute = stateRoute; this._states.set(id, state);
} history.pushState(
id,
stateRoute.caption,
this._hash ? "#" + url : "/" + url
);
}
this._history.push(state.id); // { url, data, target, stateRoute, viewRoute });
//let state = null; target.show(viewRoute, this.active);
viewRoute.set(true);
//if (data !== undefined) { this.active = viewRoute;
// for (let [k, v] of this._states)
// if (v == data) {
// state = k;
// break;
// }
// if (state == null) { this._emit("route", { route: stateRoute });
// state = Math.random().toString(36).substr(2, 10);
// this._states.set(state, data);
// }
//}
if (!(target instanceof Target)) viewRoute.query = data || {};
target = this; stateRoute.query = viewRoute.query;
if (state == null) { target.setLoading(true);
let id = Math.random().toString(36).substr(2, 10);
state = { id, url, data, target, stateRoute, viewRoute };
this._states.set(id, state);
history.pushState(id, stateRoute.caption, this._hash ? "#" + url : "/" + url);
}
this._history.push(state.id);// { url, data, target, stateRoute, viewRoute }); if (stateRoute.dataMap != null) {
// if map function failed to call setData, we will render without it
if (!(await stateRoute.dataMap.render(data || {})))
await stateRoute.render();
target.show(viewRoute, this.active); if (viewRoute != stateRoute) await viewRoute.setData(stateRoute.data);
viewRoute.set(true); } //if (data !== undefined)
else await viewRoute.setData(data);
this.active = viewRoute;
//{ url: "/", data: null, target: null };
this._emit("route", { route: stateRoute });
viewRoute.query = data || {};
stateRoute.query = viewRoute.query;
target.setLoading(true);
if (stateRoute.dataMap != null) {
// if map function failed to call setData, we will render without it
if (!(await stateRoute.dataMap.render(data || {})))
await stateRoute.render();
if (viewRoute != stateRoute)
await viewRoute.setData(stateRoute.data);
}
else //if (data !== undefined)
await viewRoute.setData(data);
target.setLoading(false);
target.setLoading(false);
} }
hide() { hide() {
// do nothing, we're not here to hide. // do nothing, we're not here to hide.
} }
refresh() { refresh() {
const state = this.current;
let state = this.current; this.navigate(state.url, state.data, state.target, state);
this.navigate(state.url, state.data, state.target, state);
//this.current.render();
//this.current.data = this.current.data;
//if (updateAttributes)
// this.current.updateAttributes(true);
} }
show(route, active) { show(route, active) {
super.show(route, active); super.show(route, active);
} }
get current() { get current() {
return this._states.get(history.state);//.viewRoute; return this._states.get(history.state); //.viewRoute;
//return this._history[this._history.length - 1].viewRoute;
} }
get previous() { get previous() {
if (this._history.length > 2)
if (this._history.length > 2) return this._states.get(this._history[this._history.length - 2]);
return this._states.get(this._history[this._history.length - 2]);//.viewRoute; //.viewRoute;
else else return null;
return null;
} }
create() { create() {
// save origin
// save origin this.origin = window.location.pathname + window.location.search;
this.origin = window.location.pathname + window.location.search; this._base = this.hasAttribute("base") ? this.getAttribute("base") : "/";
} }
destroy() { destroy() {
console.log("Destroyed", this); console.log("Destroyed", this);
} }
created() created() {
{ if (
this.hasAttribute("type") &&
this.getAttribute("type").toLowerCase() == "hash"
) {
this._hash = true;
}
if (this.hasAttribute("type") && this.getAttribute("type").toLowerCase() == "hash") /// find all children
this._hash = true; for (let i = 0; i < this.children.length; i++) {
const e = this.children[i];
if (e instanceof Route) {
/// find all children this.add(e);
for (var i = 0; i < this.children.length; i++) { if (e.visible) this.navigate(e.name);
let e = this.children[i];
if (e instanceof Route) {
this.add(e);
if (e.visible)
this.navigate(e.name);
}
} }
}
this._emit("created"); this._emit("created");
//console.log("Router created", this);
} }
connectedCallback() { connectedCallback() {
//console.log("New router", this); window.router = this;
window.router = this; const self = this;
window.addEventListener("popstate", function (event) {
const stateId = event.state;
let path;
let self = this; if (self._hash) {
path = window.location.hash;
window.addEventListener("popstate", function (event) { if (path.length > 0) path = path.substring(1);
} else {
path = window.location.pathname;
}
//console.log(event); if (stateId != null) {
let stateId = event.state; if (stateId != self._history[self._history.length - 1]) {
let path; //this._lastStateId = stateId;
const state = self._states.get(stateId);
self.navigate(path, state.data, state.target, state);
} else {
console.log("SAME");
}
} else {
this._lastState = null;
self.navigate(path, undefined, undefined, {});
}
//alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
console.log(document.location.hash, event.state);
});
if (self._hash) { this._register("navigate");
path = window.location.hash; this._register("route");
this._register("created");
if (path.length > 0)
path = path.substr(1);
}
else {
path = window.location.pathname;
}
if (stateId != null) {
if (stateId != self._history[self._history.length -1]) {
//this._lastStateId = stateId;
let state = self._states.get(stateId);
self.navigate(path, state.data, state.target, state);
}
else {
console.log("SAME");
}
}
else {
this._lastState = null;
self.navigate(path, undefined, undefined, {});
}
//alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
console.log(document.location.hash, event.state);
});
this._register("navigate");
this._register("route");
this._register("created");
} }
}
}); );

View File

@@ -2,59 +2,52 @@
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Route from "./Route.js"; import Route from "./Route.js";
export default IUI.module(class Target extends IUIElement { export default IUI.module(
class Target extends IUIElement {
constructor(properties) { constructor(properties) {
super(IUI.extend(properties, { cssClass: 'target' })); super(IUI.extend(properties, { cssClass: "target" }));
this._register("show");
this._register("hide");
this._register("show");
this._register("hide");
} }
setLoading(value) setLoading(value) {
{ if (value) this.classList.add(this.cssClass + "-loading");
if (value) else this.classList.remove(this.cssClass + "-loading");
this.classList.add(this.cssClass + "-loading");
else
this.classList.remove(this.cssClass + "-loading");
} }
create() { create() {}
}
show(route, previous) { show(route, previous) {
let previousTarget = previous?.target;
let previousTarget = previous?.target; route.target = this;
route.target = this; for (var i = 0; i < this.children.length; i++)
if (this.children[i] instanceof Route && this.children[i] != route) {
for (var i = 0; i < this.children.length; i++) this.children[i].set(false);
if (this.children[i] instanceof Route && this.children[i] != route) {
this.children[i].set(false);
}
//if (previous != null && previous != route && previous.target == this) {
// previous.set(false);
//}
//else
if (previousTarget != null && previousTarget != this) {
previousTarget.hide(this.active);
} }
//if (previous != null && previous != route && previous.target == this) {
// previous.set(false);
//}
//else
if (previousTarget != null && previousTarget != this) {
previousTarget.hide(this.active);
}
if (route.parentElement != this) if (route.parentElement != this) this.appendChild(route);
this.appendChild(route);
this._emit("show", { route, previous}); this._emit("show", { route, previous });
} }
hide(route) { hide(route) {
for (var i = 0; i < this.children.length; i++) for (var i = 0; i < this.children.length; i++)
if (this.children[i] instanceof Route) { if (this.children[i] instanceof Route) {
this.children[i].set(false); this.children[i].set(false);
} }
this._emit("hide", { route }); this._emit("hide", { route });
} }
}); }
);

View File

@@ -1,40 +1,36 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Background extends IUIElement { export default IUI.module(
class Background extends IUIElement {
constructor() { constructor() {
super({ cssClass: 'background' }); super({ cssClass: "background" });
this.classList.add(this.cssClass);
this._register("visible");
this.classList.add(this.cssClass);
this._register("visible");
} }
create() {}
create() {
}
hide() { hide() {
return this.setVisible(false); return this.setVisible(false);
} }
show() { show() {
return this.setVisible(true); return this.setVisible(true);
} }
setVisible(value) { setVisible(value) {
this.visible = value; this.visible = value;
if (value) { if (value) {
this.classList.add(this.cssClass + "-visible"); this.classList.add(this.cssClass + "-visible");
} } else {
else { this.classList.remove(this.cssClass + "-visible");
this.classList.remove(this.cssClass + "-visible"); }
}
this._emit("visible", value); this._emit("visible", value);
return this; return this;
} }
}); }
);

View File

@@ -1,70 +1,66 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Button extends IUIElement { export default IUI.module(
class Button extends IUIElement {
constructor() { constructor() {
super({ cssClass: 'button' }); super({ cssClass: "button" });
this.addEventListener("mousedown", (e)=>{ this.addEventListener(
"mousedown",
e => {
var r = this.getBoundingClientRect();
this.style.setProperty("--x", e.x - r.x + "px");
this.style.setProperty("--y", e.y - r.y + "px");
var r = this.getBoundingClientRect(); this.style.setProperty("--w", r.width + "px");
this.style.setProperty("--x", (e.x - r.x) + "px"); this.style.setProperty("--h", r.height + "px");
this.style.setProperty("--y", (e.y - r.y) + "px");
this.style.setProperty("--w", r.width + "px"); this.classList.remove(this.cssClass + "-clicked");
this.style.setProperty("--h", r.height + "px"); void this.offsetWidth;
this.classList.add(this.cssClass + "-clicked");
},
true
);
this.classList.remove(this.cssClass + "-clicked"); this._register("check");
void this.offsetWidth;
this.classList.add(this.cssClass + "-clicked");
}, true);
this._register("check");
} }
get type() { get type() {
return this.getAttribute("type"); return this.getAttribute("type");
} }
set type(value) set type(value) {
{ this.setAttribute("type", value);
this.setAttribute("type", value);
} }
get checked() { get checked() {
return this.hasAttribute("checked"); return this.hasAttribute("checked");
} }
set checked(value) set checked(value) {
{ if (value) this.setAttribute("checked", "");
if (value) else this.removeAttribute("checked");
this.setAttribute("checked", "");
else
this.removeAttribute("checked");
} }
get disabled() { get disabled() {
return this.getAttribute("disabled"); return this.getAttribute("disabled");
} }
set disabled(value) { set disabled(value) {
this.setAttribute("disabled", value); this.setAttribute("disabled", value);
} }
create() { create() {
if (this.type == "check") {
this.addEventListener("click", () => {
let checked = !this.checked;
this.checked = checked;
this._emit("check", { checked });
});
}
if (this.type == "check") //this.classList.add(this.cssClass);
{
this.addEventListener("click", ()=>{
let checked = !this.checked;
this.checked = checked;
this._emit("check", {checked});
});
}
//this.classList.add(this.cssClass);
} }
}); }
);

View File

@@ -1,58 +1,54 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Check extends IUIElement { export default IUI.module(
class Check extends IUIElement {
constructor(properties) { constructor(properties) {
super(IUI.extend(properties, { cssClass: 'check' })); super(IUI.extend(properties, { cssClass: "check" }));
this._register("check"); this._register("check");
this.on("click", () => { this.on("click", () => {
this.checked = !this.checked; this.checked = !this.checked;
}); });
} }
get checked() { get checked() {
return this.hasAttribute("checked"); return this.hasAttribute("checked");
} }
set checked(value) { set checked(value) {
this.check(value); this.check(value);
this._emit("check", { checked: value }); this._emit("check", { checked: value });
} }
check(value) { check(value) {
if (value) if (value) this.setAttribute("checked", "checked");
this.setAttribute("checked", "checked"); else this.removeAttribute("checked");
else
this.removeAttribute("checked");
} }
create() { create() {
this.field = this.getAttribute("field"); this.field = this.getAttribute("field");
} }
async setData(value) { async setData(value) {
await super.setData(value); await super.setData(value);
if (value != null && this.field != null) if (value != null && this.field != null) this.value = value[this.field];
this.value = value[this.field]; else if (this.field != null) this.value = null;
else if (this.field != null)
this.value = null;
} }
modified(name, value) { modified(name, value) {
if (name == this.field) { if (name == this.field) {
this.value = value; this.value = value;
} }
} }
get value() { get value() {
return this.checked; return this.checked;
} }
set value(value) { set value(value) {
this.checked = value; this.checked = value;
} }
}
}); );

View File

@@ -2,88 +2,87 @@ import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import RefsCollection from "../Core/RefsCollection.js"; import RefsCollection from "../Core/RefsCollection.js";
export default IUI.module(class CodePreview extends IUIElement { export default IUI.module(
class CodePreview extends IUIElement {
constructor() { constructor() {
super(); super();
this.refs = new RefsCollection(this); this.refs = new RefsCollection(this);
this._code = this.innerHTML.trim(); this._code = this.innerHTML.trim();
this.textContent = ''; this.textContent = "";
} }
async create() { async create() {
if (this.hasAttribute("debug")) debugger;
if (this.hasAttribute("debug")) //this._code = this.innerHTML.trim();
debugger; //this.textContent = '';
//this._code = this.innerHTML.trim(); // create elements
//this.textContent = ''; this.bar = document.createElement("div");
this.bar.className = this.cssClass + "-bar";
this.content = document.createElement("div");
this.content.className = this.cssClass + "-content";
this.editor = document.createElement("code");
this.editor.className = this.cssClass + "-editor";
// create elements this.editor.innerText = this._code;
this.bar = document.createElement("div"); this.editor.contentEditable = true;
this.bar.className = this.cssClass + "-bar";
this.content = document.createElement("div");
this.content.className = this.cssClass + "-content";
this.editor = document.createElement("code");
this.editor.className = this.cssClass + "-editor";
this.editor.innerText = this._code; this.editor.setAttribute("skip", true);
this.editor.contentEditable = true;
this.editor.setAttribute("skip", true); let self = this;
this.editor.addEventListener(
"input",
function () {
self._code = self.editor.textContent.trim();
self.updatePreview();
},
false
);
let self = this; this.preview = document.createElement("div");
this.editor.addEventListener("input", function() { this.preview.className = this.cssClass + "-preview";
self._code = self.editor.textContent.trim(); //this.preview.setAttribute(":content", "");
self.updatePreview();
}, false);
this.preview = document.createElement("div"); this.content.append(this.editor);
this.preview.className = this.cssClass + "-preview"; this.content.append(this.preview);
//this.preview.setAttribute(":content", "");
this.content.append(this.editor); this.append(this.bar);
this.content.append(this.preview); this.append(this.content);
this.field = this.getAttribute("field");
this.append(this.bar); //await this.updatePreview();
this.append(this.content);
this.field = this.getAttribute("field");
//await this.updatePreview();
} }
async created(){ async created() {
await this.updatePreview(); await this.updatePreview();
} }
get scope(){ get scope() {
return {view: this, refs: this.refs}; return { view: this, refs: this.refs };
} }
async updatePreview() { async updatePreview() {
if (this._updating) return;
this._updating = true;
if (this._updating) this.preview.innerHTML = this._code;
return; //this.editor.innerHTML = hljs.highlightAuto(this._code).value;
this._updating = true; // this.editor.innerHTML = hljs.highlight(this._code, {language: 'html'}).value
this.preview.innerHTML = this._code; // this.editor.innerHTML = hljs.highlightElement(this.editor, {language: 'html'}).value;
//this.editor.innerHTML = hljs.highlightAuto(this._code).value;
// this.editor.innerHTML = hljs.highlight(this._code, {language: 'html'}).value if (window.app?.loaded) {
await IUI.create(this.preview);
await IUI.created(this.preview);
IUI.bind(this.preview, true, "preview", this.scope);
this.refs._build();
await IUI.render(this.preview, this._data, true);
}
// this.editor.innerHTML = hljs.highlightElement(this.editor, {language: 'html'}).value; this._updating = false;
if (window.app?.loaded)
{
await IUI.create(this.preview);
await IUI.created(this.preview);
IUI.bind(this.preview, true, "preview", this.scope);
this.refs._build();
await IUI.render(this.preview, this._data, true);
}
this._updating = false;
} }
}); }
);

View File

@@ -1,129 +1,124 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class DateTimePicker extends IUIElement { export default IUI.module(
class DateTimePicker extends IUIElement {
constructor() { constructor() {
super(); super();
} }
get layout() { get layout() {
return this._layout; return this._layout;
} }
set layout(value) { set layout(value) {
if (value == this._layout) return;
if (value == this._layout) this.innerHTML = "";
return;
this.innerHTML = ""; this._layout = value;
this._layout = value; this.calendar = document.createElement("div");
this.calendar.className = this.cssClass + "-calendar";
this.calendar = document.createElement("div"); this.calendarContent = document.createElement("div");
this.calendar.className = this.cssClass + "-calendar"; this.calendarContent.className = this.cssClass + "-calendar-content";
this.table = document.createElement("table");
this.header = this.table.createTHead();
this.body = this.table.createTBody();
this.calendarContent = document.createElement("div"); this.calendarContent.appendChild(this.table);
this.calendarContent.className = this.cssClass + "-calendar-content";
this.table = document.createElement("table"); var tr = this.header.insertRow();
this.header = this.table.createTHead();
this.body = this.table.createTBody();
this.calendarContent.appendChild(this.table); for (var i = 0; i < 7; i++) {
var td = tr.insertCell();
td.innerHTML = this.layout.day.formatter(
(i + this.layout.weekStart) % 7
);
td.className = this.cssClass + "-day";
}
var tr = this.header.insertRow(); this.tools = document.createElement("div");
this.tools.className = this.cssClass + "-tools";
for (var i = 0; i < 7; i++) { this.month = document.createElement("div");
var td = tr.insertCell(); this.month.className = this.cssClass + "-month";
td.innerHTML = this.layout.day.formatter((i + this.layout.weekStart) % 7); this.monthName = document.createElement("div");
td.className = this.cssClass + "-day"; this.monthName.className = this.cssClass + "-name";
this.nextMonth = document.createElement("div");
this.nextMonth.className = this.cssClass + "-next";
this.previousMonth = document.createElement("div");
this.previousMonth.className = this.cssClass + "-previous";
this.month.appendChild(this.previousMonth);
this.month.appendChild(this.monthName);
this.month.appendChild(this.nextMonth);
this.year = document.createElement("div");
this.year.className = this.cssClass + "-year";
this.yearName = document.createElement("div");
this.yearName.className = this.cssClass + "-name";
this.nextYear = document.createElement("div");
this.nextYear.className = this.cssClass + "-next";
this.previousYear = document.createElement("div");
this.previousYear.className = this.cssClass + "-previous";
this.year.appendChild(this.previousYear);
this.year.appendChild(this.yearName);
this.year.appendChild(this.nextYear);
this.tools.appendChild(this.month);
this.tools.appendChild(this.year);
let self = this;
this.nextMonth.addEventListener("click", function () {
self._month = (self._month + 1) % 12;
self.render();
});
this.previousMonth.addEventListener("click", function () {
self._month = (self._month + 11) % 12;
self.render();
});
this.nextYear.addEventListener("click", function () {
self._year++;
self.render();
});
this.previousYear.addEventListener("click", function () {
self._year--;
self.render();
});
for (let i = 0; i < 6; i++) {
tr = this.body.insertRow();
for (var j = 0; j < 7; j++) {
let td = tr.insertCell(tr);
td.className = this.cssClass + "-day";
td.innerHTML = i + "x" + j;
td.addEventListener("click", function () {
self._day = parseInt(this.getAttribute("data-day"));
self._month = parseInt(this.getAttribute("data-month"));
self._year = parseInt(this.getAttribute("data-year"));
self._value.setDate(self._day);
self._value.setFullYear(self._year);
self._value.setMonth(self._month);
self.render();
self._emit("select", { value: self._value });
self._emit(":value", { value });
});
} }
}
this.tools = document.createElement("div"); this.calendar.appendChild(this.tools);
this.tools.className = this.cssClass + "-tools"; this.calendar.appendChild(this.calendarContent);
this.month = document.createElement("div"); /*
this.month.className = this.cssClass + "-month";
this.monthName = document.createElement("div");
this.monthName.className = this.cssClass + "-name";
this.nextMonth = document.createElement("div");
this.nextMonth.className = this.cssClass + "-next";
this.previousMonth = document.createElement("div");;
this.previousMonth.className = this.cssClass + "-previous";
this.month.appendChild(this.previousMonth);
this.month.appendChild(this.monthName);
this.month.appendChild(this.nextMonth);
this.year = document.createElement("div");
this.year.className = this.cssClass + "-year";
this.yearName = document.createElement("div");
this.yearName.className = this.cssClass + "-name";
this.nextYear = document.createElement("div");
this.nextYear.className = this.cssClass + "-next";
this.previousYear = document.createElement("div");
this.previousYear.className = this.cssClass + "-previous";
this.year.appendChild(this.previousYear);
this.year.appendChild(this.yearName);
this.year.appendChild(this.nextYear);
this.tools.appendChild(this.month);
this.tools.appendChild(this.year);
let self = this;
this.nextMonth.addEventListener("click", function () {
self._month = (self._month + 1) % 12;
self.render();
});
this.previousMonth.addEventListener("click", function () {
self._month = (self._month + 11) % 12;
self.render();
});
this.nextYear.addEventListener("click", function () {
self._year++;
self.render();
});
this.previousYear.addEventListener("click", function () {
self._year--;
self.render();
});
for (let i = 0; i < 6; i++) {
tr = this.body.insertRow();
for (var j = 0; j < 7; j++) {
let td = tr.insertCell(tr);
td.className = this.cssClass + "-day";
td.innerHTML = i + "x" + j;
td.addEventListener("click", function () {
self._day = parseInt(this.getAttribute("data-day"));
self._month = parseInt(this.getAttribute("data-month"));
self._year = parseInt(this.getAttribute("data-year"));
self._value.setDate(self._day);
self._value.setFullYear(self._year);
self._value.setMonth(self._month);
self.render();
self._emit("select", { value: self._value });
self._emit(":value", { value });
});
}
}
this.calendar.appendChild(this.tools);
this.calendar.appendChild(this.calendarContent);
/*
this.minutes = document.createElement("div"); this.minutes = document.createElement("div");
this.minutes.className = this.cssClass + "-clock"; this.minutes.className = this.cssClass + "-clock";
@@ -149,166 +144,180 @@ export default IUI.module(class DateTimePicker extends IUIElement {
} }
*/ */
this.clock = document.createElement("div"); this.clock = document.createElement("div");
this.clock.className = this.cssClass + "-clock"; this.clock.className = this.cssClass + "-clock";
for (let i = 0; i < 1440; i += this.layout.time.range) { for (let i = 0; i < 1440; i += this.layout.time.range) {
var range = document.createElement("div"); var range = document.createElement("div");
range.className = this.cssClass + "-time"; range.className = this.cssClass + "-time";
range.innerHTML = this.layout.time.formatter(i); range.innerHTML = this.layout.time.formatter(i);
range.setAttribute("data-time", i); range.setAttribute("data-time", i);
this.clock.appendChild(range); this.clock.appendChild(range);
range.addEventListener("click", function () { range.addEventListener("click", function () {
var t = parseInt(this.getAttribute("data-time")); var t = parseInt(this.getAttribute("data-time"));
var h = Math.floor(t / 60); var h = Math.floor(t / 60);
var m = Math.floor(t % 60); var m = Math.floor(t % 60);
self._value.setHours(h); self._value.setHours(h);
self._value.setMinutes(m); self._value.setMinutes(m);
self._emit("select", self._value); self._emit("select", self._value);
self.render(); self.render();
}); });
} }
//this.timeList = document.createElement("div"); //this.timeList = document.createElement("div");
//this.timeList = //this.timeList =
this.appendChild(this.calendar); this.appendChild(this.calendar);
this.appendChild(this.clock); this.appendChild(this.clock);
// this.appendChild(this.minutes); // this.appendChild(this.minutes);
// this.appendChild(this.hours); // this.appendChild(this.hours);
this.value = new Date(); this.value = new Date();
} }
create() { create() {
var self = this;
var self = this; this._register("select");
this.classList.add(this.cssClass);
this._register("select"); this.layout = {
day: {
formatter: function (index) {
return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][index];
//return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][index];
},
},
month: {
formatter: function (index) {
return [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
][index];
},
},
year: {
formatter: function (value) {
return value;
},
},
time: {
formatter: function (value) {
var formatDigit = function (d) {
return d < 10 ? "0" + d : d;
};
var h = Math.floor(value / 60);
var m = Math.floor(value % 60);
return formatDigit(h) + ":" + formatDigit(m);
},
range: 15,
},
this.classList.add(this.cssClass); weekStart: 5,
};
this.layout = {
day: {
formatter: function (index) {
return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][index];
//return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][index];
}
},
month: {
formatter: function (index) {
return ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"][index];
}
},
year: {
formatter: function (value) {
return value;
}
},
time: {
formatter: function (value) {
var formatDigit = function (d) { return (d < 10) ? "0" + d : d; };
var h = Math.floor(value / 60);
var m = Math.floor(value % 60);
return formatDigit(h) + ":" + formatDigit(m);
},
range: 15
},
weekStart: 5
};
} }
render() { render() {
var start = new Date(this._year, this._month, 1);
var offset = 1 - start.getDay() - ((7 - this.layout.weekStart) % 7); //(this.weekStart > 3 ? (this.weekStart - 7) : this.weekStart);
var start = new Date(this._year, this._month, 1); this.yearName.innerHTML = this.layout.year.formatter(this._year);
var offset = 1 - start.getDay() - (7 - this.layout.weekStart) % 7;//(this.weekStart > 3 ? (this.weekStart - 7) : this.weekStart); this.monthName.innerHTML = this.layout.month.formatter(this._month);
this.yearName.innerHTML = this.layout.year.formatter(this._year); var today = new Date();
this.monthName.innerHTML = this.layout.month.formatter(this._month);
var today = new Date(); for (var i = 0; i < 42; i++) {
var rowIndex = Math.floor(i / 7);
var cellIndex = i % 7;
for (var i = 0; i < 42; i++) { var td = this.body.rows[rowIndex].cells[cellIndex];
var rowIndex = Math.floor(i / 7);
var cellIndex = i % 7;
var td = this.body.rows[rowIndex].cells[cellIndex]; var d = new Date(this._year, this._month, offset + i);
var d = new Date(this._year, this._month, offset + i); td.classList.remove(this.cssClass + "-different-month");
td.classList.remove(this.cssClass + "-different-month"); // gray it
if (d.getMonth() != this._month)
td.classList.add(this.cssClass + "-different-month");
// gray it if (
if (d.getMonth() != this._month) d.getDate() == today.getDate() &&
td.classList.add(this.cssClass + "-different-month"); d.getMonth() == today.getMonth() &&
d.getFullYear() == today.getFullYear()
)
td.classList.add(this.cssClass + "-day-today");
else td.classList.remove(this.cssClass + "-day-today");
if (d.getDate() == today.getDate() && d.getMonth() == today.getMonth() && d.getFullYear() == today.getFullYear()) if (
td.classList.add(this.cssClass + "-day-today"); d.getDate() == this._value.getDate() &&
else d.getFullYear() == this._value.getFullYear() &&
td.classList.remove(this.cssClass + "-day-today"); d.getMonth() == this._value.getMonth()
)
td.classList.add(this.cssClass + "-day-selected");
else td.classList.remove(this.cssClass + "-day-selected");
if (d.getDate() == this._value.getDate() td.setAttribute("data-day", d.getDate());
&& d.getFullYear() == this._value.getFullYear() td.setAttribute("data-month", d.getMonth());
&& d.getMonth() == this._value.getMonth()) td.setAttribute("data-year", d.getFullYear());
td.classList.add(this.cssClass + "-day-selected");
else
td.classList.remove(this.cssClass + "-day-selected");
td.innerHTML = d.getDate();
}
td.setAttribute("data-day", d.getDate()); for (var i = 0; i < this.clock.children.length; i++)
td.setAttribute("data-month", d.getMonth()); this.clock.children[i].classList.remove(
td.setAttribute("data-year", d.getFullYear()); this.cssClass + "-time-selected"
);
td.innerHTML = d.getDate(); var time = this._value.getHours() * 60 + this._value.getMinutes();
}
if (time % this.layout.time.range == 0)
for (var i = 0; i < this.clock.children.length; i++) this.clock.children[time / this.layout.time.range].classList.add(
this.clock.children[i].classList.remove(this.cssClass + "-time-selected"); this.cssClass + "-time-selected"
);
var time = (this._value.getHours() * 60) + this._value.getMinutes();
if (time % this.layout.time.range == 0)
this.clock.children[time / this.layout.time.range].classList.add(this.cssClass + "-time-selected");
} }
async setData(value) { async setData(value) {
await super.setData(value);
await super.setData(value); if (value != null && this.field != null)
this.value = this.data[this.field];
if (value != null && this.field != null)
this.value = this.data[this.field];
} }
get data() { get data() {
return super.data; return super.data;
} }
modified(name, value) { modified(name, value) {
if (name == this.field) if (name == this.field) this.value = value;
this.value = value;
} }
set value(value) { set value(value) {
if (value && !isNaN(value.getTime())) { if (value && !isNaN(value.getTime())) {
this._value = value; this._value = value;
this._month = value.getMonth(); this._month = value.getMonth();
this._year = value.getFullYear(); this._year = value.getFullYear();
this._day = value.getDate(); this._day = value.getDate();
this.render(); this.render();
this._emit("select", { value }); this._emit("select", { value });
this._emit("modified", { value, property: "value" }); this._emit("modified", { value, property: "value" });
//this.modified("value", ); //this.modified("value", );
//this.modified("modified", { value }); //this.modified("modified", { value });
} }
} }
get value() { get value() {
return this._value; return this._value;
} }
}); }
);

View File

@@ -2,271 +2,265 @@ import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import IUIWindow from "./Window.js"; import IUIWindow from "./Window.js";
export default IUI.module(class IUIDialog extends IUIWindow export default IUI.module(
{ class IUIDialog extends IUIWindow {
static moduleName = "dialog"; static moduleName = "dialog";
constructor() constructor() {
{ super({
super({ closeable: true,
closeable: true, resizeable: true,
resizeable: true, draggable: false,
draggable: false, _dragging: false,
_dragging: false, _expanding: false,
_expanding: false, x: 0,
x: 0, y: 0,
y: 0, visible: false,
visible: false, modal: false,
modal: false });
}
);
var self = this; var self = this;
this._register("visible"); this._register("visible");
this._register("resize"); this._register("resize");
this.on("close", function(){ this.on("close", function () {
self.hide(); self.hide();
}); });
} }
create() create() {
{ super.create();
var self = this;
super.create(); if (this.modal) {
var self = this; this.background = iui("iui_app_background");
if (!this.background) {
var bg = document.createElement("div");
bg.id = "iui_app_background";
document.body.insertAdjacentElement("afterBegin", bg);
this.background = iui(bg).background();
}
if (this.modal) // this.modal.className = this.customClass + "-modal-background";
{
this.background = iui("iui_app_background");
if (!this.background)
{
var bg = document.createElement("div");
bg.id="iui_app_background";
document.body.insertAdjacentElement("afterBegin", bg);
this.background = iui(bg).background();
}
this.classList.add(this.customClass + "-modal");
}
// this.modal.className = this.customClass + "-modal-background"; this.loading = document.createElement("div");
this.loading.className = this.customClass + "-loading";
this.classList.add(this.customClass + "-modal"); if (this.loadingText) this.loading.innerHTML = this.loadingText;
else {
var lc = document.createElement("div");
lc.className = this.customClass + "-loading-content";
this.loading.appendChild(lc);
}
} this.body.appendChild(this.loading);
if (this.draggable) {
this.addEventListener("mousedown", function (e) {
self._startDragging(e);
});
} else {
this.header.addEventListener("mousedown", function (e) {
self._startDragging(e);
});
}
this.loading = document.createElement("div"); document.addEventListener("mouseup", function () {
this.loading.className = this.customClass + "-loading"; self._stopDragging();
self._stopExpanding();
});
if (this.loadingText) document.addEventListener("mousemove", function (e) {
this.loading.innerHTML = this.loadingText; if (self._dragging) self._drag(e);
else else if (self._expanding) self._expand(e);
{ });
var lc = document.createElement("div");
lc.className = this.customClass + "-loading-content";
this.loading.appendChild(lc);
}
this.body.appendChild(this.loading); this.addEventListener("mousedown", function (e) {
if (self.style.cursor == "nwse-resize") self._startExpanding(e);
});
this.addEventListener("mousemove", function (e) {
if (self._dragging) return;
if (this.draggable) if (!self._expanding) {
{ var x =
this.addEventListener("mousedown", function(e){ (e.pageX ||
self._startDragging(e); e.clientX +
}); (document.documentElement.scrollLeft
} ? document.documentElement.scrollLeft
else : document.body.scrollLeft)) - self.offsetLeft;
{ var y =
this.header.addEventListener('mousedown', function (e) { (e.pageY ||
self._startDragging(e); e.clientY +
}); (document.documentElement.scrollTop
} ? document.documentElement.scrollTop
: document.body.scrollTop)) - self.offsetTop;
document.addEventListener('mouseup', function () { if (self.clientWidth - x < 5 && self.clientHeight - y < 5) {
self._stopDragging(); self.style.cursor = "nwse-resize";
self._stopExpanding(); } else {
}); self.style.cursor = "";
}
}
});
}
document.addEventListener('mousemove', function (e) { _startDragging(e) {
if (self._dragging) this._dragging = true;
self._drag(e);
else if (self._expanding)
self._expand(e);
});
this.addEventListener("mousedown", function(e){ this._dragX =
if (self.style.cursor == "nwse-resize") (e.pageX ||
self._startExpanding(e); e.clientX +
}); (document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft)) - this.offsetLeft;
this._dragY =
(e.pageY ||
e.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop)) - this.offsetTop;
this.addEventListener("mousemove", function(e) //corssbrowser mouse pointer values
{ document.onselectstart = function () {
if (self._dragging) return false;
return; };
}
if (!self._expanding) _drag(e) {
{ var x =
var x = (e.pageX || e.clientX + (document.documentElement.scrollLeft ? e.pageX ||
document.documentElement.scrollLeft : e.clientX +
document.body.scrollLeft)) - self.offsetLeft; (document.documentElement.scrollLeft
var y = (e.pageY || e.clientY + (document.documentElement.scrollTop ? ? document.documentElement.scrollLeft
document.documentElement.scrollTop : : document.body.scrollLeft);
document.body.scrollTop) ) - self.offsetTop; var y =
e.pageY ||
e.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop);
this.style.top = y - this._dragY + "px"; // (y - self.y) + "px";
this.style.left = x - this._dragX + "px"; //(x - self.x) + "px";
this._emit("move", { left: this.offsetLeft, top: this.offsetTop });
}
if (self.clientWidth - x < 5 && self.clientHeight - y < 5) _stopDragging() {
{ this._dragging = false;
self.style.cursor = "nwse-resize"; }
}
else
{
self.style.cursor = "";
}
}
});
} _startExpanding(e) {
document.onselectstart = function () {
return false;
};
this._expanding = true;
this._dragX =
(e.pageX ||
e.clientX +
(document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft)) - this.offsetLeft;
this._dragY =
(e.pageY ||
e.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop)) - this.offsetTop;
this._width = this.clientWidth;
this._height = this.clientHeight;
}
_startDragging(e) _expand(e) {
{ var x =
this._dragging = true; (e.pageX ||
e.clientX +
(document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft)) - this.offsetLeft;
var y =
(e.pageY ||
e.clientY +
(document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop)) - this.offsetTop;
this._dragX = (e.pageX || e.clientX + (document.documentElement.scrollLeft ? this.resize(
document.documentElement.scrollLeft : this._width + x - this._dragX,
document.body.scrollLeft)) - this.offsetLeft; this._height + y - this._dragY
this._dragY = (e.pageY || e.clientY + (document.documentElement.scrollTop ? );
document.documentElement.scrollTop : }
document.body.scrollTop) ) - this.offsetTop;
//corssbrowser mouse pointer values _stopExpanding() {
document.onselectstart = function() {return false}; this._expanding = false;
} this.style.cursor = "";
this._width = this.clientWidth;
this._height = this.clientHeight;
document.onselectstart = function () {
return true;
};
}
_drag(e) setLoading(visible) {
{ if (this.footer)
var x = e.pageX || e.clientX + (document.documentElement.scrollLeft ? for (var i = 0; i < this.footer.children.length; i++)
document.documentElement.scrollLeft : if (this.footer.children[i].nodeName == "BUTTON")
document.body.scrollLeft); this.footer.children[i].disabled = visible;
var y = e.pageY || e.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop);
this.style.top = (y - this._dragY ) + "px";// (y - self.y) + "px";
this.style.left = (x -this._dragX ) + "px";//(x - self.x) + "px";
this._emit("move", {left: this.offsetLeft, top: this.offsetTop});
}
_stopDragging() if (visible)
{ this.loading.classList.add(this.customClass + "-loading-visible");
this._dragging = false; else this.loading.classList.remove(this.customClass + "-loading-visible");
}
_startExpanding(e) return this;
{ }
document.onselectstart = function() {return false};
this._expanding = true;
this._dragX = (e.pageX || e.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft)) - this.offsetLeft;
this._dragY = (e.pageY || e.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop) ) - this.offsetTop;
this._width = this.clientWidth;
this._height = this.clientHeight;
}
_expand(e) center() {
{ this._updateSize();
var x = (e.pageX || e.clientX + (document.documentElement.scrollLeft ? return this.move(
document.documentElement.scrollLeft : window.pageXOffset + window.innerWidth / 2 - this.offsetWidth / 2,
document.body.scrollLeft)) - this.offsetLeft; window.pageYOffset + window.innerHeight / 2 - this.offsetHeight / 2
var y = (e.pageY || e.clientY + (document.documentElement.scrollTop ? );
document.documentElement.scrollTop : }
document.body.scrollTop)) - this.offsetTop;
setVisible(visible) {
if (visible == this.visible) return;
this.resize(this._width + x -this._dragX, this._height + y - this._dragY); this.visible = visible;
}
_stopExpanding() if (visible) {
{ this.classList.add(this.customClass + "-visible");
this._expanding = false;
this.style.cursor = "";
this._width = this.clientWidth;
this._height = this.clientHeight;
document.onselectstart = function() {return true};
}
setLoading(visible) if (this.background) {
{ this.background.setVisible(true);
if (this.footer) }
for(var i = 0; i < this.footer.children.length; i++) //else
if (this.footer.children[i].nodeName == "BUTTON") if (!this._shown) {
this.footer.children[i].disabled = visible; this._updateSize();
this._shown = true;
}
if (visible) this.setFocus(true);
this.loading.classList.add(this.customClass + "-loading-visible");
else
this.loading.classList.remove(this.customClass + "-loading-visible");
return this; this._updateSize();
} } else {
this._updateSize();
center() this.classList.remove(this.customClass + "-visible");
{ this.classList.remove(this.customClass + "-active");
this._updateSize();
return this.move(window.pageXOffset + (window.innerWidth / 2) - (this.offsetWidth / 2),
window.pageYOffset + (window.innerHeight / 2) - (this.offsetHeight / 2));
}
setVisible(visible) if (this.background) this.background.setVisible(false);
{
if (visible == this.visible) //this.modal.classList.remove(this.customClass + "-modal-background-visible");
return;
this.visible = visible; this.setFocus(false);
if (visible) var i = IUI._nav_list.indexOf(this);
{ if (i > -1) IUI._nav_list.splice(i, 1);
this.classList.add(this.customClass + "-visible");
if (this.background) /*
{
this.background.setVisible(true);
}
//else
if (!this._shown)
{
this._updateSize();
this._shown = true;
}
this.setFocus(true);
this._updateSize();
}
else
{
this._updateSize();
this.classList.remove(this.customClass + "-visible");
this.classList.remove(this.customClass + "-active");
if (this.background)
this.background.setVisible(false);
//this.modal.classList.remove(this.customClass + "-modal-background-visible");
this.setFocus(false);
var i = IUI._nav_list.indexOf(this);
if (i > -1)
IUI._nav_list.splice(i, 1);
/*
IUI._nav_list.pop IUI._nav_list.pop
if (IUI._previousWindow) if (IUI._previousWindow)
if (IUI._previousWindow.visible) if (IUI._previousWindow.visible)
@@ -276,33 +270,37 @@ export default IUI.module(class IUIDialog extends IUIWindow
else else
window.location.hash = ""; window.location.hash = "";
*/ */
} }
this._emit("visible", {visible}); this._emit("visible", { visible });
return this; return this;
} }
hide() hide() {
{ this.setVisible(false);
this.setVisible(false); return this;
return this; }
}
show() show() {
{ this.setVisible(true);
this.setVisible(true); return this;
return this; }
} }
}); );
document.addEventListener("keydown", function (e) { document.addEventListener("keydown", function (e) {
if ( e.keyCode === 27 ) { // ESC if (e.keyCode === 27) {
var dialogs = IUI.registry.filter(function(o){ return ( o instanceof IUIDialog); }).filter(function(x){return x.focus;}); // ESC
for(var i = 0; i < dialogs.length; i++) var dialogs = IUI.registry
dialogs[i].hide(); .filter(function (o) {
} return o instanceof IUIDialog;
}) })
.filter(function (x) {
return x.focus;
});
for (var i = 0; i < dialogs.length; i++) dialogs[i].hide();
}
});
//IUI.module("dialog", IUIDialog, function(el, modal, properties){ return new IUIDialog(el, modal, properties);}); //IUI.module("dialog", IUIDialog, function(el, modal, properties){ return new IUIDialog(el, modal, properties);});

View File

@@ -1,48 +1,45 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class DropDown extends IUIElement { export default IUI.module(
class DropDown extends IUIElement {
constructor() { constructor() {
super({"direction": "down" }); super({ direction: "down" });
var self = this; var self = this;
this._register("visible"); this._register("visible");
this.visible = false; this.visible = false;
// this.classList.add(this.cssClass + "-" + this.direction); // this.classList.add(this.cssClass + "-" + this.direction);
this.menu = this.getElementsByClassName(this.cssClass + "-menu")[0]; this.menu = this.getElementsByClassName(this.cssClass + "-menu")[0];
//this.arrow = document.createElement("div");
//this.arrow.className = this.customClass + "-arrow";
//this.arrow = document.createElement("div"); //this.el.appendChild(this.arrow);
//this.arrow.className = this.customClass + "-arrow";
if (this.getAttribute("fixed")) {
this._fixed = true;
document.body.appendChild(this.menu);
}
//this.el.appendChild(this.arrow); //this.el.appendChild(this.menu);
if (this.getAttribute("fixed")) this.addEventListener("click", function (e) {
{ var t = e.target;
this._fixed = true; do {
document.body.appendChild(this.menu); if (t == self.menu) return;
} } while ((t = t.parentElement));
//this.el.appendChild(this.menu); self.setVisible(!self.visible);
});
this.addEventListener("click", function (e) { IUI._menus.push(this);
var t = e.target
do {
if (t == self.menu)
return;
} while (t = t.parentElement)
self.setVisible(!self.visible); /*
});
IUI._menus.push(this);
/*
document.body.addEventListener("click", function(e) document.body.addEventListener("click", function(e)
{ {
if (!self.visible) if (!self.visible)
@@ -62,135 +59,128 @@ export default IUI.module(class DropDown extends IUIElement {
} }
set fixed(value) { set fixed(value) {
if (value) if (value) document.body.appendChild(this.menu);
document.body.appendChild(this.menu); this._fixed = value;
this._fixed = value;
} }
get fixed() { get fixed() {
return this._fixed; return this._fixed;
} }
hide() { hide() {
return this.setVisible(false); return this.setVisible(false);
} }
show() { show() {
return this.setVisible(true); return this.setVisible(true);
} }
getOffset() { getOffset() {
var el = this; var el = this;
var _x = 0; var _x = 0;
var _y = 0; var _y = 0;
while (!isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) { while (!isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft; _x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop; _y += el.offsetTop - el.scrollTop;
el = el.offsetParent; el = el.offsetParent;
} }
_x += window.pageXOffset; _x += window.pageXOffset;
_y += window.pageYOffset; _y += window.pageYOffset;
return { top: _y, left: _x, width: this.clientWidth, height: this.clientHeight }; return {
top: _y,
left: _x,
width: this.clientWidth,
height: this.clientHeight,
};
} }
set data(value) { set data(value) {
// console.log("DD", value); // console.log("DD", value);
super.data = value; super.data = value;
// console.log("VV", this._uiBindings, this._dataBindings); // console.log("VV", this._uiBindings, this._dataBindings);
} }
setVisible(visible) { setVisible(visible) {
this.visible = visible; this.visible = visible;
if (!this.fixed) { if (!this.fixed) {
if (visible) { if (visible) {
this.menu.classList.add(this.cssClass + "-menu-visible"); this.menu.classList.add(this.cssClass + "-menu-visible");
this.classList.add(this.cssClass + "-visible"); this.classList.add(this.cssClass + "-visible");
} } else {
else { this.menu.classList.remove(this.cssClass + "-menu-visible");
this.menu.classList.remove(this.cssClass + "-menu-visible"); this.classList.remove(this.cssClass + "-visible");
this.classList.remove(this.cssClass + "-visible");
}
} }
else { } else {
if (visible) { if (visible) {
var rect = this.getBoundingClientRect(); var rect = this.getBoundingClientRect();
var menuWidth = this.menu.clientWidth; var menuWidth = this.menu.clientWidth;
var menuHeight = this.menu.clientHeight; var menuHeight = this.menu.clientHeight;
if (menuWidth > document.body.clientWidth) { if (menuWidth > document.body.clientWidth) {
menuWidth = (document.body.clientWidth - 10); menuWidth = document.body.clientWidth - 10;
this.menu.style.width = menuWidth + "px"; this.menu.style.width = menuWidth + "px";
} }
var startX = rect.left + (rect.width / 2 - menuWidth / 2);
var startX = rect.left + (rect.width / 2 - menuWidth / 2); if (this.direction == "up") {
// var menuTop = rect.top - this.arrow.clientHeight - this.menu.clientHeight;
var menuTop = rect.top - this.menu.clientHeight;
if (menuTop < 0) {
menuTop = 5;
// this.menu.style.height = (rect.top - this.arrow.clientHeight ) + "px";
this.menu.style.height = rect.top + "px";
if (this.direction == "up") { this.menu.classList.add(this.cssClass + "-menu-oversized");
// var menuTop = rect.top - this.arrow.clientHeight - this.menu.clientHeight; } else
var menuTop = rect.top - this.menu.clientHeight; this.menu.classList.remove(this.cssClass + "-menu-oversized");
if (menuTop < 0) { //this.arrow.classList.remove(this.customClass + "-arrow-down");
menuTop = 5; //this.arrow.classList.add(this.customClass + "-arrow-up");
// this.menu.style.height = (rect.top - this.arrow.clientHeight ) + "px"; //this.arrow.style.top = ( rect.top - this.arrow.clientHeight ) + "px";
this.menu.style.height = (rect.top) + "px"; this.menu.style.top = menuTop + "px";
} else {
//var menuTop = rect.top + rect.height + this.arrow.clientHeight;
var menuTop = rect.top + rect.height;
this.menu.classList.add(this.cssClass + "-menu-oversized"); //this.arrow.classList.remove(this.customClass + "-arrow-up");
} //this.arrow.classList.add(this.customClass + "-arrow-down");
else //this.arrow.style.top = ( rect.top + rect.height ) + "px";
this.menu.classList.remove(this.cssClass + "-menu-oversized");
this.menu.style.top = menuTop + "px";
//this.arrow.classList.remove(this.customClass + "-arrow-down"); if (menuTop + menuHeight > document.body.clientHeight) {
//this.arrow.classList.add(this.customClass + "-arrow-up"); this.menu.style.height =
//this.arrow.style.top = ( rect.top - this.arrow.clientHeight ) + "px"; document.body.clientHeight - menuTop + "px";
this.menu.style.top = (menuTop) + "px"; this.menu.classList.add(this.cssClass + "-menu-oversized");
} } else {
else { this.menu.classList.remove(this.cssClass + "-menu-oversized");
//var menuTop = rect.top + rect.height + this.arrow.clientHeight;
var menuTop = rect.top + rect.height;
//this.arrow.classList.remove(this.customClass + "-arrow-up");
//this.arrow.classList.add(this.customClass + "-arrow-down");
//this.arrow.style.top = ( rect.top + rect.height ) + "px";
this.menu.style.top = menuTop + "px";
if (menuTop + menuHeight > document.body.clientHeight) {
this.menu.style.height = (document.body.clientHeight - menuTop) + "px";
this.menu.classList.add(this.cssClass + "-menu-oversized");
}
else {
this.menu.classList.remove(this.cssClass + "-menu-oversized");
}
}
if (startX < 0)
startX = 5;
else if (startX + menuWidth > document.body.clientWidth)
startX = document.body.clientWidth - menuWidth - 5;
//this.arrow.style.left = (rect.left + (rect.width/2 - this.arrow.clientWidth/2)) + "px";
this.menu.style.left = startX + "px";
//this.arrow.classList.add(this.customClass + "-arrow-visible");
this.menu.classList.add(this.cssClass + "-menu-visible");
this.classList.add(this.cssClass + "-visible");
}
else {
//this.arrow.classList.remove(this.customClass + "-arrow-visible");
this.menu.classList.remove(this.cssClass + "-menu-visible");
this.classList.remove(this.cssClass + "-visible");
} }
}
if (startX < 0) startX = 5;
else if (startX + menuWidth > document.body.clientWidth)
startX = document.body.clientWidth - menuWidth - 5;
//this.arrow.style.left = (rect.left + (rect.width/2 - this.arrow.clientWidth/2)) + "px";
this.menu.style.left = startX + "px";
//this.arrow.classList.add(this.customClass + "-arrow-visible");
this.menu.classList.add(this.cssClass + "-menu-visible");
this.classList.add(this.cssClass + "-visible");
} else {
//this.arrow.classList.remove(this.customClass + "-arrow-visible");
this.menu.classList.remove(this.cssClass + "-menu-visible");
this.classList.remove(this.cssClass + "-visible");
} }
}
this._emit("visible", { visible}); this._emit("visible", { visible });
return this;
return this;
} }
}); }
);

View File

@@ -3,46 +3,45 @@ import { IUI } from "../Core/IUI.js";
import Tabs from "./Tabs.js"; import Tabs from "./Tabs.js";
import Tab from "./Tab.js"; import Tab from "./Tab.js";
export default IUI.module(class Form extends IUIElement { export default IUI.module(
class Form extends IUIElement {
constructor() { constructor() {
super(); super();
} }
create() { create() {
this._container = document.createElement("div");
this._container.className = "container";
this._container = document.createElement("div"); this._actions = document.createElement("div");
this._container.className = "container"; this._actions.className = "actions";
this._actions = document.createElement("div"); this._save = document.createElement("button");
this._actions.className = "actions"; this._save.className = "button";
this._save.innerHTML = this.hasAttribute("save")
? this.getAttribute("save")
: "Save";
this._cancel = document.createElement("button");
this._cancel.className = "button";
this._cancel = this.hasAttribute("cancel")
? this.getAttribute("cancel")
: "Cancel";
this._save.addEventListener("click", x => {});
this._save = document.createElement("button"); this._cancel.addEventListener("click", x => {
this._save.className = "button"; window.router.back();
this._save.innerHTML = this.hasAttribute("save") ? this.getAttribute("save") : "Save"; });
this._cancel = document.createElement("button");
this._cancel.className = "button";
this._cancel = this.hasAttribute("cancel") ? this.getAttribute("cancel") : "Cancel";
this._save.addEventListener("click", (x) => { this._actions.appendChild(this._save);
this._actions.appendChild(this._cancel);
});
this._cancel.addEventListener("click", (x) => {
window.router.back();
});
this._actions.appendChild(this._save);
this._actions.appendChild(this._cancel);
this.appendChild(this._container);
this.appendChild(this._actions);
this.appendChild(this._container);
this.appendChild(this._actions);
} }
set layout(value) { set layout(value) {
/* /*
mode:tabs, mode:tabs,
tabs: [ tabs: [
@@ -52,50 +51,48 @@ export default IUI.module(class Form extends IUIElement {
]} ]}
] ]
*/ */
// render layout // render layout
if (value.mode == "tabs") { if (value.mode == "tabs") {
for (var i = 0; i < this.layout.tabs.length; i++) { for (var i = 0; i < this.layout.tabs.length; i++) {
// render tab // render tab
this.mode = "tabs"; this.mode = "tabs";
this._tabs = new Tabs(); this._tabs = new Tabs();
var tab = new Tab(); var tab = new Tab();
this._tabs.add(tab); this._tabs.add(tab);
for (var j = 0; j < this._tabs.length; j++) { for (var j = 0; j < this._tabs.length; j++) {}
this.layout.tasbs[i].content;
}
this.layout.tasbs[i].content
}
} }
}
} }
set data(value) { set data(value) {
var self = this; var self = this;
if (value == null) if (value == null) this._input.value = "";
this._input.value = ""; else {
else { this._input.value = value[this._field];
this._input.value = value[this._field];
if (value.on) if (value.on)
value.on("modified", (propertyName, value) => { value.on("modified", (propertyName, value) => {
if (propertyName == self._field) if (propertyName == self._field)
self._input.value = value[self._field]; self._input.value = value[self._field];
}); });
} }
//super.data = data; //super.data = data;
} }
get layout() { get layout() {
return this._input.value; return this._input.value;
} }
set layout(value) { set layout(value) {
// load layout // load layout
for (var i = 0; i < value.length; i++) { for (var i = 0; i < value.length; i++) {
// [{tab: },{}] // [{tab: },{}]
} }
this._input.value = value; this._input.value = value;
} }
}); }
);

View File

@@ -1,204 +1,205 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Grid extends IUIElement { export default IUI.module(
constructor() class Grid extends IUIElement {
{ constructor() {
super({index: "iid", super({
layout: {content: {field: "name", formatter: null}, index: "iid",
title: {field: "content", formatter: null}, layout: {
footer: {field: "footer", formatter: null}}}); content: { field: "name", formatter: null },
title: { field: "content", formatter: null },
footer: { field: "footer", formatter: null },
},
});
this._register("add"); this._register("add");
this._register("layout"); this._register("layout");
this._register("contextmenu"); this._register("contextmenu");
this.windows = []; this.windows = [];
} }
create() { create() {
for (var i = 0; i < this.children.length; i++) for (var i = 0; i < this.children.length; i++) this.add(this.children[i]);
this.add(this.children[i]);
} }
setGridLayout(style) setGridLayout(style) {
{ this.style.grid = style;
this.style.grid = style; this._emit("layout", style, this);
this._emit("layout", style, this); return this;
return this; }
}
add(win) { add(win) {
let self = this; let self = this;
win.setAttribute("draggable", true); win.setAttribute("draggable", true);
win.addEventListener("dragstart", function (e) { win.addEventListener("dragstart", function (e) {
e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.effectAllowed = "move";
self._dragItem = this; self._dragItem = this;
this.classList.add(self.cssClass + '-window-drag'); this.classList.add(self.cssClass + "-window-drag");
});
}); win.addEventListener("dragover", function (e) {
if (self._dragItem) {
e.preventDefault();
this.classList.add(self.cssClass + "-window-over");
e.dataTransfer.dropEffect = "move"; // See the section on the DataTransfer object.
}
});
win.addEventListener("dragover", function (e) { win.addEventListener("dragleave", function (e) {
if (self._dragItem) { if (e.preventDefault) e.preventDefault();
e.preventDefault();
this.classList.add(self.cssClass + '-window-over');
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
}
});
win.addEventListener("dragleave", function (e) { this.classList.remove(self.cssClass + "-window-over");
});
if (e.preventDefault) win.addEventListener("dragend", function (e) {
e.preventDefault(); this.classList.remove(self.cssClass + "-window-drag");
self._dragItem = null;
});
this.classList.remove(self.cssClass + "-window-over"); win.addEventListener("drop", function (e) {
}); self._dragItem.classList.remove(self.cssClass + "-window-drag");
e.currentTarget.classList.remove(self.cssClass + "-window-over");
win.addEventListener("dragend", function (e) { for (var i = 0; i < self.children.length; i++)
this.classList.remove(self.cssClass + '-window-drag'); if (self.children[i] == self._dragItem) {
self._dragItem = null; self.insertBefore(self._dragItem, e.currentTarget.nextSibling);
}); break;
} else if (self.children[i] == e.currentTarget) {
self.insertBefore(self._dragItem, e.currentTarget);
break;
}
win.addEventListener("drop", function (e) { self._dragItem = null;
self._dragItem.classList.remove(self.cssClass + "-window-drag"); });
e.currentTarget.classList.remove(self.cssClass + "-window-over");
for (var i = 0; i < self.children.length; i++) win.addEventListener("contextmenu", function (e) {
if (self.children[i] == self._dragItem) { self.selected = win;
self.insertBefore(self._dragItem, e.currentTarget.nextSibling); self._emit("contextmenu", { win });
break; });
}
else if (self.children[i] == e.currentTarget) {
self.insertBefore(self._dragItem, e.currentTarget);
break;
}
self._dragItem = null; win.on("close", function () {
}); self.remove(win);
});
win.addEventListener("contextmenu", function (e) {
self.selected = win;
self._emit("contextmenu", { win });
});
win.on("close", function () {
self.remove(win);
});
} }
addOld(item) addOld(item) {
{ var self = this;
var self = this; var li = item; //document.createElement("li");
//li.setAttribute("data-id", item[this.index]);
var li = item;//document.createElement("li"); li.setAttribute("draggable", true);
//li.setAttribute("data-id", item[this.index]);
li.setAttribute("draggable", true); li.addEventListener("dragstart", function (e) {
e.dataTransfer.effectAllowed = "move";
self._dragItem = this;
li.addEventListener("dragstart", function(e){ this.classList.add(self.cssClass + "-window-drag");
e.dataTransfer.effectAllowed = 'move'; });
self._dragItem = this;
this.classList.add(self.cssClass + '-window-drag'); li.addEventListener("dragover", function (e) {
if (self._dragItem) {
e.preventDefault();
this.classList.add(self.cssClass + "-window-over");
e.dataTransfer.dropEffect = "move"; // See the section on the DataTransfer object.
}
});
}); li.addEventListener("dragleave", function (e) {
if (e.preventDefault) e.preventDefault();
li.addEventListener("dragover", function(e){ this.classList.remove(self.cssClass + "-window-over");
if (self._dragItem) });
{
e.preventDefault();
this.classList.add(self.cssClass + '-window-over');
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
}
});
li.addEventListener("dragleave", function(e){ li.addEventListener("dragend", function (e) {
this.classList.remove(self.cssClass + "-window-drag");
self._dragItem = null;
});
if (e.preventDefault) li.addEventListener("drop", function (e) {
e.preventDefault(); self._dragItem.classList.remove(self.cssClass + "-window-drag");
e.currentTarget.classList.remove(self.cssClass + "-window-over");
this.classList.remove(self.cssClass + "-window-over"); for (var i = 0; i < self.children.length; i++)
}); if (self.children[i] == self._dragItem) {
self.insertBefore(self._dragItem, e.currentTarget.nextSibling);
break;
} else if (self.children[i] == e.currentTarget) {
self.insertBefore(self._dragItem, e.currentTarget);
break;
}
li.addEventListener("dragend", function(e){ self._dragItem = null;
this.classList.remove(self.cssClass + '-window-drag'); });
self._dragItem = null;
});
li.addEventListener("drop", function(e){ li.addEventListener("contextmenu", function (e) {
self._dragItem.classList.remove(self.cssClass + "-window-drag"); self.selected = win;
e.currentTarget.classList.remove(self.cssClass + "-window-over"); self._emit("contextmenu", item, win, this, e);
});
for(var i = 0; i < self.children.length; i++) var win = iui(li).window({
if (self.children[i] == self._dragItem) draggable: false,
{ title: this.layout.title.formatter
self.insertBefore(self._dragItem, e.currentTarget.nextSibling); ? this.layout.title.formatter(item[this.layout.title.field], item)
break; : item[this.layout.title.field],
} });
else if (self.children[i] == e.currentTarget)
{
self.insertBefore(self._dragItem, e.currentTarget);
break;
}
self._dragItem = null; var body = this.layout.content.formatter
}); ? this.layout.content.formatter(
item[this.layout.content.field],
item,
win,
this
)
: item[this.layout.content.field];
if (body instanceof HTMLElement) win.body.appendChild(body);
else win.body.innerHTML = body;
li.addEventListener("contextmenu", function(e){ var footer = this.layout.footer.formatter
self.selected = win; ? this.layout.footer.formatter(
self._emit("contextmenu", item, win, this, e); item[this.layout.footer.field],
}); item,
win,
this
)
: item[this.layout.footer.field];
if (footer != null) {
var fe = document.createElement("div");
fe.className = "window-footer";
var win = iui(li).window({draggable: false, title: this.layout.title.formatter ? this.layout.title.formatter(item[this.layout.title.field], item) : item[this.layout.title.field]}); if (footer instanceof HTMLElement) fe.appendChild(footer);
else fe.innerHTML = footer;
var body = this.layout.content.formatter ? this.layout.content.formatter(item[this.layout.content.field], item, win, this) : item[this.layout.content.field]; win.appendChild(fe);
if (body instanceof HTMLElement) }
win.body.appendChild(body);
else
win.body.innerHTML = body;
var footer = this.layout.footer.formatter ? this.layout.footer.formatter(item[this.layout.footer.field], item, win, this) : item[this.layout.footer.field]; win.on("close", function () {
if (footer != null) self.remove(win);
{ });
var fe = document.createElement("div");
fe.className = "window-footer";
if (footer instanceof HTMLElement) this.appendChild(li);
fe.appendChild(footer);
else
fe.innerHTML = footer;
win.appendChild(fe); win.control = item;
}
win.on("close", function(){ this.windows.push(win);
self.remove(win);
});
this.appendChild(li); this._emit("add", item, win, this);
win.control = item; return this;
//win._updateSize();
}
this.windows.push(win); remove(win) {
win.destroy();
this.removeChild(win);
}
this._emit("add", item, win, this); clear() {
while (this.children.length > 0) this.removeChild(this.children[0]);
return this; }
//win._updateSize(); }
} );
remove(win)
{
win.destroy();
this.removeChild(win);
}
clear()
{
while (this.children.length > 0)
this.removeChild(this.children[0]);
}
});

View File

@@ -1,163 +1,159 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Input extends IUIElement { export default IUI.module(
class Input extends IUIElement {
constructor() { constructor() {
super({ formatter: (x) => x }); super({ formatter: x => x });
this._register("input"); this._register("input");
this._register("change"); this._register("change");
} }
_checkValidity() { _checkValidity() {
if (this.validate != null) { if (this.validate != null) {
try { try {
let valid = this.validate.apply(this); let valid = this.validate.apply(this);
if (!valid) { if (!valid) {
this.setAttribute("invalid", ""); this.setAttribute("invalid", "");
this.classList.add(this.cssClass + "-invalid"); this.classList.add(this.cssClass + "-invalid");
return false; return false;
} } else {
else { this.removeAttribute("invalid");
this.removeAttribute("invalid"); this.classList.remove(this.cssClass + "-invalid");
this.classList.remove(this.cssClass + "-invalid"); return true;
return true; }
} } catch (e) {
} console.log("Validation Error", e);
catch (e) { return false;
console.log("Validation Error", e);
return false;
}
} }
}
return true; return true;
} }
get caption(){ get caption() {
return this.getAttribute("caption");// this._span.innerHTML; return this.getAttribute("caption"); // this._span.innerHTML;
} }
set caption(value){ set caption(value) {
this.setAttribute("caption", value); this.setAttribute("caption", value);
this._span.innerHTML = value; this._span.innerHTML = value;
} }
create() { create() {
this.isAuto = this.hasAttribute("auto");
this.field = this.getAttribute("field");
this.isAuto = this.hasAttribute("auto"); if (this.field != null) {
this.field = this.getAttribute("field"); this.setAttribute(":data", `d['${this.field}']`);
this.setAttribute(
"async:revert",
`d['${this.field}'] = await this.getData()`
);
}
this._span = document.createElement("span");
this._span.innerHTML = this.getAttribute("caption");
if (this.field != null) this._input = document.createElement("input");
{ this._input.placeholder = " ";
this.setAttribute(":data", `d['${this.field}']`)
this.setAttribute("async:revert", `d['${this.field}'] = await this.getData()`);
}
this._span = document.createElement("span"); let self = this;
this._span.innerHTML = this.getAttribute("caption");
this._input = document.createElement("input"); this._input.addEventListener("input", () => {
this._input.placeholder = " "; if (self._checkValidity() && self.isAuto) this.revert();
//self.data[self.field] = self.value;
});
let self = this; this._input.addEventListener("change", () => {
self._emit("change", { value: self.value });
});
this._input.addEventListener("input", () => { this.type = this.hasAttribute("type")
if (self._checkValidity() && self.isAuto) ? this.getAttribute("type").toLowerCase()
this.revert(); : "text";
//self.data[self.field] = self.value;
this.accept = this.getAttribute("accept");
this.appendChild(this._input);
this.appendChild(this._span);
if (this.type == "password") {
this._eye = document.createElement("div");
this._eye.className = this.cssClass + "-eye";
this._eye.addEventListener("mousedown", () => {
self._input.type = "text";
self._eye.classList.add(self.cssClass + "-eye-active");
});
this._eye.addEventListener("mouseup", () => {
self._input.type = "password";
self._eye.classList.remove(self.cssClass + "-eye-active");
}); });
this._input.addEventListener("change", () => { this.appendChild(this._eye);
self._emit("change", { value: self.value }); }
});
this.type = this.hasAttribute("type") ? this.getAttribute("type").toLowerCase() : "text";
this.accept = this.getAttribute("accept");
this.appendChild(this._input);
this.appendChild(this._span);
if (this.type == "password")
{
this._eye = document.createElement("div");
this._eye.className = this.cssClass + "-eye";
this._eye.addEventListener("mousedown", ()=>{
self._input.type = "text";
self._eye.classList.add(self.cssClass + "-eye-active");
});
this._eye.addEventListener("mouseup", ()=>{
self._input.type = "password";
self._eye.classList.remove(self.cssClass + "-eye-active");
});
this.appendChild(this._eye);
}
} }
async updateAttributes(deep, parentData) { async updateAttributes(deep, parentData) {
await super.updateAttributes(deep, parentData); await super.updateAttributes(deep, parentData);
//this._input.type = this.type; //this._input.type = this.type;
//this._input.value = this.value; //this._input.value = this.value;
} }
set type(value) { set type(value) {
this._input.type = value; this._input.type = value;
} }
get type() { get type() {
return this._input.type; return this._input.type;
} }
set accept(value){ set accept(value) {
this._input.accept = value; this._input.accept = value;
} }
get accept() { get accept() {
return this._input.accept; return this._input.accept;
} }
set disabled(value) { set disabled(value) {
if (value) if (value) this.setAttribute("disabled", "disabled");
this.setAttribute("disabled", "disabled"); else this.removeAttribute("disabled");
else
this.removeAttribute("disabled");
this._input.disabled = value; this._input.disabled = value;
} }
get disabled() { get disabled() {
return this._input.disabled; return this._input.disabled;
} }
set enabled(value) { set enabled(value) {
this.disabled = !value; this.disabled = !value;
} }
get enabled() { get enabled() {
return !this._input.disabled; return !this._input.disabled;
} }
async setData(value) { async setData(value) {
await super.setData(value);
await super.setData(value); if (this.type == "checkbox") this._input.checked = value;
else if (this.type == "date")
this._input.value =
value != null ? value.toISOString().slice(0, 10) : value;
else if (
this.type == null ||
this.type == "text" ||
this.type == "search" ||
this.type == "password"
)
this._input.value = value == null ? "" : value;
else this._input.value = value;
if (this.type == "checkbox") if (this._checkValidity() && this.isAuto) this.revert();
this._input.checked = value;
else if (this.type == "date")
this._input.value = value != null ? value.toISOString().slice(0, 10) : value;
else if (this.type == null || this.type == "text" || this.type == "search" || this.type == "password")
this._input.value = value == null ? '' : value;
else
this._input.value = value;
if (this._checkValidity() && this.isAuto) /*
this.revert();
/*
await super.setData(value); await super.setData(value);
if (value != null && this.field != null) if (value != null && this.field != null)
this.value = value[this.field]; this.value = value[this.field];
@@ -166,40 +162,30 @@ export default IUI.module(class Input extends IUIElement {
*/ */
} }
// modified(name, value) { // modified(name, value) {
// if (name == this.field) { // if (name == this.field) {
// this.value = value; // this.value = value;
// } // }
// } // }
async getData(){ async getData() {
if (this.type == "checkbox") if (this.type == "checkbox") return this._input.checked;
return this._input.checked; else if (this.type == "date") return new Date(this._input.value);
else if (this.type == "date") else if (this.type == "file")
return new Date(this._input.value); return new Uint8Array(await this._input.files[0].arrayBuffer());
else if (this.type == "file") else return this._input.value;
return new Uint8Array(await this._input.files[0].arrayBuffer());
else
return this._input.value;
} }
get data() get data() {
{ if (this.type == "checkbox") return this._input.checked;
if (this.type == "checkbox") else if (this.type == "date") return new Date(this._input.value);
return this._input.checked; else if (this.type == "file") {
else if (this.type == "date") return new Promise(resolve => {
return new Date(this._input.value); this._input.files[0].arrayBuffer().then(x => {
else if (this.type == "file") resolve(new Uint8Array(x));
{ });
return new Promise((resolve)=>{ });
this._input.files[0].arrayBuffer().then((x)=>{ } else return this._input.value;
resolve(new Uint8Array(x));
});
});
}
else
return this._input.value;
} }
/* /*
@@ -230,4 +216,5 @@ export default IUI.module(class Input extends IUIElement {
// this._checkValidity(); // this._checkValidity();
// } // }
}); }
);

View File

@@ -1,39 +1,37 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Link from '../Router/Link.js'; import Link from "../Router/Link.js";
export default IUI.module(class Location extends IUIElement { export default IUI.module(
class Location extends IUIElement {
constructor() { constructor() {
super(); super();
} }
create() { create() {
let self = this; let self = this;
window.router.on("route", (e) => { window.router.on("route", e => {
self.textContent = ""; // clear everything
self.textContent = ''; // clear everything let html = "";
let route = e.route;
var current = document.createElement("div");
current.innerHTML = route.caption;
let html = ""; self.append(current);
let route = e.route;
var current = document.createElement("div"); while ((route = route.parent)) {
current.innerHTML = route.caption; var sep = document.createElement("span");
self.prepend(sep);
self.append(current); let link = new Link();
link.link = route.link;
link.innerHTML = route.caption;
while (route = route.parent) { self.prepend(link);
}
var sep = document.createElement("span"); });
self.prepend(sep);
let link = new Link();
link.link = route.link;
link.innerHTML = route.caption;
self.prepend(link);
}
});
} }
}); }
);

View File

@@ -1,14 +1,12 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Login extends IUIElement export default IUI.module(
{ class Login extends IUIElement {
constructor() constructor() {
{ super();
super();
var template = `<div class='body' style='box-shadow: 0 2px 2px rgba(0, 0, 0, .3);
var template = `<div class='body' style='box-shadow: 0 2px 2px rgba(0, 0, 0, .3);
background: white; background: white;
border-radius: 3px; border-radius: 3px;
display: flex; display: flex;
@@ -42,138 +40,128 @@ export default IUI.module(class Login extends IUIElement
</div> </div>
</div>`; </div>`;
this.innerHTML = template; this.innerHTML = template;
this._message = this.querySelector("div[name='message']");
this._usernameText = this.querySelector("span[name='spnUsername']");
this._passwordText = this.querySelector("span[name='spnPassword']");
this._rememberText = this.querySelector("label[name='labelRemember']");
this._username = this.querySelector("input[name='txtUsername']");
this._password = this.querySelector("input[name='txtPassword']");
this._remember = this.querySelector("input[name='remember']");
this._login = this.querySelector("button[name='login']");
this._message = this.querySelector("div[name='message']"); var self = this;
this._usernameText = this.querySelector("span[name='spnUsername']"); this._password.addEventListener("keydown", e => {
this._passwordText = this.querySelector("span[name='spnPassword']"); if (e.keyCode == 13) self.login();
this._rememberText = this.querySelector("label[name='labelRemember']"); });
this._username = this.querySelector("input[name='txtUsername']");
this._password = this.querySelector("input[name='txtPassword']");
this._remember = this.querySelector("input[name='remember']");
this._login = this.querySelector("button[name='login']");
var self = this; if (this.hasAttribute("message")) {
this._message.innerHTML = this.getAttribute("message");
}
this._password.addEventListener("keydown", (e) => { if (e.keyCode == 13) self.login(); }); if (this.hasAttribute("username")) {
this._usernameText.innerHTML = this.getAttribute("username");
}
if (this.hasAttribute("message")) { if (this.hasAttribute("password")) {
this._message.innerHTML = this.getAttribute("message"); this._passwordText.innerHTML = this.getAttribute("password");
} }
if (this.hasAttribute("username")) { if (this.hasAttribute("remember")) {
this._usernameText.innerHTML = this.getAttribute("username"); this._rememberText.innerHTML = this.getAttribute("remember");
} }
if (this.hasAttribute("password")) { if (this.hasAttribute("login")) {
this._passwordText.innerHTML = this.getAttribute("password"); this._login.innerHTML = this.getAttribute("login");
} }
if (this.hasAttribute("remember")) { let username = this.username; // window.localStorage.getItem("iui.login.username");
this._rememberText.innerHTML = this.getAttribute("remember"); let password = this.password; // window.localStorage.getItem("iui.login.password");
} if (username != "") {
this._username.value = username;
this._password.value = password;
this._remember.checked = true;
}
if (this.hasAttribute("login")) { this._login.addEventListener("click", () => this.login());
this._login.innerHTML = this.getAttribute("login");
}
let username = this.username;// window.localStorage.getItem("iui.login.username");
let password = this.password;// window.localStorage.getItem("iui.login.password");
if (username != "") {
this._username.value = username;
this._password.value = password;
this._remember.checked = true;
}
this._login.addEventListener("click", ()=>this.login());
this._register("login");
this._register("logout");
this._register("login");
this._register("logout");
} }
login() { login() {
let username = this._username.value; let username = this._username.value;
let password = this._password.value; let password = this._password.value;
if (username == "" || password == "") if (username == "" || password == "") return;
return;
if (this._remember.checked) { if (this._remember.checked) {
this.username = username; this.username = username;
this.password = password; this.password = password;
//window.localStorage.setItem("iui.login.username", username); //window.localStorage.setItem("iui.login.username", username);
//window.localStorage.setItem("iui.login.password", password); //window.localStorage.setItem("iui.login.password", password);
} } else {
else { window.localStorage.removeItem("iui.login.username");
window.localStorage.removeItem("iui.login.username"); window.localStorage.removeItem("iui.login.password");
window.localStorage.removeItem("iui.login.password"); }
}
this._emit("login", { username, password }); this._emit("login", { username, password });
} }
get username() { get username() {
return window.localStorage.getItem("iui.login.username"); return window.localStorage.getItem("iui.login.username");
} }
set username(value) { set username(value) {
return window.localStorage.setItem("iui.login.username", value); return window.localStorage.setItem("iui.login.username", value);
} }
get password() { get password() {
return window.localStorage.getItem("iui.login.password"); return window.localStorage.getItem("iui.login.password");
} }
set password(value) { set password(value) {
return window.localStorage.setItem("iui.login.password", value); return window.localStorage.setItem("iui.login.password", value);
} }
get token() { get token() {
return window.localStorage.getItem("iui.login.token"); return window.localStorage.getItem("iui.login.token");
} }
set token(value) { set token(value) {
return window.localStorage.setItem("iui.login.token", value); return window.localStorage.setItem("iui.login.token", value);
} }
get message() { get message() {
return this._message.innerHTML; return this._message.innerHTML;
} }
set message(value) { set message(value) {
this._message.innerHTML = value; this._message.innerHTML = value;
} }
logout() { logout() {
window.localStorage.removeItem("iui.login.username"); window.localStorage.removeItem("iui.login.username");
window.localStorage.removeItem("iui.login.password"); window.localStorage.removeItem("iui.login.password");
window.localStorage.removeItem("iui.login.token"); window.localStorage.removeItem("iui.login.token");
this._username.value = ""; this._username.value = "";
this._password.value = ""; this._password.value = "";
this._remember.checked = false; this._remember.checked = false;
this._emit("logout"); this._emit("logout");
} }
created() created() {
{ //if (this.hasAttribute("auto")) {
// let username = this.username;// window.localStorage.getItem("iui.login.username");
//if (this.hasAttribute("auto")) { // let password = this.password;// window.localStorage.getItem("iui.login.password");
// if (this.username != "") {
// let username = this.username;// window.localStorage.getItem("iui.login.username"); // this._emit("login", { username, password });
// let password = this.password;// window.localStorage.getItem("iui.login.password"); // }
// if (this.username != "") { //}
// this._emit("login", { username, password });
// }
//}
} }
}); }
);

View File

@@ -1,196 +1,176 @@
import { IUI } from '../Core/IUI.js'; import { IUI } from "../Core/IUI.js";
import IUIElement from '../Core/IUIElement.js'; import IUIElement from "../Core/IUIElement.js";
import Background from './Background.js'; import Background from "./Background.js";
import DropDown from './DropDown.js'; import DropDown from "./DropDown.js";
export default class Menu extends IUIElement { export default class Menu extends IUIElement {
constructor(props) { constructor(props) {
super(IUI.extend(props, { super(
index: "iid", IUI.extend(props, {
layout: { field: "name", formatter: null }, index: "iid",
visible: false, layout: { field: "name", formatter: null },
static: false, visible: false,
"target-class": "selected" static: false,
})); "target-class": "selected",
})
);
this._register("visible"); this._register("visible");
this._register("select"); this._register("select");
IUI._menus.push(this); IUI._menus.push(this);
}
// clear() {
// this.innerHTML = "";
// this._uiBindings = null;
// }
hide() {
return this.setVisible(false);
}
//show(x, y, element) {
// return this.setVisible(true, x, y, element);
//}
show(event) {
event.preventDefault();
let el = event.currentTarget;
let x = event.pageX;
let y = event.pageY;
this.setVisible(true, x, y, el);
}
async showModal(element) {
//super.data = this._getElementData(element);
await super.setData(element.data);
if (!this.background) {
this.background = document.getElementById("iui_app_background");
if (!this.background) {
this.background = new Background(); // document.createElement("div");
this.background.id = "iui_app_background";
document.body.insertAdjacentElement("afterBegin", this.background);
}
} }
this.background.show();
this.classList.add(this.cssClass + "-modal");
this.classList.add(this.cssClass + "-visible");
var width = window.innerWidth * 0.8;
this.style.width = width + "px";
// clear() { this.style.top =
// this.innerHTML = ""; window.pageYOffset +
// this._uiBindings = null; window.innerHeight / 2 -
// } this.offsetHeight / 2 +
"px"; // (document.body.clientHeight / 2 - this.clientHeight / 2) + "px";
this.style.left =
window.pageXOffset + window.innerWidth / 2 - this.offsetWidth / 2 + "px"; //(document.body.clientWidth / 2 - width / 2) + "px";
hide() { this.visible = true;
return this.setVisible(false); this._emit("visible", { visible: true });
return this;
}
async setVisible(visible, x, y, element) {
this.visible = visible;
if (this.target) {
if (this["target-class"] != null && this["target-class"] != "")
this.target.classList.remove(this["target-class"]);
this.target = null;
} }
//show(x, y, element) { if (visible) {
// return this.setVisible(true, x, y, element); //if (element)
//} //let dt = super._getElementData(element);
if (element) {
//[super.data, this.target] = dt;
show(event) { await this.setData(element.data);
event.preventDefault(); this.target = element;
let el = event.currentTarget; if (this["target-class"] != null && this["target-class"] != "")
let x = event.pageX; this.target.classList.add(this["target-class"]);
let y = event.pageY; }
this.setVisible(true, x, y, el); this._pass = true;
if (IUI.responsive && !this.static) return this.showModal();
this.classList.remove(this.cssClass + "-modal");
var rect = this.getBoundingClientRect();
if (y != null) {
if (y + rect.height > document.documentElement.clientHeight)
this.style.top =
document.documentElement.clientHeight - rect.height + "px";
else this.style.top = y + "px";
}
this.classList.add(this.cssClass + "-visible");
if (x != null) {
if (x + rect.width > document.body.scrollWidth)
this.style.left = document.body.scrollWidth - rect.width + "px";
//else if (x < 0)
// this.style.left = "0px";
else this.style.left = x + "px";
}
} else {
this.classList.remove(this.cssClass + "-visible");
if (this.background) this.background.hide();
//await super.setData({});// = {};
} }
this._emit("visible", { visible });
async showModal(element) { return this;
}
}
//super.data = this._getElementData(element);
await super.setData(element.data);
if (!this.background) {
this.background = document.getElementById("iui_app_background");
if (!this.background) {
this.background = new Background();// document.createElement("div");
this.background.id = "iui_app_background";
document.body.insertAdjacentElement("afterBegin", this.background);
}
}
this.background.show();
this.classList.add(this.cssClass + "-modal");
this.classList.add(this.cssClass + "-visible");
var width = (window.innerWidth * 0.8);
this.style.width = width + "px";
this.style.top = (window.pageYOffset + window.innerHeight / 2 - this.offsetHeight / 2) + "px"; // (document.body.clientHeight / 2 - this.clientHeight / 2) + "px";
this.style.left = (window.pageXOffset + window.innerWidth / 2 - this.offsetWidth / 2) + "px"; //(document.body.clientWidth / 2 - width / 2) + "px";
this.visible = true;
this._emit("visible", { visible: true });
return this;
}
async setVisible(visible, x, y, element) {
this.visible = visible;
if (this.target) {
if (this["target-class"] != null && this["target-class"] != "")
this.target.classList.remove(this["target-class"]);
this.target = null;
}
if (visible) {
//if (element)
//let dt = super._getElementData(element);
if (element) {
//[super.data, this.target] = dt;
await this.setData(element.data);
this.target = element;
if (this["target-class"] != null && this["target-class"] != "")
this.target.classList.add(this["target-class"]);
}
this._pass = true;
if (IUI.responsive && !this.static)
return this.showModal();
this.classList.remove(this.cssClass + "-modal");
var rect = this.getBoundingClientRect();
if (y != null) {
if (y + rect.height > document.documentElement.clientHeight)
this.style.top = (document.documentElement.clientHeight - rect.height) + "px";
else
this.style.top = y + "px";
}
this.classList.add(this.cssClass + "-visible");
if (x != null) {
if (x + rect.width > document.body.scrollWidth)
this.style.left = (document.body.scrollWidth - rect.width) + "px";
//else if (x < 0)
// this.style.left = "0px";
else
this.style.left = x + "px";
}
}
else {
this.classList.remove(this.cssClass + "-visible");
if (this.background)
this.background.hide();
//await super.setData({});// = {};
}
this._emit("visible", { visible });
return this;
}
};
IUI.module(Menu); IUI.module(Menu);
IUI.responsive = false; IUI.responsive = false;
window.addEventListener("load", function () { window.addEventListener("load", function () {
var handler = function (e) {
if (e.target.id == "iui_app_background" && IUI.responsive) {
for (var i = 0; i < IUI._menus.length; i++)
if (IUI._menus[i] instanceof Menu) IUI._menus[i].setVisible(false);
var handler = function (e) { e.preventDefault();
if (e.target.id == "iui_app_background" && IUI.responsive) { return;
for (var i = 0; i < IUI._menus.length; i++) }
if (IUI._menus[i] instanceof Menu)
IUI._menus[i].setVisible(false);
e.preventDefault(); for (var i = 0; i < IUI._menus.length; i++) {
return; if (IUI._menus[i].visible) {
var x = e.target;
var m = IUI._menus[i];
if (m instanceof Menu) {
if (m._pass) {
m._pass = false;
continue;
} else if (m.visible) if (!m.contains(e.target)) m.setVisible(false);
} else if (m instanceof DropDown) {
if (!(m.contains(e.target) || m.menu.contains(e.target)))
m.setVisible(false);
} }
}
}
};
for (var i = 0; i < IUI._menus.length; i++) { document.body.addEventListener("click", handler);
if (IUI._menus[i].visible) { document.body.addEventListener("touchstart", handler);
var x = e.target;
var m = IUI._menus[i];
if (m instanceof Menu) {
if (m._pass) {
m._pass = false;
continue;
}
else
if (m.visible)
if (!m.contains(e.target))
m.setVisible(false);
}
else if (m instanceof DropDown) {
if (!(m.contains(e.target) || m.menu.contains(e.target)))
m.setVisible(false);
}
}
}
};
document.body.addEventListener("click", handler);
document.body.addEventListener("touchstart", handler);
}); });

View File

@@ -3,253 +3,226 @@ import { IUI } from "../Core/IUI.js";
import Link from "../Router/Link.js"; import Link from "../Router/Link.js";
import Check from "./Check.js"; import Check from "./Check.js";
export default IUI.module(class Navbar extends IUIElement export default IUI.module(
{ class Navbar extends IUIElement {
constructor() constructor() {
{ super();
super();
this._list = []; this._list = [];
} }
search_old(text) { search_old(text) {
for(var i = 0; i < this._container.children.length; i++) for (var i = 0; i < this._container.children.length; i++) {
{ let el = this._container.children[i];
let el = this._container.children[i]; if (el.title.toLowerCase().includes(text)) {
if (el.title.toLowerCase().includes(text)) el.text.innerHTML = el.title.replace(
{ new RegExp(text, "gi"),
el.text.innerHTML = el.title.replace(new RegExp(text, 'gi'), (str) => `<span>${str}</span>`); str => `<span>${str}</span>`
el.style.display = ""; );
el.removeAttribute("hidden"); el.style.display = "";
el.removeAttribute("hidden");
// make parents visible // make parents visible
let level = parseInt(el.getAttribute("data-level")); let level = parseInt(el.getAttribute("data-level"));
for(var j = i - 1; j >= 0; j--) for (var j = i - 1; j >= 0; j--) {
{ let previous = this._container.children[j];
let previous = this._container.children[j]; let pLevel = parseInt(previous.getAttribute("data-level"));
let pLevel = parseInt(previous.getAttribute("data-level"));
if (pLevel < level) if (pLevel < level) {
{ previous.removeAttribute("hidden");
previous.removeAttribute("hidden"); previous.style.display = "";
previous.style.display = ""; if (previous.expand) previous.expand.checked = true;
if (previous.expand) level = pLevel;
previous.expand.checked = true;
level = pLevel;
}
}
}
else
{
el.style.display = "none";
} }
}
} else {
el.style.display = "none";
} }
}
} }
search(text, within) { search(text, within) {
let menu = within == null ? this._container : within.menu;
let menu = within == null ? this._container : within.menu; for (var i = 0; i < menu.children.length; i++) {
let item = menu.children[i];
let link = item.link;
if (link.title.toLowerCase().includes(text)) {
link.text.innerHTML = link.title.replace(
new RegExp(text, "gi"),
str => `<span>${str}</span>`
);
item.style.display = "";
for(var i = 0; i < menu.children.length; i++) //if (within != null)
{ // within.removeAttribute("collapsed");
let item = menu.children[i];
let link = item.link;
if (link.title.toLowerCase().includes(text))
{
link.text.innerHTML = link.title.replace(new RegExp(text, 'gi'), (str) => `<span>${str}</span>`);
item.style.display = "";
//if (within != null) // make parents visible
// within.removeAttribute("collapsed"); let parent = within;
// make parents visible while (parent != null && parent != this) {
let parent = within; parent.expand.checked = true;
parent.removeAttribute("collapsed");
while (parent != null && parent != this) parent.style.display = "";
{ parent = parent.parentElement.parentElement;
parent.expand.checked = true; }
parent.removeAttribute("collapsed"); } else {
parent.style.display = ""; item.style.display = "none";
parent = parent.parentElement.parentElement;
}
}
else
{
item.style.display = "none";
}
if (item.menu != null)
this.search(text, item);
} }
if (item.menu != null) this.search(text, item);
}
} }
expand_old(link, value) { expand_old(link, value) {
let next = link;// = link.nextElementSibling; let next = link; // = link.nextElementSibling;
let level = parseInt(link.getAttribute("data-level")); let level = parseInt(link.getAttribute("data-level"));
// save
//window.localStorage.setItem("iui.navbar/" + link.link, value);
// save if (link.expand && link.expand.checked != value)
//window.localStorage.setItem("iui.navbar/" + link.link, value); link.expand.checked = value;
if (link.expand && link.expand.checked != value) while ((next = next.nextElementSibling)) {
link.expand.checked = value; if (parseInt(next.getAttribute("data-level")) > level) {
if (value) next.removeAttribute("hidden");
while (next = next.nextElementSibling) { else next.setAttribute("hidden", "");
if (parseInt(next.getAttribute("data-level")) > level){ if (next.expand) next.expand.checked = value;
if (value) } else break;
next.removeAttribute("hidden"); }
else
next.setAttribute("hidden", "");
if (next.expand)
next.expand.checked = value;
}
else
break;
}
} }
expand(item, value) { expand(item, value) {
if (value) if (value) item.removeAttribute("collapsed");
item.removeAttribute("collapsed"); else item.setAttribute("collapsed", "");
else
item.setAttribute("collapsed", "");
item.expand.checked = value; item.expand.checked = value;
} }
get collapsed(){ get collapsed() {
return this.hasAttribute("collapsed"); return this.hasAttribute("collapsed");
} }
get auto(){ get auto() {
return this.hasAttribute("auto"); return this.hasAttribute("auto");
} }
build(){ build() {
this.innerHTML = "";
let roots = router.routes.filter(x => x.parent == null);
let self = this;
this._search = document.createElement("input");
this._search.type = "search";
this._search.className = this.cssClass + "-search textbox";
this._search.addEventListener("input", x => {
self.search(this._search.value);
});
this.innerHTML = ""; this.appendChild(this._search);
let roots = router.routes.filter(x => x.parent == null);
let self = this; this._container = document.createElement("div");
this._search = document.createElement("input"); this._container.className = this.cssClass + "-container";
this._search.type = "search";
this._search.className = this.cssClass + "-search textbox"; this.appendChild(this._container);
this._search.addEventListener("input", (x) => {
self.search(this._search.value); let collapsed = this.collapsed;
let auto = this.auto;
const filterRoutes = routes =>
routes.filter(r => {
if (r.hasAttribute("private")) return false;
if (this.private instanceof Function) {
try {
if (this.private(r)) {
return false;
}
} catch (ex) {
console.log(ex);
debugger;
}
return true;
}
return true;
}); });
this.appendChild(this._search); const appendRoutes = (routes, level, container) => {
for (var i = 0; i < routes.length; i++) {
let item = document.createElement("div");
item.className = this.cssClass + "-item";
this._container = document.createElement("div"); let link = new Link(); // document.createElement("i-link");
this._container.className = this.cssClass + "-container"; item.setAttribute("level", level);
link.link = routes[i].link;
link.title = routes[i].caption;
if (routes[i].icon != null)
link.innerHTML = "<img src='" + routes[i].icon + "'>";
this.appendChild(this._container); link.text = document.createElement("span");
link.text.innerHTML = link.title;
link.appendChild(link.text);
let collapsed = this.collapsed; item.link = link;
let auto = this.auto;
const filterRoutes = (routes) => item.appendChild(link);
routes.filter(r => { container.appendChild(item);
if (r.hasAttribute("private"))
return false;
if (this.private instanceof Function) self._list.push(item);
{
try{
if (this.private(r))
{
return false;
}
} catch(ex){
console.log(ex);
debugger;
}
return true; let subRoutes = filterRoutes(routes[i].routes);
}
return true; if (subRoutes.length > 0) {
// append plus
item.expand = new Check({ cssClass: this.cssClass + "-check" }); // document.createElement("i-check");
item.expand.checked = this.collapsed ? false : true;
item.expand.checked = !collapsed;
if (collapsed) item.setAttribute("collapsed", "");
link.appendChild(item.expand);
item.menu = document.createElement("div");
item.menu.className = this.cssClass + "-menu";
item.appendChild(item.menu);
item.expand.on("click", e => {
self.expand(item, item.expand.checked);
e.stopPropagation();
}); });
const appendRoutes = (routes, level, container) => { if (auto) {
for (var i = 0; i < routes.length; i++) { item.addEventListener("mouseenter", () =>
self.expand(item, true)
);
let item = document.createElement("div"); item.addEventListener("mouseleave", () =>
item.className = this.cssClass + "-item"; self.expand(item, false)
);
let link = new Link();// document.createElement("i-link");
item.setAttribute("level", level);
link.link = routes[i].link;
link.title = routes[i].caption;
if (routes[i].icon != null)
link.innerHTML = "<img src='" + routes[i].icon + "'>";
link.text = document.createElement("span");
link.text.innerHTML = link.title;
link.appendChild(link.text);
item.link = link;
item.appendChild(link);
container.appendChild(item);
self._list.push(item);
let subRoutes = filterRoutes(routes[i].routes);
if (subRoutes.length > 0) {
// append plus
item.expand = new Check({cssClass: this.cssClass + "-check"});// document.createElement("i-check");
item.expand.checked = this.collapsed ? false : true;
item.expand.checked = !collapsed;
if (collapsed)
item.setAttribute("collapsed", "");
link.appendChild(item.expand);
item.menu = document.createElement("div");
item.menu.className = this.cssClass + "-menu";
item.appendChild(item.menu);
item.expand.on("click", (e) => {
self.expand(item, item.expand.checked);
e.stopPropagation();
});
if (auto)
{
item.addEventListener("mouseenter", ()=> self.expand(item, true));
item.addEventListener("mouseleave", ()=> self.expand(item, false));
}
appendRoutes(subRoutes, level + 1, item.menu);
}
} }
};
appendRoutes(filterRoutes(roots), 0, this._container); appendRoutes(subRoutes, level + 1, item.menu);
}
}
};
appendRoutes(filterRoutes(roots), 0, this._container);
} }
created() { created() {
if (!this.hasAttribute("manual")) if (!this.hasAttribute("manual"))
window.router.on("created", ()=>this.build()); window.router.on("created", () => this.build());
window.router.on("navigate", (e) => { window.router.on("navigate", e => {
for (var i = 0; i < this._list.length; i++) {
for(var i = 0; i < this._list.length; i++) var el = this._list[i];
{ if (el.link.link == e.base) el.setAttribute("selected", "");
var el = this._list[i]; else el.removeAttribute("selected");
if (el.link.link == e.base) }
el.setAttribute("selected", ""); });
else
el.removeAttribute("selected");
}
});
} }
}); }
);

View File

@@ -1,188 +1,206 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class Range extends IUIElement { export default IUI.module(
class Range extends IUIElement {
constructor() { constructor() {
super({ super({
getItem: function (index, data) { getItem: function (index, data) {
var item = data[index]; var item = data[index];
return item == null ? index : item; return item == null ? index : item;
}, },
getIndex: function (x, width, data) { getIndex: function (x, width, data) {
if (x < 0) x = 0; if (x < 0) x = 0;
var p = x / width; var p = x / width;
var index = Math.floor(p * data.length); var index = Math.floor(p * data.length);
return index; return index;
}, },
getPreview: function (index, data, x, width, el) { getPreview: function (index, data, x, width, el) {
return null; return null;
}, },
getPosition: function (index, data, width) { getPosition: function (index, data, width) {
var itemSize = width / data.length; var itemSize = width / data.length;
return (index * itemSize) + (itemSize / 2); return index * itemSize + itemSize / 2;
}, },
layout: { layout: {
render: function () { render: function () {
return true; return true;
}, },
initialize: function () { initialize: function () {
return true; return true;
} },
}, },
data: [] data: [],
}); });
var self = this; var self = this;
this._register("select");
this._register("userSelect");
this._register("select"); this.preview = document.createElement("div");
this._register("userSelect"); this.preview.className = this.customClass + "-preview";
this.preview = document.createElement("div"); if (this.layout) this.layout.initialize.apply(this);
this.preview.className = this.customClass + "-preview";
this.thumb = document.createElement("div");
this.thumb.classList.add(this.customClass + "-thumb");
if (this.layout) this.classList.add(this.customClass);
this.layout.initialize.apply(this); this.appendChild(this.preview);
this.appendChild(this.thumb);
this.addEventListener("mousedown", function (e) {
self._startDragging(e.clientX, e.clientY);
});
this.thumb = document.createElement("div"); this.addEventListener("mouseleave", function (e) {
this.thumb.classList.add(this.customClass + "-thumb"); self.preview.classList.remove(self.customClass + "-preview-visible");
});
this.classList.add(this.customClass); this.addEventListener("mouseenter", function (e) {
this.appendChild(this.preview); var rect = self.getBoundingClientRect();
this.appendChild(this.thumb); self._offset = {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft,
};
});
this.addEventListener("mousedown", function (e) { this.addEventListener("mousemove", function (e) {
self._startDragging(e.clientX, e.clientY); self._drag(e.clientX, e.clientY);
});
this.addEventListener("mouseleave", function (e) { var x = e.clientX - self._offset.left;
self.preview.classList.remove(self.customClass + "-preview-visible"); var index = self.getIndex(x, self.offsetWidth, self.data);
}); var preview = self.getPreview.call(
self,
index,
self.data,
x,
self.offsetWidth,
self.preview
);
this.addEventListener("mouseenter", function (e) { if (preview == null || preview == false) {
var rect = self.getBoundingClientRect(); self.preview.classList.remove(self.customClass + "-preview-visible");
self._offset = { return;
top: rect.top + document.body.scrollTop, } else if (preview instanceof HTMLElement) {
left: rect.left + document.body.scrollLeft while (self.preview.children.length > 0)
}; self.preview.removeChild(self.preview.children[0]);
}); self.preview.appendChild(preview);
} else if (preview != true) {
self.preview.innerHTML = preview;
}
this.addEventListener("mousemove", function (e) { var index = self.getIndex(
e.clientX - self._offset.left,
self.offsetWidth,
self.data
);
var dx = self.getPosition(index, self.data, self.offsetWidth);
self.preview.style.setProperty("--x", dx + "px");
self.preview.classList.add(self.customClass + "-preview-visible");
});
self._drag(e.clientX, e.clientY); document.addEventListener("mouseup", function (e) {
if (self._dragging) self._endDragging(e.clientX, e.clientY);
});
var x = e.clientX - self._offset.left; this.addEventListener("touchstart", function (e) {
var index = self.getIndex(x, self.offsetWidth, self.data); self._startDragging(
var preview = self.getPreview.call(self, index, self.data, x, self.offsetWidth, self.preview); e.targetTouches[0].clientX,
e.targetTouches[0].clientY
);
});
if (preview == null || preview == false) { this.addEventListener("touchmove", function (e) {
self.preview.classList.remove(self.customClass + "-preview-visible"); self._drag(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
return; });
}
else if (preview instanceof HTMLElement) {
while (self.preview.children.length > 0)
self.preview.removeChild(self.preview.children[0]);
self.preview.appendChild(preview);
}
else if (preview != true) {
self.preview.innerHTML = preview;
}
var index = self.getIndex((e.clientX - self._offset.left), self.offsetWidth, self.data); this.addEventListener("touchend", function (e) {
var dx = self.getPosition(index, self.data, self.offsetWidth); self._endDragging(
e.changedTouches[0].clientX,
e.changedTouches[0].clientY
);
});
self.preview.style.setProperty("--x", dx + "px"); this.setData(this.data);
self.preview.classList.add(self.customClass + "-preview-visible");
});
document.addEventListener("mouseup", function (e) {
if (self._dragging)
self._endDragging(e.clientX, e.clientY);
});
this.addEventListener("touchstart", function (e) {
self._startDragging(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
});
this.addEventListener("touchmove", function (e) {
self._drag(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
});
this.addEventListener("touchend", function (e) {
self._endDragging(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
});
this.setData(this.data);
} }
_startDragging(x, y) { _startDragging(x, y) {
this._dragging = true; this._dragging = true;
document.onselectstart = function () { return false }; document.onselectstart = function () {
return false;
};
var rect = this.getBoundingClientRect(); var rect = this.getBoundingClientRect();
var body = document.body.getBoundingClientRect(); var body = document.body.getBoundingClientRect();
this._offset = { this._offset = {
top: rect.top + body.top,// document.body.scrollTop, top: rect.top + body.top, // document.body.scrollTop,
left: rect.left + body.left, left: rect.left + body.left,
}; };
var index = this.getIndex((x - this._offset.left), this.offsetWidth, this.data); var index = this.getIndex(
this.set(index, true, true); x - this._offset.left,
this.offsetWidth,
this.data
);
this.set(index, true, true);
} }
set(index, moveThumb = true, byUser = false) { set(index, moveThumb = true, byUser = false) {
var item = this.getItem(index, this.data);
var item = this.getItem(index, this.data); if (item != null) {
if (moveThumb) {
if (item != null) { var dx = this.getPosition(index, this.data, this.offsetWidth);
if (moveThumb) { this.thumb.style.setProperty("--x", dx + "px");
var dx = this.getPosition(index, this.data, this.offsetWidth);
this.thumb.style.setProperty("--x", dx + "px");
}
this._emit("select", { item, index });
if (byUser)
this._emit("userSelect", { item, index });
this.selected = item;
this.selectedIndex = index;
} }
return this; this._emit("select", { item, index });
if (byUser) this._emit("userSelect", { item, index });
this.selected = item;
this.selectedIndex = index;
}
return this;
} }
_drag(x, y) { _drag(x, y) {
if (this._dragging) { if (this._dragging) {
this.thumb.classList.add(this.customClass + "-thumb-dragging"); this.thumb.classList.add(this.customClass + "-thumb-dragging");
var dx = (x - this._offset.left); var dx = x - this._offset.left;
var index = this.getIndex(dx, this.offsetWidth, this.data); var index = this.getIndex(dx, this.offsetWidth, this.data);
this.thumb.style.setProperty("--x", dx + "px"); this.thumb.style.setProperty("--x", dx + "px");
this.set(index, false, true); this.set(index, false, true);
} }
} }
_endDragging(x, y) { _endDragging(x, y) {
document.onselectstart = function () { return true }; document.onselectstart = function () {
this.thumb.classList.remove(this.customClass + "-thumb-dragging"); return true;
var index = this.getIndex((x - this._offset.left), this.offsetWidth, this.data); };
this.set(index, true, true); this.thumb.classList.remove(this.customClass + "-thumb-dragging");
this._dragging = false; var index = this.getIndex(
x - this._offset.left,
this.offsetWidth,
this.data
);
this.set(index, true, true);
this._dragging = false;
} }
clear() { clear() {
return this.setData([]); return this.setData([]);
} }
render() { render() {
if (this.layout && this.layout.render) if (this.layout && this.layout.render) this.layout.render.apply(this);
this.layout.render.apply(this); return this;
return this;
} }
}); }
);

View File

@@ -1,23 +1,23 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class RoutesList extends IUIElement { export default IUI.module(
class RoutesList extends IUIElement {
constructor(properties) { constructor(properties) {
super(properties, { class: 'routes-list' }); super(properties, { class: "routes-list" });
} }
create() { create() {
if (!window.router) if (!window.router) return;
return;
var table = document.createElement("i-table"); var table = document.createElement("i-table");
this.appendChild(table); this.appendChild(table);
for (var i = 0; i < window.router.routes.length; i++) { for (var i = 0; i < window.router.routes.length; i++) {
// hell // hell
table.add table.add;
} }
} }
}); }
);

View File

@@ -1,42 +1,40 @@
import { IUI, iui } from '../Core/IUI.js'; import { IUI, iui } from "../Core/IUI.js";
import IUIElement from '../Core/IUIElement.js'; import IUIElement from "../Core/IUIElement.js";
import Menu from '../UI/Menu.js'; import Menu from "../UI/Menu.js";
import Layout from '../Data/Layout.js'; import Layout from "../Data/Layout.js";
import Repeat from '../Data/Repeat.js'; import Repeat from "../Data/Repeat.js";
export default IUI.module(class Select extends IUIElement { export default IUI.module(
class Select extends IUIElement {
constructor() { constructor() {
super({ super({
visible: false, visible: false,
searchlist: false, searchlist: false,
hasArrow: true, hasArrow: true,
//hasAdd: false, //hasAdd: false,
updateTextBox: true, updateTextBox: true,
query: (x) => null, query: x => null,
//_formatter: (x) => x, //_formatter: (x) => x,
_autocomplete: false, _autocomplete: false,
cssClass: 'select' cssClass: "select",
}); });
this._register("select"); this._register("select");
this._register("input"); this._register("input");
this._register("add"); this._register("add");
} }
disconnectedCallback() { disconnectedCallback() {
//console.log("Select removed", this); //console.log("Select removed", this);
if (!this.searchlist && this.menu) if (!this.searchlist && this.menu) app.removeChild(this.menu);
app.removeChild(this.menu);
} }
connectedCallback(){ connectedCallback() {
super.connectedCallback(); super.connectedCallback();
if (!this.searchlist && this.menu) if (!this.searchlist && this.menu) app.appendChild(this.menu);
app.appendChild(this.menu);
} }
get autocomplete() { get autocomplete() {
return this._autocomplete; return this._autocomplete;
} }
// get formatter() { // get formatter() {
@@ -48,211 +46,192 @@ export default IUI.module(class Select extends IUIElement {
// } // }
_checkValidity() { _checkValidity() {
if (this.validate != null) {
if (this.validate != null) { try {
try { let valid = this.validate.apply(this);
let valid = this.validate.apply(this); if (!valid) {
if (!valid) { this.setAttribute("invalid", "");
this.setAttribute("invalid", ""); this.classList.add(this.cssClass + "-invalid");
this.classList.add(this.cssClass + "-invalid"); return false;
return false; } else {
} this.removeAttribute("invalid");
else { this.classList.remove(this.cssClass + "-invalid");
this.removeAttribute("invalid"); return true;
this.classList.remove(this.cssClass + "-invalid"); }
return true; } catch (ex) {
} console.log("Validation Error", ex);
} return false;
catch (ex) {
console.log("Validation Error", ex);
return false;
}
} }
}
return true; return true;
} }
set hasAdd(value) { set hasAdd(value) {
if (value) if (value) this.setAttribute("add", "add");
this.setAttribute("add", "add"); else this.removeAttribute("add");
else
this.removeAttribute("add");
} }
get hasAdd() { get hasAdd() {
return this.hasAttribute("add"); return this.hasAttribute("add");
} }
async create() { async create() {
this.isAuto = this.hasAttribute("auto");
this.field = this.getAttribute("field");
this.isAuto = this.hasAttribute("auto"); if (this.field != null) {
this.field = this.getAttribute("field"); this.setAttribute(":data", `d['${this.field}']`);
this.setAttribute(":revert", `d['${this.field}'] = this.data`);
}
this._autocomplete = this.hasAttribute("autocomplete");
//this.hasAdd = this.hasAttribute("add") || this.hasAdd;
if (this.field != null) let self = this;
{
this.setAttribute(":data", `d['${this.field}']`)
this.setAttribute(":revert", `d['${this.field}'] = this.data`);
}
this._autocomplete = this.hasAttribute("autocomplete"); //if (this._autocomplete)
//this.hasAdd = this.hasAttribute("add") || this.hasAdd; // this.cssClass += "-autocomplete";
let self = this; this.repeat = new Repeat();
this.repeat.cssClass = "select-menu-repeat";
//this.repeat.innerHTML = this.innerHTML;
this.repeat.setAttribute(":data", "d[1]");
//if (this._autocomplete) this.counter = document.createElement("div");
// this.cssClass += "-autocomplete"; this.counter.className = this.cssClass + "-counter";
this.counter.innerHTML = "${d[0]}";
this.menu = new Menu({
cssClass: this.cssClass + "-menu",
"target-class": "",
});
this.menu
.on("click", async e => {
if (
e.target != self.textbox &&
e.target != self.counter &&
e.target !== self.menu
) {
await self.setData(e.target.data);
self._emit("input", { value: e.target.data });
this.repeat = new Repeat(); self.hide();
this.repeat.cssClass = "select-menu-repeat"; }
//this.repeat.innerHTML = this.innerHTML; })
this.repeat.setAttribute(":data", "d[1]"); .on("visible", x => {
if (!x.visible) self.hide();
this.counter = document.createElement("div");
this.counter.className = this.cssClass + "-counter";
this.counter.innerHTML = "${d[0]}";
this.menu = new Menu({ cssClass: this.cssClass + "-menu", "target-class": "" });
this.menu.on("click", async (e) => {
if (e.target != self.textbox && e.target != self.counter && e.target !== self.menu) {
await self.setData(e.target.data);
self._emit("input", { value: e.target.data });
self.hide();
}
}).on("visible", x=> { if (!x.visible) self.hide()});
if (this._autocomplete) {
this.textbox = document.createElement("input");
this.textbox.type = "search";
this.textbox.className = this.cssClass + "-textbox";
if (this.placeholder)
this.textbox.placeholder = this.placeholder;
this.textbox.addEventListener("keyup", function (e) {
if (e.keyCode != 13) {
self._query(0, self.textbox.value);
}
});
this.textbox.addEventListener("search", function (e) {
// console.log(e);
});
this.menu.appendChild(this.textbox);
}
// get collection
let layout = Layout.get(this, "div", true, true);
//debugger;
if (layout != null && layout.label != undefined && layout.menu != undefined) {
this.label = layout.label.node;
this.repeat.appendChild(layout.menu.node);
}
else if (layout != null && layout.null != null)
{
this.label = layout.null.node;
this.repeat.appendChild(layout.null.node.cloneNode(true));
}
else
{
this.label = document.createElement("div");
this.repeat.innerHTML = this.innerHTML;
}
// clear everything else
//this.innerHTML = "";
this.label.className = this.cssClass + "-label";
this.appendChild(this.label);
this.label.addEventListener("click", function (e) {
self.show();
}); });
this.menu.appendChild(this.repeat); if (this._autocomplete) {
this.menu.appendChild(this.counter); this.textbox = document.createElement("input");
this.textbox.type = "search";
this.textbox.className = this.cssClass + "-textbox";
if (this.placeholder) this.textbox.placeholder = this.placeholder;
if (this.hasArrow) { this.textbox.addEventListener("keyup", function (e) {
this.arrow = document.createElement("div"); if (e.keyCode != 13) {
this.arrow.className = this.cssClass + "-arrow"; self._query(0, self.textbox.value);
this.appendChild(this.arrow); }
this.arrow.addEventListener("click", function (e) {
if (self.visible)
self.hide();
else
self.show();
});
}
if (this.hasAdd) {
this._add_button = document.createElement("div");
this._add_button.className = this.cssClass + "-add";
this.appendChild(this._add_button);
this._add_button.addEventListener("click", function (e) {
self._emit("add", { value: self.data })
});
}
if (this.searchlist)
this.appendChild(this.menu);
else
{
app.appendChild(this.menu);
if (app.loaded)
{
///console.log("Append", this.menu);
await this.menu.create();
IUI.bind(this.menu, false, "menu");
await IUI.create(this.menu);
//this._make_bindings(this.menu);
}
}
this.addEventListener("click", function (e) {
if (e.target == self.textbox)
self.show();
}); });
this.textbox.addEventListener("search", function (e) {
// console.log(e);
});
this.menu.appendChild(this.textbox);
}
// get collection
let layout = Layout.get(this, "div", true, true);
//debugger;
if (
layout != null &&
layout.label != undefined &&
layout.menu != undefined
) {
this.label = layout.label.node;
this.repeat.appendChild(layout.menu.node);
} else if (layout != null && layout.null != null) {
this.label = layout.null.node;
this.repeat.appendChild(layout.null.node.cloneNode(true));
} else {
this.label = document.createElement("div");
this.repeat.innerHTML = this.innerHTML;
}
// clear everything else
//this.innerHTML = "";
this.label.className = this.cssClass + "-label";
this.appendChild(this.label);
this.label.addEventListener("click", function (e) {
self.show();
});
this.menu.appendChild(this.repeat);
this.menu.appendChild(this.counter);
if (this.hasArrow) {
this.arrow = document.createElement("div");
this.arrow.className = this.cssClass + "-arrow";
this.appendChild(this.arrow);
this.arrow.addEventListener("click", function (e) {
if (self.visible) self.hide();
else self.show();
});
}
if (this.hasAdd) {
this._add_button = document.createElement("div");
this._add_button.className = this.cssClass + "-add";
this.appendChild(this._add_button);
this._add_button.addEventListener("click", function (e) {
self._emit("add", { value: self.data });
});
}
if (this.searchlist) this.appendChild(this.menu);
else {
app.appendChild(this.menu);
if (app.loaded) {
///console.log("Append", this.menu);
await this.menu.create();
IUI.bind(this.menu, false, "menu");
await IUI.create(this.menu);
//this._make_bindings(this.menu);
}
}
this.addEventListener("click", function (e) {
if (e.target == self.textbox) self.show();
});
} }
get disabled() { get disabled() {
return this.hasAttribute("disabled"); return this.hasAttribute("disabled");
} }
set disabled(value) { set disabled(value) {
if (this._autocomplete) { if (this._autocomplete) {
this.textbox.disabled = value; this.textbox.disabled = value;
} }
if (value) {
this.setAttribute("disabled", value);
}
else {
this.removeAttribute("disabled");
}
if (value) {
this.setAttribute("disabled", value);
} else {
this.removeAttribute("disabled");
}
} }
/* /*
set(item) { set(item) {
@@ -275,117 +254,95 @@ export default IUI.module(class Select extends IUIElement {
*/ */
show() { show() {
this.setVisible(true); this.setVisible(true);
//this.textbox.focus(); //this.textbox.focus();
} }
hide() { hide() {
this.setVisible(false); this.setVisible(false);
//this.textbox.focus(); //this.textbox.focus();
} }
clear() { clear() {
if (this.autocomplete !== undefined) if (this.autocomplete !== undefined) this.textbox.value = "";
this.textbox.value = ""; //else
//else // this.label.innerHTML = "";
// this.label.innerHTML = "";
//this.menu.clear(); //this.menu.clear();
this.response.start = 0; this.response.start = 0;
this.selected = null; this.selected = null;
} }
async _query() { async _query() {
if (this._autocomplete) if (this.disabled) return;
let self = this;
let text = this._autocomplete ? this.textbox.value : null;
if (this._autocomplete) var res = this.query(0, text);
if (this.disabled) if (res instanceof Promise) res = await res;
return;
let self = this;
let text = this._autocomplete ? this.textbox.value : null;
var res = this.query(0, text)
if (res instanceof Promise)
res = await res;
//.then(async (res) => {
if (res[1].length == 0)
await self.setData(null);
await this.menu.setData(res);
//.then(async (res) => {
if (res[1].length == 0) await self.setData(null);
await this.menu.setData(res);
} }
async setData(value) { async setData(value) {
// this.label.innerHTML = "";
// this.label.innerHTML = ""; await super.setData(value);
await super.setData(value); try {
//let text = this.formatter(value);
// this.label.innerHTML = text == null ? "" : text;
try { this._emit("select", { value });
//let text = this.formatter(value); } catch (ex) {
// this.label.innerHTML = text == null ? "" : text; //console.log(ex);
this._emit("select", { value });
}
this._emit("select", { value }); //this._checkValidity();
}
catch (ex) {
//console.log(ex);
this._emit("select", { value });
}
//this._checkValidity();
if (this._checkValidity() && this.isAuto)
this.revert();
if (this._checkValidity() && this.isAuto) this.revert();
} }
setVisible(visible) { setVisible(visible) {
if (visible == this.visible) return;
if (visible == this.visible) //console.log("SLCT: SetVisible", visible);
return;
//console.log("SLCT: SetVisible", visible); if (visible) {
this._query(0);
if (visible) { // show menu
this._query(0); var rect = this.getBoundingClientRect();
this.menu.style.width =
this.clientWidth - this._computeMenuOuterWidth() + "px";
this.menu.style.paddingTop = rect.height + "px";
this.menu.setVisible(true, rect.left, rect.top); //, this.menu);
this.visible = true;
// show menu this.classList.add(this.cssClass + "-visible");
var rect = this.getBoundingClientRect();
this.menu.style.width = (this.clientWidth - this._computeMenuOuterWidth()) + "px";
this.menu.style.paddingTop = rect.height + "px";
this.menu.setVisible(true, rect.left, rect.top);//, this.menu);
this.visible = true;
this.classList.add(this.cssClass + "-visible"); if (this._autocomplete)
setTimeout(() => {
this.textbox.focus();
}, 100);
} else {
this.visible = false;
this.classList.remove(this.cssClass + "-visible");
if (this._autocomplete) this.menu.hide();
setTimeout(() => { }
this.textbox.focus();
}, 100);
}
else {
this.visible = false;
this.classList.remove(this.cssClass + "-visible");
this.menu.hide();
}
//this.textbox.focus();
//this.textbox.focus();
} }
_computeMenuOuterWidth() { _computeMenuOuterWidth() {
return this.menu.offsetWidth - this.menu.clientWidth;
return this.menu.offsetWidth - this.menu.clientWidth; /*
/*
var style = window.getComputedStyle(this.menu.el, null); var style = window.getComputedStyle(this.menu.el, null);
var paddingLeft = style.getPropertyValue('padding-left'); var paddingLeft = style.getPropertyValue('padding-left');
var paddingRight = style.getPropertyValue('padding-right'); var paddingRight = style.getPropertyValue('padding-right');
@@ -400,5 +357,5 @@ export default IUI.module(class Select extends IUIElement {
return paddingLeft + paddingRight + borderLeft + borderRight; return paddingLeft + paddingRight + borderLeft + borderRight;
*/ */
} }
}
}); );

View File

@@ -1,119 +1,121 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class SelectList extends IUIElement { export default IUI.module(
class SelectList extends IUIElement {
constructor() { constructor() {
super({ super({
selected: null, selected: null,
list: [], list: [],
query: (x) => null, query: x => null,
formatter: (x) => x["name"] formatter: x => x["name"],
}); });
var self = this; var self = this;
this._register("select"); this._register("select");
this.classList.add(this.cssClass); this.classList.add(this.cssClass);
// this.menu = iui(menu[0]).menu({ customClass: this.customClass + "-menu", layout: this.layout.menu }); // this.menu = iui(menu[0]).menu({ customClass: this.customClass + "-menu", layout: this.layout.menu });
this.menu = new Menu({ cssClass: this.cssClass + "-menu", "target-class": "" }); this.menu = new Menu({
cssClass: this.cssClass + "-menu",
"target-class": "",
});
this.menu.on("visible", function (v) { this.menu.on("visible", function (v) {
if (v) if (v) self.classList.add(self.cssClass + "-active");
self.classList.add(self.cssClass + "-active"); else self.classList.remove(self.cssClass + "-active");
else });
self.classList.remove(self.cssClass + "-active");
});
this.menu.on("click", (e) => { this.menu.on("click", e => {
let [data, element] = self.menu._getElementData(e.target); let [data, element] = self.menu._getElementData(e.target);
if (data != undefined) if (data != undefined) self.data = data;
self.data = data; });
});
document.body.appendChild(this.menu);
document.body.appendChild(this.menu); this.label = document.createElement("div");
this.label.className = this.cssClass + "-label";
this.label = document.createElement("div"); this.appendChild(this.label);
this.label.className = this.cssClass + "-label";
this.label.addEventListener("click", function (e) {
self.show();
});
this.appendChild(this.label); this.arrow = document.createElement("div");
this.arrow.className = this.customClass + "-arrow";
this.label.addEventListener("click", function (e) { this.header = document.createElement("div");
self.show(); this.header.className = this.customClass + "-header";
});
this.arrow = document.createElement("div"); this.header.appendChild(this.label);
this.arrow.className = this.customClass + "-arrow"; this.header.appendChild(this.arrow);
this.header = document.createElement("div"); this.appendChild(this.header);
this.header.className = this.customClass + "-header";
this.header.appendChild(this.label); this.arrow.addEventListener("click", function (e) {
this.header.appendChild(this.arrow); self.show();
});
this.appendChild(this.header);
this.arrow.addEventListener("click", function (e) {
self.show();
});
} }
clear() { clear() {
this.menu.clear(); this.menu.clear();
return this; return this;
} }
add(item) { add(item) {
this.menu.add(item); this.menu.add(item);
return this; return this;
} }
set(item) { set(item) {
if (typeof item == "string" || typeof item == "number") { if (typeof item == "string" || typeof item == "number") {
for (var i = 0; i < this.menu.list.length; i++) { for (var i = 0; i < this.menu.list.length; i++) {
if (this.menu.list[i][this.menu.index] == item) { if (this.menu.list[i][this.menu.index] == item) {
item = this.menu.list[i]; item = this.menu.list[i];
break; break;
} }
}
} }
}
// item is action // item is action
this.label.innerHTML = this.layout.text.formatter ? this.layout.text.formatter(item[this.layout.text.field], item) : item[this.layout.text.field]; this.label.innerHTML = this.layout.text.formatter
this.selected = item; ? this.layout.text.formatter(item[this.layout.text.field], item)
: item[this.layout.text.field];
this.selected = item;
this._emit("select", item); this._emit("select", item);
return this; return this;
} }
show() { show() {
return this.setVisible(true); return this.setVisible(true);
} }
hide() { hide() {
return this.setVisible(false); return this.setVisible(false);
} }
_computeMenuOuterWidth() { _computeMenuOuterWidth() {
return this.menu.offsetWidth - this.menu.clientWidth; return this.menu.offsetWidth - this.menu.clientWidth;
} }
setVisible(visible) { setVisible(visible) {
if (visible) { if (visible) {
this.response.start = 0; this.response.start = 0;
this._emit("query", null, this.response); this._emit("query", null, this.response);
// show menu // show menu
var rect = this.el.getBoundingClientRect(); var rect = this.el.getBoundingClientRect();
this.menu.el.style.width = (rect.width - this._computeMenuOuterWidth()) + "px"; this.menu.el.style.width =
this.menu.setVisible(true, rect.left, rect.top + rect.height); rect.width - this._computeMenuOuterWidth() + "px";
} this.menu.setVisible(true, rect.left, rect.top + rect.height);
else { } else {
this.menu.hide(); this.menu.hide();
} }
return this; return this;
} }
}); }
);

View File

@@ -1,20 +1,20 @@
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
export default IUI.module(class Tab extends IUIElement { export default IUI.module(
class Tab extends IUIElement {
constructor(properties) { constructor(properties) {
super(properties); super(properties);
} }
create() { create() {}
}
get caption() { get caption() {
return this.getAttribute("caption"); return this.getAttribute("caption");
} }
get selected() { get selected() {
return this.hasAttribute("selected");// == "1" || selected == "yes" || selected == "true"); return this.hasAttribute("selected"); // == "1" || selected == "yes" || selected == "true");
} }
}); }
);

View File

@@ -1,150 +1,149 @@
import IUIElement from "../Core/IUIElement.js";
import IUIElement from "../Core/IUIElement.js";
import Tab from "./Tab.js"; import Tab from "./Tab.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Target from "../Router/Target.js"; import Target from "../Router/Target.js";
export default IUI.module(class TabbedTarget extends Target { export default IUI.module(
class TabbedTarget extends Target {
constructor() { constructor() {
super({ super({
selected: null, selected: null,
list: [], list: [],
_y: 0, _y: 0,
_x: 0, _x: 0,
auto: true, auto: true,
}); });
} }
create() { create() {
var self = this; var self = this;
this._register("select"); this._register("select");
this._bar = document.createElement("div");
this._bar.classList.add(this.cssClass + "-bar");
this._bar = document.createElement("div"); this._ext = document.createElement("span");
this._bar.classList.add(this.cssClass + "-bar"); this._ext.className = this.cssClass + "-bar-ext";
this._bar.appendChild(this._ext);
this._ext = document.createElement("span"); //this.insertAdjacentElement("afterBegin", this._bar);
this._ext.className = this.cssClass + "-bar-ext";
this._bar.appendChild(this._ext);
this._body = document.createElement("div");
this._body.className = this.cssClass + "-body";
this.appendChild(this._bar);
this.appendChild(this._body);
//this.insertAdjacentElement("afterBegin", this._bar); var items = []; // this.getElementsByClassName("tab");
this._body = document.createElement("div"); for (var i = 0; i < this.children.length; i++)
this._body.className = this.cssClass + "-body"; if (this.children[i] instanceof Tab) items.push(this.children[i]);
this.appendChild(this._bar); this._observer = new ResizeObserver(x => {
this.appendChild(this._body); self._body.style.height = x[0].target.offsetHeight + "px"; // x[0].contentRect.height + "px";
});
items.map(x => self.add(x));
this.addEventListener(
"touchstart",
function (e) {
var x = e.target;
do {
if (x == self) break;
var sy = window.getComputedStyle(x)["overflow-x"];
if (
x.scrollWidth > x.clientWidth &&
(sy == "scroll" || sy == "auto")
)
return;
} while ((x = x.parentElement));
var items = [];// this.getElementsByClassName("tab"); self._x = e.originalEvent
? e.originalEvent.touches[0].clientX
: e.touches[0].clientX;
self._y = e.originalEvent
? e.originalEvent.touches[0].clientY
: e.touches[0].clientY;
},
{ passive: true }
);
for (var i = 0; i < this.children.length; i++) this.addEventListener(
if (this.children[i] instanceof Tab) "touchmove",
items.push(this.children[i]); function (e) {
if (!self._x || !self._y) {
return;
}
this._observer = new ResizeObserver(x => { var xUp = e.originalEvent
self._body.style.height = x[0].target.offsetHeight + "px";// x[0].contentRect.height + "px"; ? e.originalEvent.touches[0].clientX
}); : e.touches[0].clientX;
var yUp = e.originalEvent
? e.originalEvent.touches[0].clientY
: e.touches[0].clientY;
var xDiff = document.dir == "rtl" ? xUp - self._x : self._x - xUp;
var yDiff = self._y - yUp;
items.map(x => self.add(x)); var index = self.list.indexOf(self.selected);
if (Math.abs(xDiff) > Math.abs(yDiff)) {
this.addEventListener("touchstart", function (e) { /*most significant*/
if (xDiff > 0) {
var x = e.target; if (index < self.list.length - 1) {
do { self.select(self.list[index + 1]);
if (x == self) //self.selected.scrollIntoView();
break; }
var sy = window.getComputedStyle(x)["overflow-x"]; /* left swipe */
if (x.scrollWidth > x.clientWidth && (sy == "scroll" || sy == "auto"))
return;
} while (x = x.parentElement)
self._x = e.originalEvent ? e.originalEvent.touches[0].clientX : e.touches[0].clientX;
self._y = e.originalEvent ? e.originalEvent.touches[0].clientY : e.touches[0].clientY;
}, { passive: true });
this.addEventListener("touchmove", function (e) {
if (!self._x || !self._y) {
return;
}
var xUp = e.originalEvent ? e.originalEvent.touches[0].clientX : e.touches[0].clientX;
var yUp = e.originalEvent ? e.originalEvent.touches[0].clientY : e.touches[0].clientY;
var xDiff = document.dir == "rtl" ? xUp - self._x : self._x - xUp;
var yDiff = self._y - yUp;
var index = self.list.indexOf(self.selected);
if (Math.abs(xDiff) > Math.abs(yDiff)) {/*most significant*/
if (xDiff > 0) {
if (index < self.list.length - 1) {
self.select(self.list[index + 1]);
//self.selected.scrollIntoView();
}
/* left swipe */
} else {
if (index > 0)
self.select(self.list[index - 1]);
/* right swipe */
}
} else { } else {
if (yDiff > 0) { if (index > 0) self.select(self.list[index - 1]);
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
self._x = null;
self._y = null;
}, { passive: true }); /* right swipe */
}
} else {
if (yDiff > 0) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
self._x = null;
self._y = null;
},
{ passive: true }
);
} }
created() { created() {
//this._updateSize(); //this._updateSize();
} }
add(item) { add(item) {
var label = document.createElement("i-check");
label.innerHTML = item.title;
var label = document.createElement("i-check"); this._ext.insertAdjacentElement("beforebegin", label);
label.innerHTML = item.title;
this._ext.insertAdjacentElement("beforebegin", label); label.className = this.cssClass + "-button";
label.className = this.cssClass + "-button"; item.classList.add(this.cssClass + "-content");
label.content = item;
item.label = label;
item.classList.add(this.cssClass + "-content"); this._body.append(item);
label.content = item;
item.label = label;
this._body.append(item); this.list.push(item);
var self = this;
label.on("check", function (v) {
//if (v && !self._neglect)
self.select(item);
});
if (item.selected) this.select(item);
return this;
this.list.push(item);
var self = this;
label.on("check", function (v) {
//if (v && !self._neglect)
self.select(item);
});
if (item.selected)
this.select(item);
return this;
} }
//_updateSize() { //_updateSize() {
@@ -156,48 +155,41 @@ export default IUI.module(class TabbedTarget extends Target {
//} //}
select(item) { select(item) {
var tab; var tab;
if (item instanceof Tab) if (item instanceof Tab) tab = item;
else if (typeof o === "string" || o instanceof String)
for (var i = 0; i < this.list.length; i++)
if (this.list[i].id == item) {
tab = item; tab = item;
else if (typeof o === 'string' || o instanceof String) break;
for (var i = 0; i < this.list.length; i++) } else if (!isNaN(item)) tab = this.list[i];
if (this.list[i].id == item) {
tab = item;
break;
}
else if (!isNaN(item))
tab = this.list[i];
//this._neglect = true; //this._neglect = true;
var self = this; var self = this;
this.list.forEach(function (i) { this.list.forEach(function (i) {
if (i == tab) if (i == tab) tab.label.check(true);
tab.label.check(true);// set(true, false); // set(true, false);
else { else {
i.classList.remove(self.cssClass + "-content-active"); i.classList.remove(self.cssClass + "-content-active");
i.label.check(false);// set(false, false); i.label.check(false); // set(false, false);
} }
}); });
//this._neglect = false;
tab.classList.add(this.cssClass + "-content-active");
//this._neglect = false; if (this.selected != null) this._observer.unobserve(this.selected);
tab.classList.add(this.cssClass + "-content-active"); this.selected = tab;
this._observer.observe(this.selected);
if (this.selected != null) if (document.dir == "rtl")
this._observer.unobserve(this.selected); this._bar.scrollLeft = tab.label.offsetLeft + tab.label.clientWidth;
this.selected = tab; else this._bar.scrollLeft = tab.label.offsetLeft - tab.label.clientWidth;
this._observer.observe(this.selected);
if (document.dir == "rtl") this._emit("select", tab);
this._bar.scrollLeft = tab.label.offsetLeft + tab.label.clientWidth; return this;
else
this._bar.scrollLeft = tab.label.offsetLeft - tab.label.clientWidth;
this._emit("select", tab);
return this;
} }
}
}); );

File diff suppressed because it is too large Load Diff

View File

@@ -1,151 +1,149 @@
import IUIElement from "../Core/IUIElement.js";
import IUIElement from "../Core/IUIElement.js";
import Tab from "./Tab.js"; import Tab from "./Tab.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
import Check from "./Check.js"; import Check from "./Check.js";
export default IUI.module(class Tabs extends IUIElement { export default IUI.module(
class Tabs extends IUIElement {
constructor() { constructor() {
super({ super({
selected: null, selected: null,
list: [], list: [],
_y: 0, _y: 0,
_x: 0, _x: 0,
auto: true, auto: true,
}); });
} }
create() {
var self = this;
create() this._register("select");
{
var self = this;
this._register("select"); this._bar = document.createElement("div");
this._bar.classList.add(this.cssClass + "-bar");
this._ext = document.createElement("span");
this._ext.className = this.cssClass + "-bar-ext";
this._bar.appendChild(this._ext);
this._bar = document.createElement("div"); //this.insertAdjacentElement("afterBegin", this._bar);
this._bar.classList.add(this.cssClass + "-bar");
this._ext = document.createElement("span"); this._body = document.createElement("div");
this._ext.className = this.cssClass + "-bar-ext"; this._body.className = this.cssClass + "-body";
this._bar.appendChild(this._ext);
this.appendChild(this._bar);
this.appendChild(this._body);
var items = []; // this.getElementsByClassName("tab");
//this.insertAdjacentElement("afterBegin", this._bar); for (var i = 0; i < this.children.length; i++)
if (this.children[i] instanceof Tab) items.push(this.children[i]);
this._body = document.createElement("div"); this._observer = new ResizeObserver(x => {
this._body.className = this.cssClass + "-body"; self._body.style.height = x[0].target.offsetHeight + "px"; // x[0].contentRect.height + "px";
});
this.appendChild(this._bar); items.map(x => self.add(x));
this.appendChild(this._body);
this.addEventListener(
"touchstart",
function (e) {
var x = e.target;
do {
if (x == self) break;
var sy = window.getComputedStyle(x)["overflow-x"];
if (
x.scrollWidth > x.clientWidth &&
(sy == "scroll" || sy == "auto")
)
return;
} while ((x = x.parentElement));
self._x = e.originalEvent
? e.originalEvent.touches[0].clientX
: e.touches[0].clientX;
self._y = e.originalEvent
? e.originalEvent.touches[0].clientY
: e.touches[0].clientY;
},
{ passive: true }
);
var items = [];// this.getElementsByClassName("tab"); this.addEventListener(
"touchmove",
function (e) {
if (!self._x || !self._y) {
return;
}
for (var i = 0; i < this.children.length; i++) var xUp = e.originalEvent
if (this.children[i] instanceof Tab) ? e.originalEvent.touches[0].clientX
items.push(this.children[i]); : e.touches[0].clientX;
var yUp = e.originalEvent
? e.originalEvent.touches[0].clientY
: e.touches[0].clientY;
var xDiff = document.dir == "rtl" ? xUp - self._x : self._x - xUp;
var yDiff = self._y - yUp;
this._observer = new ResizeObserver(x => { var index = self.list.indexOf(self.selected);
self._body.style.height = x[0].target.offsetHeight + "px";// x[0].contentRect.height + "px";
});
items.map(x => self.add(x)); if (Math.abs(xDiff) > Math.abs(yDiff)) {
/*most significant*/
if (xDiff > 0) {
this.addEventListener("touchstart", function (e) { if (index < self.list.length - 1) {
self.select(self.list[index + 1]);
var x = e.target; //self.selected.scrollIntoView();
do { }
if (x == self) /* left swipe */
break;
var sy = window.getComputedStyle(x)["overflow-x"];
if (x.scrollWidth > x.clientWidth && (sy == "scroll" || sy == "auto"))
return;
} while (x = x.parentElement)
self._x = e.originalEvent ? e.originalEvent.touches[0].clientX : e.touches[0].clientX;
self._y = e.originalEvent ? e.originalEvent.touches[0].clientY : e.touches[0].clientY;
}, { passive: true });
this.addEventListener("touchmove", function (e) {
if (!self._x || !self._y) {
return;
}
var xUp = e.originalEvent ? e.originalEvent.touches[0].clientX : e.touches[0].clientX;
var yUp = e.originalEvent ? e.originalEvent.touches[0].clientY : e.touches[0].clientY;
var xDiff = document.dir == "rtl" ? xUp - self._x : self._x - xUp;
var yDiff = self._y - yUp;
var index = self.list.indexOf(self.selected);
if (Math.abs(xDiff) > Math.abs(yDiff)) {/*most significant*/
if (xDiff > 0) {
if (index < self.list.length - 1) {
self.select(self.list[index + 1]);
//self.selected.scrollIntoView();
}
/* left swipe */
} else {
if (index > 0)
self.select(self.list[index - 1]);
/* right swipe */
}
} else { } else {
if (yDiff > 0) { if (index > 0) self.select(self.list[index - 1]);
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
self._x = null;
self._y = null;
}, { passive: true }); /* right swipe */
}
} else {
if (yDiff > 0) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
self._x = null;
self._y = null;
},
{ passive: true }
);
} }
created() { created() {
//this._updateSize(); //this._updateSize();
} }
add(item) { add(item) {
var label = new Check(); // document.createElement("i-check");
label.innerHTML = item.caption;
var label = new Check();// document.createElement("i-check"); this._ext.insertAdjacentElement("beforebegin", label);
label.innerHTML = item.caption;
this._ext.insertAdjacentElement("beforebegin", label); label.className = this.cssClass + "-button";
label.className = this.cssClass + "-button"; item.classList.add(this.cssClass + "-content");
label.content = item;
item.label = label;
item.classList.add(this.cssClass + "-content"); this._body.append(item);
label.content = item;
item.label = label;
this._body.append(item); this.list.push(item);
var self = this;
label.on("check", function (v) {
//if (v && !self._neglect)
self.select(item);
});
if (item.selected) this.select(item);
return this;
this.list.push(item);
var self = this;
label.on("check", function (v) {
//if (v && !self._neglect)
self.select(item);
});
if (item.selected)
this.select(item);
return this;
} }
//_updateSize() { //_updateSize() {
@@ -157,48 +155,41 @@ export default IUI.module(class Tabs extends IUIElement {
//} //}
select(item) { select(item) {
var tab; var tab;
if (item instanceof Tab) if (item instanceof Tab) tab = item;
else if (typeof o === "string" || o instanceof String)
for (var i = 0; i < this.list.length; i++)
if (this.list[i].id == item) {
tab = item; tab = item;
else if (typeof o === 'string' || o instanceof String) break;
for (var i = 0; i < this.list.length; i++) } else if (!isNaN(item)) tab = this.list[i];
if (this.list[i].id == item) {
tab = item;
break;
}
else if (!isNaN(item))
tab = this.list[i];
//this._neglect = true; //this._neglect = true;
var self = this; var self = this;
this.list.forEach(function (i) { this.list.forEach(function (i) {
if (i == tab) if (i == tab) tab.label.check(true);
tab.label.check(true);// set(true, false); // set(true, false);
else { else {
i.classList.remove(self.cssClass + "-content-active"); i.classList.remove(self.cssClass + "-content-active");
i.label.check(false);// set(false, false); i.label.check(false); // set(false, false);
} }
}); });
//this._neglect = false;
tab.classList.add(this.cssClass + "-content-active");
//this._neglect = false; if (this.selected != null) this._observer.unobserve(this.selected);
tab.classList.add(this.cssClass + "-content-active"); this.selected = tab;
this._observer.observe(this.selected);
if (this.selected != null) if (document.dir == "rtl")
this._observer.unobserve(this.selected); this._bar.scrollLeft = tab.label.offsetLeft + tab.label.clientWidth;
this.selected = tab; else this._bar.scrollLeft = tab.label.offsetLeft - tab.label.clientWidth;
this._observer.observe(this.selected);
if (document.dir == "rtl") this._emit("select", tab);
this._bar.scrollLeft = tab.label.offsetLeft + tab.label.clientWidth; return this;
else
this._bar.scrollLeft = tab.label.offsetLeft - tab.label.clientWidth;
this._emit("select", tab);
return this;
} }
}
}); );

View File

@@ -1,104 +1,97 @@
import IUIElement from "../Core/IUIElement.js"; import IUIElement from "../Core/IUIElement.js";
import { IUI } from "../Core/IUI.js"; import { IUI } from "../Core/IUI.js";
export default IUI.module(class IUIWindow extends IUIElement { export default IUI.module(
class IUIWindow extends IUIElement {
constructor() { constructor() {
super({ closeable: true, draggable: false, focus: false }); super({ closeable: true, draggable: false, focus: false });
this._register("resize"); this._register("resize");
this._register("move"); this._register("move");
this._register("close"); this._register("close");
this._uid = "d:" + Math.random().toString(36).substring(2);
this._uid = "d:" + Math.random().toString(36).substring(2);
} }
static moduleName = "window"; static moduleName = "window";
create() { create() {
var self = this; var self = this;
this.tabIndex = 0; this.tabIndex = 0;
// create header // create header
this._header = document.createElement("div"); this._header = document.createElement("div");
this._header.className = this.cssClass + "-header"; this._header.className = this.cssClass + "-header";
if (this.draggable) if (this.draggable) this._header.setAttribute("draggable", true);
this._header.setAttribute("draggable", true);
var f = this.getElementsByClassName(this.cssClass + "-footer"); var f = this.getElementsByClassName(this.cssClass + "-footer");
this._footer = f.length > 0 ? f[0] : null; this._footer = f.length > 0 ? f[0] : null;
var b = this.getElementsByClassName(this.cssClass + "-body"); var b = this.getElementsByClassName(this.cssClass + "-body");
//this.body = b.length > 0 ? b[0]: null; //this.body = b.length > 0 ? b[0]: null;
if (b.length == 0) { if (b.length == 0) {
this._body = document.createElement("div"); this._body = document.createElement("div");
this._body.className = this.cssClass + "-body"; this._body.className = this.cssClass + "-body";
while (this.children.length > (this._footer == null ? 0 : 1)) while (this.children.length > (this._footer == null ? 0 : 1))
this._body.appendChild(this.children[0]); this._body.appendChild(this.children[0]);
this.insertAdjacentElement("afterBegin", this._body); this.insertAdjacentElement("afterBegin", this._body);
} else this._body = b[0];
} if (this.icon) {
else this._icon = document.createElement("div");
this._body = b[0]; this._icon.className = this.cssClass + "-icon";
//this._icon.src = this.icon;
if (this.icon) { this._icon.style.setProperty("--icon", `url('${this.icon}')`);
this._icon = document.createElement("div"); this._header.appendChild(this._icon);
this._icon.className = this.cssClass + "-icon"; }
//this._icon.src = this.icon;
this._caption = document.createElement("div");
this._caption.className = this.cssClass + "-caption";
this._caption.innerHTML = this.caption;
this._subtitle = document.createElement("div");
this._subtitle.className = this.cssClass + "-subtitle";
this._subtitle.innerHTML = this.subtitle;
this._icon.style.setProperty("--icon", `url('${this.icon}')`); this._tools = document.createElement("div");
this._header.appendChild(this._icon); this._tools.className = this.cssClass + "-tools";
}
this._caption = document.createElement("div"); this._header.appendChild(this._caption);
this._caption.className = this.cssClass + "-caption"; this._header.appendChild(this._subtitle);
this._caption.innerHTML = this.caption; this._header.appendChild(this._tools);
this._subtitle = document.createElement("div"); if (this.closeable) {
this._subtitle.className = this.cssClass + "-subtitle"; this._close = document.createElement("div");
this._subtitle.innerHTML = this.subtitle; this._close.className = this.cssClass + "-tools-close button";
this._close.addEventListener("click", function () {
self._emit("close");
});
}
this._tools = document.createElement("div"); //this.addEventListener("mousedown", function (e) {
this._tools.className = this.cssClass + "-tools"; // self.setFocus(true);
//});
this._header.appendChild(this._caption); this.insertAdjacentElement("afterBegin", this._header);
this._header.appendChild(this._subtitle);
this._header.appendChild(this._tools);
if (this.closeable) {
this._close = document.createElement("div");
this._close.className = this.cssClass + "-tools-close button";
this._close.addEventListener("click", function () {
self._emit("close");
});
}
//this.addEventListener("mousedown", function (e) {
// self.setFocus(true);
//});
this.insertAdjacentElement("afterBegin", this._header);
} }
setHeaderVisible(value) { setHeaderVisible(value) {
this._header.style.display = value ? "" : "none"; this._header.style.display = value ? "" : "none";
//this._updateSize(); //this._updateSize();
} }
setCloseVisible(value) { setCloseVisible(value) {
if (this.closeable) if (this.closeable) this._close.style.display = value ? "" : "none";
this._close.style.display = value ? "" : "none";
} }
get icon() { get icon() {
return this.getAttribute("icon"); return this.getAttribute("icon");
} }
/* /*
setFocus(v) { setFocus(v) {
@@ -174,91 +167,98 @@ export default IUI.module(class IUIWindow extends IUIElement {
} }
*/ */
show() { show() {
//this.setFocus(true); //this.setFocus(true);
return this; return this;
} }
move(x, y) { move(x, y) {
this.style.left = x + "px"; this.style.left = x + "px";
this.style.top = y + "px"; this.style.top = y + "px";
this._emit("move", x, y); this._emit("move", x, y);
return this; return this;
} }
resize(width, height) { resize(width, height) {
this.style.width = width + "px"; this.style.width = width + "px";
this.style.height = height + "px"; this.style.height = height + "px";
this._updateSize(); this._updateSize();
this._emit("resize", this.clientWidth, this.clientHeight); this._emit("resize", this.clientWidth, this.clientHeight);
return this; return this;
} }
_updateSize() { _updateSize() {
if (IUI.responsive) if (IUI.responsive) return;
return;
if (this._body) { if (this._body) {
if (this.clientWidth < this._body.scrollWidth) if (this.clientWidth < this._body.scrollWidth)
this.style.width = this._body.scrollWidth + 1 + "px"; this.style.width = this._body.scrollWidth + 1 + "px";
if (this._footer) { if (this._footer) {
if (this.clientWidth < this._footer.offsetWidth)
this.style.width = this._footer.offsetWidth + "px";
if (this.clientWidth < this._footer.offsetWidth) if (
this.style.width = this._footer.offsetWidth + "px"; this.clientHeight <
this._header.offsetHeight +
if (this.clientHeight < this._header.offsetHeight + this._body.scrollHeight + this._footer.offsetHeight) this._body.scrollHeight +
this.style.height = (this._header.offsetHeight + this._body.scrollHeight + this._footer.offsetHeight) + "px"; this._footer.offsetHeight
)
} this.style.height =
else { this._header.offsetHeight +
if (this.clientHeight < this._header.offsetHeight + this._body.scrollHeight) this._body.scrollHeight +
this.style.height = (this._header.offsetHeight + this._body.scrollHeight + 1) + "px"; this._footer.offsetHeight +
"px";
} } else {
if (
this.clientHeight <
this._header.offsetHeight + this._body.scrollHeight
)
this.style.height =
this._header.offsetHeight + this._body.scrollHeight + 1 + "px";
} }
}
// handle windows exceeding document size // handle windows exceeding document size
if (this.clientHeight > document.body.clientHeight) { if (this.clientHeight > document.body.clientHeight) {
this.style.height = document.body.clientHeight + "px"; this.style.height = document.body.clientHeight + "px";
if (this._footer) if (this._footer)
this._body.style.height = (this.clientHeight - this._footer.clientHeight - this._header.clientHeight) + "px"; this._body.style.height =
else this.clientHeight -
this._body.style.height = (this.clientHeight - this._header.clientHeight) + "px"; this._footer.clientHeight -
} this._header.clientHeight +
"px";
else
if (this.clientWidth > document.body.clientWidth) this._body.style.height =
this.style.width = document.body.clientWidth + 1 + "px"; this.clientHeight - this._header.clientHeight + "px";
}
if (this.clientWidth > document.body.clientWidth)
this.style.width = document.body.clientWidth + 1 + "px";
} }
get caption() { get caption() {
return this.getAttribute("caption"); return this.getAttribute("caption");
} }
set caption(value) { set caption(value) {
this._caption.innerHTML = value; this._caption.innerHTML = value;
this.setAttribute("caption", value); this.setAttribute("caption", value);
} }
get subtitle() { get subtitle() {
return this.getAttribute("subtitle"); return this.getAttribute("subtitle");
} }
set subtitle(value) { set subtitle(value) {
this._subtitle.innerHTML = value; this._subtitle.innerHTML = value;
this.setAttribute("subtitle", value); this.setAttribute("subtitle", value);
} }
}
);
});
/* /*
IUI._nav_list = []; IUI._nav_list = [];

View File

@@ -1,64 +1,61 @@
import {IUI, iui} from "./Core/IUI.js"; import { IUI, iui } from "./Core/IUI.js";
import "./Core/IUIElement.js"; import "./Core/IUIElement.js";
import './Core/App.js'; import "./Core/App.js";
import './Router/Router.js'; import "./Router/Router.js";
import './Router/Route.js'; import "./Router/Route.js";
import './Router/Link.js'; import "./Router/Link.js";
import './Router/Target.js'; import "./Router/Target.js";
import './Data/Repeat.js'; import "./Data/Repeat.js";
import './Data/Include.js'; import "./Data/Include.js";
import './Data/Form.js'; import "./Data/Form.js";
import './UI/Login.js'; import "./UI/Login.js";
import './UI/Window.js'; import "./UI/Window.js";
import './UI/Dialog.js'; import "./UI/Dialog.js";
import './UI/Input.js'; import "./UI/Input.js";
import './UI/Tab.js'; import "./UI/Tab.js";
import './UI/Tabs.js'; import "./UI/Tabs.js";
import './UI/Table.js'; import "./UI/Table.js";
import './UI/Check.js'; import "./UI/Check.js";
import './UI/Button.js'; import "./UI/Button.js";
import './UI/Navbar.js'; import "./UI/Navbar.js";
import './UI/DateTimePicker.js'; import "./UI/DateTimePicker.js";
import './Data/Layout.js'; import "./Data/Layout.js";
import './Data/Field.js'; import "./Data/Field.js";
import './UI/Background.js'; import "./UI/Background.js";
import './UI/Menu.js'; import "./UI/Menu.js";
import './Data/TableRow.js'; import "./Data/TableRow.js";
import './UI/Select.js'; import "./UI/Select.js";
import './UI/DropDown.js'; import "./UI/DropDown.js";
import './UI/Grid.js'; import "./UI/Grid.js";
import './UI/Location.js'; import "./UI/Location.js";
import './UI/CodePreview.js'; import "./UI/CodePreview.js";
window.addEventListener("beforeprint", (e)=>{ window.addEventListener("beforeprint", e => {
let viewRoute = router.current.viewRoute; let viewRoute = router.current.viewRoute;
viewRoute.style.height = "auto"; viewRoute.style.height = "auto";
router.style.height = viewRoute.clientHeight + "px"; router.style.height = viewRoute.clientHeight + "px";
}); });
window.addEventListener("afterprint", (e)=>{ window.addEventListener("afterprint", e => {
let viewRoute = router.current.viewRoute; let viewRoute = router.current.viewRoute;
viewRoute.style.height = ""; viewRoute.style.height = "";
router.style.height = ""; router.style.height = "";
}); });
window.addEventListener("load", async function () { window.addEventListener("load", async function () {
await IUI.create(document.body); await IUI.create(document.body);
await IUI.created(document.body); await IUI.created(document.body);
//if (window.app != null) {
// window.app._emit("load", { app: window.app });
// }
}); });
window.iui = iui; window.iui = iui;