all repos — h3 @ 176ab9207a785a6186e7975298282b72786320ea

A tiny, extremely minimalist JavaScript microframework.

docs/example/assets/js/h3.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
/**
 * H3 v0.9.0 "Impeccable Iconian"
 * Copyright 2020 Fabio Cevasco <h3rald@h3rald.com>
 * 
 * @license MIT
 * For the full license, see: https://github.com/h3rald/h3/blob/master/LICENSE
 */
const checkProperties = (obj1, obj2) => {
  for (const key in obj1) {
    if (!(key in obj2)) {
      return false;
    }
    if (!equal(obj1[key], obj2[key])) {
      return false;
    }
  }
  return true;
};

const equal = (obj1, obj2) => {
  if (
    (obj1 === null && obj2 === null) ||
    (obj1 === undefined && obj2 === undefined)
  ) {
    return true;
  }
  if (
    (obj1 === undefined && obj2 !== undefined) ||
    (obj1 !== undefined && obj2 === undefined) ||
    (obj1 === null && obj2 !== null) ||
    (obj1 !== null && obj2 === null)
  ) {
    return false;
  }
  if (obj1.constructor !== obj2.constructor) {
    return false;
  }
  if (typeof obj1 === "function") {
    if (obj1.toString() !== obj2.toString()) {
      return false;
    }
  }
  if ([String, Number, Boolean].includes(obj1.constructor)) {
    if (obj1 !== obj2) {
    }
    return obj1 === obj2;
  }
  if (obj1.constructor === Array) {
    if (obj1.length !== obj2.length) {
      return false;
    }
    for (let i = 0; i < obj1.length; i++) {
      if (!equal(obj1[i], obj2[i])) {
        return false;
      }
    }
    return true;
  }
  return checkProperties(obj1, obj2); // && checkProperties(obj2, obj1);
};

const selectorRegex = /^([a-z][a-z0-9:_=-]*)(#[a-z0-9:_=-]+)?(\.[^ ]+)*$/i;

let $onrenderCallbacks = [];

// Virtual Node Implementation with HyperScript-like syntax
class VNode {
  constructor(...args) {
    this.type = undefined;
    this.attributes = {};
    this.data = {};
    this.id = undefined;
    this.$html = undefined;
    this.$onrender = undefined;
    this.style = undefined;
    this.value = undefined;
    this.children = [];
    this.classList = [];
    this.eventListeners = {};
    if (args.length === 0) {
      throw new Error("[VNode] No arguments passed to VNode constructor.");
    }
    if (args.length === 1) {
      let vnode = args[0];
      if (typeof vnode === "string") {
        // Assume empty element
        this.processSelector(vnode);
      } else if (
        typeof vnode === "function" ||
        (typeof vnode === "object" && vnode !== null)
      ) {
        // Text node
        if (vnode.type === "#text") {
          this.type = "#text";
          this.value = vnode.value;
        } else {
          this.from(this.processVNodeObject(vnode));
        }
      } else {
        throw new Error(
          "[VNode] Invalid first argument passed to VNode constructor."
        );
      }
    } else if (args.length === 2) {
      let [selector, data] = args;
      if (typeof selector !== "string") {
        throw new Error(
          "[VNode] Invalid first argument passed to VNode constructor."
        );
      }
      this.processSelector(selector);
      if (typeof data === "string") {
        // Assume single child text node
        this.children = [new VNode({ type: "#text", value: data })];
        return;
      }
      if (
        typeof data !== "function" &&
        (typeof data !== "object" || data === null)
      ) {
        throw new Error(
          "[VNode] The second argument of a VNode constructor must be an object, an array or a string."
        );
      }
      if (Array.isArray(data)) {
        // Assume 2nd argument as children
        this.processChildren(data);
      } else {
        if (data instanceof Function || data instanceof VNode) {
          this.processChildren(data);
        } else {
          // Not a VNode, assume props object
          this.processProperties(data);
        }
      }
    } else if (args.length === 3) {
      let [selector, props, children] = args;
      if (typeof selector !== "string") {
        throw new Error(
          "[VNode] Invalid first argument passed to VNode constructor."
        );
      }
      this.processSelector(selector);
      if (typeof props !== "object" || props === null) {
        throw new Error(
          "[VNode] Invalid second argument passed to VNode constructor."
        );
      }
      this.processProperties(props);
      this.processChildren(children);
    } else {
      throw new Error(
        "[VNode] Too many arguments passed to VNode constructor."
      );
    }
  }

  from(data) {
    this.value = data.value;
    this.type = data.type;
    this.id = data.id;
    this.$html = data.$html;
    this.$onrender = data.$onrender;
    this.style = data.style;
    this.data = data.data;
    this.value = data.value;
    this.eventListeners = data.eventListeners;
    this.children = data.children;
    this.attributes = data.attributes;
    this.classList = data.classList;
  }

  equal(a, b) {
    return equal(a, b === undefined ? this : b);
  }

  processProperties(attrs) {
    this.id = this.id || attrs.id;
    this.$html = attrs.$html;
    this.$onrender = attrs.$onrender;
    this.style = attrs.style;
    this.value = attrs.value;
    this.data = attrs.data || {};
    this.classList =
      attrs.classList && attrs.classList.length > 0
        ? attrs.classList
        : this.classList;
    this.attributes = attrs;
    Object.keys(attrs)
      .filter((a) => a.startsWith("on") && attrs[a])
      .forEach((key) => {
        if (typeof attrs[key] !== "function") {
          throw new Error(
            `[VNode] Event handler specified for ${key} event is not a function.`
          );
        }
        this.eventListeners[key.slice(2)] = attrs[key];
        delete this.attributes[key];
      });
    delete this.attributes.value;
    delete this.attributes.$html;
    delete this.attributes.$onrender;
    delete this.attributes.id;
    delete this.attributes.data;
    delete this.attributes.style;
    delete this.attributes.classList;
  }

  processSelector(selector) {
    if (!selector.match(selectorRegex)) {
      throw new Error(`[VNode] Invalid selector: ${selector}`);
    }
    const [, type, id, classes] = selector.match(selectorRegex);
    this.type = type;
    if (id) {
      this.id = id.slice(1);
    }
    this.classList = (classes && classes.split(".").slice(1)) || [];
  }

  processVNodeObject(arg) {
    if (arg instanceof VNode) {
      return arg;
    }
    if (arg instanceof Function) {
      let vnode = arg();
      if (typeof vnode === "string") {
        vnode = new VNode({ type: "#text", value: vnode });
      }
      if (!(vnode instanceof VNode)) {
        throw new Error("[VNode] Function argument does not return a VNode");
      }
      return vnode;
    }
    throw new Error(
      "[VNode] Invalid first argument provided to VNode constructor."
    );
  }

  processChildren(arg) {
    const children = Array.isArray(arg) ? arg : [arg];
    this.children = children
      .map((c) => {
        if (typeof c === "string") {
          return new VNode({ type: "#text", value: c });
        }
        if (typeof c === "function" || (typeof c === "object" && c !== null)) {
          return this.processVNodeObject(c);
        }
        if (c) {
          throw new Error(`[VNode] Specified child is not a VNode: ${c}`);
        }
      })
      .filter((c) => c);
  }

  // Renders the actual DOM Node corresponding to the current Virtual Node
  render() {
    if (this.type === "#text") {
      return document.createTextNode(this.value);
    }
    const node = document.createElement(this.type);
    if (this.id) {
      node.id = this.id;
    }
    Object.keys(this.attributes).forEach((attr) => {
      // Set attributes (only if non-empty strings)
      if (this.attributes[attr] && typeof this.attributes[attr] === "string") {
        const a = document.createAttribute(attr);
        a.value = this.attributes[attr];
        node.setAttributeNode(a);
      }
      // Set properties
      if (typeof this.attributes[attr] !== "string" || !node[attr]) {
        node[attr] = this.attributes[attr];
      }
    });
    // Event Listeners
    Object.keys(this.eventListeners).forEach((event) => {
      node.addEventListener(event, this.eventListeners[event]);
    });
    // Value
    if (this.value) {
      node.value = this.value;
    }
    // Style
    if (this.style) {
      node.style.cssText = this.style;
    }
    // Classes
    this.classList.forEach((c) => {
      node.classList.add(c);
    });
    // Data
    Object.keys(this.data).forEach((key) => {
      node.dataset[key] = this.data[key];
    });
    // Children
    this.children.forEach((c) => {
      const cnode = c.render();
      node.appendChild(cnode);
      c.$onrender && $onrenderCallbacks.push(() => c.$onrender(cnode));
    });
    if (this.$html) {
      node.innerHTML = this.$html;
    }
    return node;
  }

  // Updates the current Virtual Node with a new Virtual Node (and syncs the existing DOM Node)
  redraw(data) {
    let { node, vnode } = data;
    const newvnode = vnode;
    const oldvnode = this;
    if (
      oldvnode.constructor !== newvnode.constructor ||
      oldvnode.type !== newvnode.type ||
      (oldvnode.type === newvnode.type &&
        oldvnode.type === "#text" &&
        oldvnode !== newvnode)
    ) {
      const renderedNode = newvnode.render();
      node.parentNode.replaceChild(renderedNode, node);
      newvnode.$onrender && newvnode.$onrender(renderedNode);
      oldvnode.from(newvnode);
      return;
    }
    // ID
    if (oldvnode.id !== newvnode.id) {
      node.id = newvnode.id || "";
      oldvnode.id = newvnode.id;
    }
    // Value
    if (oldvnode.value !== newvnode.value) {
      node.value = newvnode.value || "";
      oldvnode.value = newvnode.value;
    }
    // Classes
    if (!equal(oldvnode.classList, newvnode.classList)) {
      oldvnode.classList.forEach((c) => {
        if (!newvnode.classList.includes(c)) {
          node.classList.remove(c);
        }
      });
      newvnode.classList.forEach((c) => {
        if (!oldvnode.classList.includes(c)) {
          node.classList.add(c);
        }
      });
      oldvnode.classList = newvnode.classList;
    }
    // Style
    if (oldvnode.style !== newvnode.style) {
      node.style.cssText = newvnode.style || "";
      oldvnode.style = newvnode.style;
    }
    // Data
    if (!equal(oldvnode.data, newvnode.data)) {
      Object.keys(oldvnode.data).forEach((a) => {
        if (!newvnode.data[a]) {
          delete node.dataset[a];
        } else if (newvnode.data[a] !== oldvnode.data[a]) {
          node.dataset[a] = newvnode.data[a];
        }
      });
      Object.keys(newvnode.data).forEach((a) => {
        if (!oldvnode.data[a]) {
          node.dataset[a] = newvnode.data[a];
        }
      });
      oldvnode.data = newvnode.data;
    }
    // Attributes
    if (!equal(oldvnode.attributes, newvnode.attributes)) {
      Object.keys(oldvnode.attributes).forEach((a) => {
        if (newvnode.attributes[a] === false) {
          node[a] = false;
        }
        if (!newvnode.attributes[a]) {
          node.removeAttribute(a);
        } else if (
          newvnode.attributes[a] &&
          newvnode.attributes[a] !== oldvnode.attributes[a]
        ) {
          node.setAttribute(a, newvnode.attributes[a]);
        }
      });
      Object.keys(newvnode.attributes).forEach((a) => {
        if (!oldvnode.attributes[a] && newvnode.attributes[a]) {
          node.setAttribute(a, newvnode.attributes[a]);
        }
      });
      oldvnode.attributes = newvnode.attributes;
    }
    // Event listeners
    if (!equal(oldvnode.eventListeners, newvnode.eventListeners)) {
      Object.keys(oldvnode.eventListeners).forEach((a) => {
        if (!newvnode.eventListeners[a]) {
          node.removeEventListener(a, oldvnode.eventListeners[a]);
        } else if (
          !equal(newvnode.eventListeners[a], oldvnode.eventListeners[a])
        ) {
          node.removeEventListener(a, oldvnode.eventListeners[a]);
          node.addEventListener(a, newvnode.eventListeners[a]);
        }
      });
      Object.keys(newvnode.eventListeners).forEach((a) => {
        if (!oldvnode.eventListeners[a]) {
          node.addEventListener(a, newvnode.eventListeners[a]);
        }
      });
      oldvnode.eventListeners = newvnode.eventListeners;
    }
    // Children
    function mapChildren(oldvnode, newvnode) {
      let map = [];
      let oldNodesFound = 0;
      let newNodesFound = 0;
      // First look for existing nodes
      for (let oldIndex = 0; oldIndex < oldvnode.children.length; oldIndex++) {
        let found = -1;
        for (let index = 0; index < newvnode.children.length; index++) {
          if (
            equal(oldvnode.children[oldIndex], newvnode.children[index]) &&
            !map.includes(index)
          ) {
            found = index;
            newNodesFound++;
            oldNodesFound++;
            break;
          }
        }
        map.push(found);
      }
      if (
        newNodesFound === oldNodesFound &&
        newvnode.children.length === oldvnode.children.length
      ) {
        // something changed but everything else is the same
        return map;
      }
      if (newNodesFound === newvnode.children.length) {
        // All children in newvnode exist in oldvnode
        // All nodes that are not found must be removed
        for (let i = 0; i < map.length; i++) {
          if (map[i] === -1) {
            map[i] = -3;
          }
        }
      }
      if (oldNodesFound === oldvnode.children.length) {
        // All children in oldvnode exist in newvnode
        // Check where the missing newvnodes children need to be added
        for (
          let newIndex = 0;
          newIndex < newvnode.children.length;
          newIndex++
        ) {
          if (!map.includes(newIndex)) {
            map.splice(newIndex, 0, -2);
          }
        }
      }
      // Check if nodes needs to be removed (if there are fewer children)
      if (newvnode.children.length < oldvnode.children.length) {
        for (let i = 0; i < map.length; i++) {
          if (map[i] === -1 && !newvnode.children[i]) {
            map[i] = -3;
          }
        }
      }
      return map;
    }
    let childMap = mapChildren(oldvnode, newvnode);
    let resultMap = [...Array(childMap.filter((i) => i !== -3).length).keys()];
    while (!equal(childMap, resultMap)) {
      let count = -1;
      for (let i of childMap) {
        count++;
        let breakFor = false;
        if (i === count) {
          // Matching nodes;
          continue;
        }
        switch (i) {
          case -1:
            // different node, check
            oldvnode.children[count].redraw({
              node: node.childNodes[count],
              vnode: newvnode.children[count],
            });
            break;
          case -2:
            // add node
            oldvnode.children.splice(count, 0, newvnode.children[count]);
            const renderedNode = newvnode.children[count].render();
            node.insertBefore(renderedNode, node.childNodes[count]);
            newvnode.children[count].$onrender &&
              newvnode.children[count].$onrender(renderedNode);
            breakFor = true;
            break;
          case -3:
            // remove node
            oldvnode.children.splice(count, 1);
            node.removeChild(node.childNodes[count]);
            breakFor = true;
            break;
          default:
            // Node found, move nodes and remap
            const vtarget = oldvnode.children.splice(i, 1)[0];
            oldvnode.children.splice(count, 0, vtarget);
            node.insertBefore(node.childNodes[i], node.childNodes[count]);
            breakFor = true;
            break;
        }
        if (breakFor) {
          break;
        }
      }
      childMap = mapChildren(oldvnode, newvnode);
      resultMap = [...Array(childMap.length).keys()];
    }
    // $onrender
    if (!equal(oldvnode.$onrender, newvnode.$onrender)) {
      oldvnode.$onrender = newvnode.$onrender;
    }
    // innerHTML
    if (oldvnode.$html !== newvnode.$html) {
      node.innerHTML = newvnode.$html;
      oldvnode.$html = newvnode.$html;
      oldvnode.$onrender && oldvnode.$onrender(node);
    }
  }
}

/**
 * The code of the following class is heavily based on Storeon
 * Modified according to the terms of the MIT License
 * <https://github.com/storeon/storeon/blob/master/LICENSE>
 * Copyright 2019 Andrey Sitnik <andrey@sitnik.ru>
 */
class Store {
  constructor() {
    this.events = {};
    this.state = {};
  }
  dispatch(event, data) {
    if (event !== "$log") this.dispatch("$log", { event, data });
    if (this.events[event]) {
      let changes = {};
      let changed;
      this.events[event].forEach((i) => {
        this.state = { ...this.state, ...i(this.state, data) };
      });
    }
  }

  on(event, cb) {
    (this.events[event] || (this.events[event] = [])).push(cb);

    return () => {
      this.events[event] = this.events[event].filter((i) => i !== cb);
    };
  }
}

class Route {
  constructor({ path, def, query, parts }) {
    this.path = path;
    this.def = def;
    this.query = query;
    this.parts = parts;
    this.params = {};
    if (this.query) {
      const rawParams = this.query.split("&");
      rawParams.forEach((p) => {
        const [name, value] = p.split("=");
        this.params[decodeURIComponent(name)] = decodeURIComponent(value);
      });
    }
  }
}

class Router {
  constructor({ element, routes, store, location }) {
    this.element = element;
    this.redraw = null;
    this.store = store;
    this.location = location || window.location;
    if (!routes || Object.keys(routes).length === 0) {
      throw new Error("[Router] No routes defined.");
    }
    const defs = Object.keys(routes);
    this.routes = routes;
  }

  setRedraw(vnode, state) {
    this.redraw = () => {
      vnode.redraw({
        node: this.element.childNodes[0],
        vnode: this.routes[this.route.def](state),
      });
      this.store.dispatch("$redraw");
    };
  }

  async start() {
    const processPath = async (data) => {
      const oldRoute = this.route;
      const fragment =
        (data &&
          data.newURL &&
          data.newURL.match(/(#.+)$/) &&
          data.newURL.match(/(#.+)$/)[1]) ||
        this.location.hash;
      const path = fragment.replace(/\?.+$/, "").slice(1);
      const rawQuery = fragment.match(/\?(.+)$/);
      const query = rawQuery && rawQuery[1] ? rawQuery[1] : "";
      const pathParts = path.split("/").slice(1);

      let parts = {};
      for (let def of Object.keys(this.routes)) {
        let routeParts = def.split("/").slice(1);
        let match = true;
        let index = 0;
        parts = {};
        while (match && routeParts[index]) {
          const rP = routeParts[index];
          const pP = pathParts[index];
          if (rP.startsWith(":") && pP) {
            parts[rP.slice(1)] = pP;
          } else {
            match = rP === pP;
          }
          index++;
        }
        if (match) {
          this.route = new Route({ query, path, def, parts });
          break;
        }
      }
      if (!this.route) {
        throw new Error(`[Router] No route matches '${fragment}'`);
      }
      // Old route component teardown
      if (oldRoute) {
        const oldRouteComponent = this.routes[oldRoute.def];
        oldRouteComponent.state =
          oldRouteComponent.teardown &&
          (await oldRouteComponent.teardown(oldRouteComponent.state));
      }
      // New route component setup
      const newRouteComponent = this.routes[this.route.def];
      newRouteComponent.state = {};
      newRouteComponent.setup &&
        (await newRouteComponent.setup(newRouteComponent.state));
      // Redrawing...
      redrawing = true;
      this.store.dispatch("$navigation", this.route);
      while (this.element.firstChild) {
        this.element.removeChild(this.element.firstChild);
      }
      const vnode = newRouteComponent(newRouteComponent.state);
      const node = vnode.render();
      this.element.appendChild(node);
      vnode.$onrender && vnode.$onrender(node);
      $onrenderCallbacks.forEach((cbk) => cbk());
      $onrenderCallbacks = [];
      this.setRedraw(vnode, newRouteComponent.state);
      window.scrollTo(0, 0);
      this.store.dispatch("$redraw");
      redrawing = false;
    };
    window.addEventListener("hashchange", processPath);
    await processPath();
  }

  navigateTo(path, params) {
    let query = Object.keys(params || {})
      .map((p) => `${encodeURIComponent(p)}=${encodeURIComponent(params[p])}`)
      .join("&");
    query = query ? `?${query}` : "";
    this.location.hash = `#${path}${query}`;
  }
}

// High Level API
const h3 = (...args) => {
  return new VNode(...args);
};

let store = null;
let router = null;
let redrawing = false;

h3.init = (config) => {
  let { element, routes, modules, preStart, postStart, location } = config;
  if (!routes) {
    // Assume config is a component object, define default route
    if (typeof config !== "function") {
      throw new Error(
        "[h3.init] The specified argument is not a valid configuration object or component function"
      );
    }
    routes = { "/": config };
  }
  element = element || document.body;
  if (!(element && element instanceof Element)) {
    throw new Error("[h3.init] Invalid element specified.");
  }
  // Initialize store
  store = new Store();
  (modules || []).forEach((i) => {
    i(store);
  });
  store.dispatch("$init");
  // Initialize router
  router = new Router({ element, routes, store, location });
  return Promise.resolve(preStart && preStart())
    .then(() => router.start())
    .then(() => postStart && postStart());
};

h3.navigateTo = (path, params) => {
  if (!router) {
    throw new Error(
      "[h3.navigateTo] No application initialized, unable to navigate."
    );
  }
  return router.navigateTo(path, params);
};

Object.defineProperty(h3, "route", {
  get: () => {
    if (!router) {
      throw new Error(
        "[h3.route] No application initialized, unable to retrieve current route."
      );
    }
    return router.route;
  },
});

Object.defineProperty(h3, "state", {
  get: () => {
    if (!store) {
      throw new Error(
        "[h3.state] No application initialized, unable to retrieve current state."
      );
    }
    return store.state;
  },
});

h3.on = (event, cb) => {
  if (!store) {
    throw new Error(
      "[h3.on] No application initialized, unable to listen to events."
    );
  }
  return store.on(event, cb);
};

h3.dispatch = (event, data) => {
  if (!store) {
    throw new Error(
      "[h3.dispatch] No application initialized, unable to dispatch events."
    );
  }
  return store.dispatch(event, data);
};

h3.redraw = (setRedrawing) => {
  if (!router || !router.redraw) {
    throw new Error(
      "[h3.redraw] No application initialized, unable to redraw."
    );
  }
  if (redrawing) {
    return;
  }
  redrawing = true;
  router.redraw();
  redrawing = setRedrawing || false;
};

export default h3;