Skip to content

Commit

Permalink
Merge pull request #704 from trheyi/main
Browse files Browse the repository at this point in the history
Refactor SUI core to use dynamic loading for the SUI library
  • Loading branch information
trheyi authored Jul 23, 2024
2 parents 748a852 + 60ada0a commit 5ec63f6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 10 deletions.
6 changes: 5 additions & 1 deletion sui/core/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ func (page *Page) Compile(ctx *BuildContext, option *BuildOption) (string, []str
}

// SUI lib
head.AppendHtml("\n\n" + `<script name="sui" type="text/javascript">` + suiLibScript + `</script>` + "\n\n")
lib, err := libsui(option.ScriptMinify)
if err != nil {
return "", warnings, err
}
head.AppendHtml("\n\n" + `<script name="sui" type="text/javascript">` + lib + `</script>` + "\n\n")

// Page Config
page.Config = page.GetConfig()
Expand Down
55 changes: 46 additions & 9 deletions sui/core/injections.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,33 @@ package core

import (
"fmt"

"github.com/evanw/esbuild/pkg/api"
"github.com/yaoapp/gou/runtime/transform"
)

const suiLibScript = `
var libsuicode = ""

func libsui(minify bool) (string, error) {
if libsuicode != "" {
return libsuicode, nil
}

option := api.TransformOptions{Target: api.ES2015}
if minify {
option.MinifyIdentifiers = true
option.MinifySyntax = true
option.MinifyWhitespace = true
}
var err error
libsuicode, err = transform.JavaScript(libsuisource, option)
if err != nil {
return "", fmt.Errorf("libsui error: %w", err)
}
return libsuicode, nil
}

const libsuisource = `
function __sui_state(component) {
this.handlers = component.watch || {};
Expand All @@ -23,13 +47,32 @@ const suiLibScript = `
}
function __sui_component(elm, component) {
console.log('elm', component);
this.root = elm;
this.store = new __sui_store(elm);
this.props = new __sui_props(elm);
this.state = component ? new __sui_state(component) : {};
}
function $$(selector) {
elm = null;
if (typeof selector === "string" ){
elm = document.querySelector(selector);
}
if (selector instanceof HTMLElement) {
elm = selector;
}
if (elm) {
cn = elm.getAttribute("s:cn");
if (cn != "" && typeof window[cn] === "function") {
const component = new window[cn](elm);
return new __sui_component(elm, component);
}
}
return null;
}
function __sui_event_handler(event, dataKeys, jsonKeys, elm, handler) {
const data = {};
dataKeys.forEach(function (key) {
Expand All @@ -48,13 +91,7 @@ const suiLibScript = `
}
}
})
const cn = elm.getAttribute("s:cn");
let component = null
if (cn != "") {
component = new window[cn](elm);
}
handler && handler(event, data, new __sui_component(elm, component));
handler && handler(event, data, elm);
};
function __sui_store(elm) {
Expand Down

0 comments on commit 5ec63f6

Please sign in to comment.