Skip to content

Commit

Permalink
More work
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Oct 21, 2024
1 parent 1cabdb7 commit 3518aec
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 97 deletions.
53 changes: 22 additions & 31 deletions tpl/js/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -771,9 +771,6 @@ func (b *batcher) build() (*Package, error) {
}

func (b *batcher) doBuild() (*Package, error) {
start := time.Now()
defer logTime("build", start) // TODO1 remove.

keyPath := b.id

type importContext struct {
Expand All @@ -782,6 +779,11 @@ func (b *batcher) doBuild() (*Package, error) {
scriptOptions *ScriptOptions // TODO1 remove resourceGetter?
}

type originImportContext struct {

Check failure on line 782 in tpl/js/batch.go

View workflow job for this annotation

GitHub Actions / test (1.22.x, ubuntu-latest)

type originImportContext is unused (U1000)

Check failure on line 782 in tpl/js/batch.go

View workflow job for this annotation

GitHub Actions / test (1.23.x, ubuntu-latest)

type originImportContext is unused (U1000)
importContextPath string
importContext importContext
}

state := struct {
importResource *maps.Cache[string, resource.Resource]
resultResource *maps.Cache[string, resource.Resource]
Expand All @@ -794,6 +796,7 @@ func (b *batcher) doBuild() (*Package, error) {
pathGroup: maps.NewCache[string, string](),
}

// Entry points passed to ESBuid.
var entryPoints []string
addResource := func(group, pth string, r resource.Resource, isResult bool) {
state.pathGroup.Set(pth, group)
Expand Down Expand Up @@ -843,20 +846,15 @@ func (b *batcher) doBuild() (*Package, error) {
script: vv,
Import: impPath,
}

state.importResource.Set(bt.Import, vv.Resource)
for _, vvv := range instances.ByScriptID(vv.ID) {
bt.Instances = append(bt.Instances, scriptInstanceBatchTemplateContext{instance: vvv})
sort.Slice(bt.Instances, func(i, j int) bool {
return bt.Instances[i].ID() < bt.Instances[j].ID()
})
}

t.Scripts = append(t.Scripts, bt)
}

sort.Slice(t.Scripts, func(i, j int) bool {
return t.Scripts[i].ID < t.Scripts[j].ID
})

r, s, err := b.client.buildBatch(t)
if err != nil {
return nil, err
Expand All @@ -880,26 +878,25 @@ func (b *batcher) doBuild() (*Package, error) {
return nil, err
}

var importResulveMu sync.Mutex

externalOptions := b.config
externalOptions.Format = "esm" // Maybe allow other formats for simple 1 script setups. Also consider splitting below.
if externalOptions.Format == "" {
externalOptions.Format = "esm"
}
if externalOptions.Format != "esm" {
return nil, fmt.Errorf("only esm format is currently supported")
}

jopts := js.Options{
jsOpts := js.Options{
ExternalOptions: externalOptions,
InternalOptions: js.InternalOptions{
OutDir: outDir,
Write: true,
AllowOverwrite: true,
Splitting: true,
ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string {
importResulveMu.Lock()
defer importResulveMu.Unlock()

if _, found := state.importResource.Get(imp); found {
return imp
}

var importContextPath string
if args.Kind == api.ResolveEntryPoint {
importContextPath = args.Path
Expand All @@ -910,21 +907,17 @@ func (b *batcher) doBuild() (*Package, error) {

if importContext.resourceGetter != nil {
resolved := importContext.resourceGetter.Get(imp)

if resolved != nil {
imp := hugoVirtualNS + resolved.(resource.PathProvider).Path()
state.importResource.Set(imp, resolved)
state.importerImportContext.Set(imp, importContext) // TODO1 test case (see headlessui)
state.importerImportContext.Set(imp, importContext)
return imp

}
}
return ""
},
ImportOnLoadFunc: func(args api.OnLoadArgs) string {
importResulveMu.Lock()
defer importResulveMu.Unlock()

imp := args.Path

if r, found := state.importResource.Get(imp); found {
Expand Down Expand Up @@ -968,7 +961,7 @@ func (b *batcher) doBuild() (*Package, error) {
},
}

result, err := b.client.client.BuildBundle(jopts)
result, err := b.client.client.BuildBundle(jsOpts)
if err != nil {
return nil, fmt.Errorf("failed to build bundle: %w", err)
}
Expand All @@ -981,8 +974,7 @@ func (b *batcher) doBuild() (*Package, error) {

groups := make(map[string]resource.Resources)

// TODO1
addFoo := func(filename, targetPath, group string, mt media.Type) error {
createAndAddResource := func(filename, targetPath, group string, mt media.Type) error {
rd := resources.ResourceSourceDescriptor{
LazyPublish: true,
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
Expand All @@ -1002,7 +994,7 @@ func (b *batcher) doBuild() (*Package, error) {
return nil
}

createAndAddResource3 := func(o esBuildResultMetaOutput) (bool, error) {
createAndAddResources := func(o esBuildResultMetaOutput) (bool, error) {
p := filepath.ToSlash(strings.TrimPrefix(o.filename, outDir))
ext := path.Ext(p)
mt, _, found := mediaTypes.GetBySuffix(ext)
Expand All @@ -1016,14 +1008,13 @@ func (b *batcher) doBuild() (*Package, error) {
return false, nil
}

if err := addFoo(o.filename, p, group, mt); err != nil {
// TODO1
if err := createAndAddResource(o.filename, p, group, mt); err != nil {
return false, err
}

if o.CSSBundle != "" {
p := filepath.ToSlash(strings.TrimPrefix(o.CSSBundle, outDir))
if err := addFoo(o.CSSBundle, p, group, cssMt); err != nil {
if err := createAndAddResource(o.CSSBundle, p, group, cssMt); err != nil {
return false, err
}
}
Expand All @@ -1032,7 +1023,7 @@ func (b *batcher) doBuild() (*Package, error) {
}

for _, o := range m.Outputs {
handled, err := createAndAddResource3(o)
handled, err := createAndAddResources(o)
if err != nil {
return nil, err
}
Expand Down
81 changes: 15 additions & 66 deletions tpl/js/batch_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,18 @@ module.exports = window.React;
---
title: "My Bundle"
---
-- content/mybundle/bundlestyles.css --
import './foo.css'
import './bar.css'
.bundlestyles {
-- content/mybundle/mybundlestyles.css --
@import './foo.css';
@import './bar.css';
@import './otherbundlestyles.css';
.mybundlestyles {
background-color: blue;
}
-- content/mybundle/bundlereact.jsx --
import * as React from "react";
import './foo.css'
import './bundlestyles.css'
import './foo.css';
import './mybundlestyles.css';
window.React1 = React;
let text = 'Click me, too!'
Expand Down Expand Up @@ -90,6 +92,10 @@ export default function Run(modules) {
}
}
}
-- assets/other/otherbundlestyles.css --
.otherbundlestyles {
background-color: red;
}
-- assets/other/foo.css --
@import './bar.css';
Expand Down Expand Up @@ -128,7 +134,6 @@ export function helper() {
import * as React from "react";
import './button.css'
import './foo.css'
import './bundlestyles.css'
import './react1styles.css'
window.React1 = React;
Expand Down Expand Up @@ -305,8 +310,8 @@ var id3 = "config";
console.log("main3.params.id", id3);
`)

b.EditFileReplaceAll("content/mybundle/bundlestyles.css", ".bundlestyles", ".bundlestyles-edit").Build()
b.AssertFileContent("public/mybundle_reactbatch.css", ".bundlestyles-edit {")
b.EditFileReplaceAll("content/mybundle/mybundlestyles.css", ".mybundlestyles", ".mybundlestyles-edit").Build()
b.AssertFileContent("public/mybundle_reactbatch.css", ".mybundlestyles-edit {")

b.EditFileReplaceAll("assets/other/bar.css", ".bar {", ".bar-edit {").Build()
b.AssertFileContent("public/mybundle_reactbatch.css", ".bar-edit {")
Expand All @@ -315,62 +320,6 @@ console.log("main3.params.id", id3);
b.AssertFileContent("public/mybundle_reactbatch.css", ".bar-edit2 {")
}

func TestEsBuildResolvePageBundle(t *testing.T) {
files := `
-- hugo.toml --
-- content/mybundle/index.md --
---
title: "My Bundle"
---
-- content/mybundle/mystyles1.css --
body {
background-color: blue;
}
-- content/mybundle/mystyles2.css --
button {
background-color: red;
}
-- content/mybundle/myscript.js --
import "./mystyles1.css";
import "./mystyles2.css";
console.log('Hello, world!');
// TODO1 make it work without this.
export default {};
-- layouts/_default/single.html --
Single.
TODO1 directory structure vs ID:
{{ $batch := (js.Batch "myjsbundle" .Store) }}
{{ $js := .Resources.GetMatch "*.js" }}
{{ with $batch.UseScriptGroup "g1" }}
{{ with .Script "s1" }}
{{ if not .GetImportContext }}
{{ .SetImportContext $ }}
{{ end }}
{{ if not .GetResource }}
{{ .SetResource $js }}
{{ end }}
{{ .AddInstance "i1" (dict "title" "Instance s1-1") }}
{{ end }}
{{ end }}
{{ range $batch.Build.Groups }}
{{ range $i, $e := . }}
{{ $i }}: {{ $e.RelPermalink }}|
{{ end }}
{{ end }}
`

// TODO1 check what happens without AddInstance.

b := hugolib.Test(t, files, hugolib.TestOptWithOSFs())

b.AssertFileContent("public/myjsbundle_g1.css", "body", "button")
b.AssertFileContent("public/myjsbundle_g1.js", `Hello, world!`)
}

// TODO1 executing "_default/single.html" at <$batch.Build.Groups>: error calling Build: Could not resolve "./mystyles.css"` error file source.

// TODO1 move this.
func TestResourcesGet(t *testing.T) {
files := `
Expand All @@ -394,7 +343,7 @@ Text 1.
-- layouts/index.html --
{{ $mybundle := site.GetPage "mybundle" }}
{{ $subResources := resources.Match "text/sub/*.*" }}
{{ $subResourcesMount := $subResources.Mount "newroot" }}
{{ $subResourcesMount := $subResources.Mount "text/sub" "newroot" }}
resources:text/txt1.txt:{{ with resources.Get "text/txt1.txt" }}{{ .Name }}{{ end }}|
resources:text/txt2.txt:{{ with resources.Get "text/txt2.txt" }}{{ .Name }}{{ end }}|
resources:text/sub/txt3.txt:{{ with resources.Get "text/sub/txt3.txt" }}{{ .Name }}{{ end }}|
Expand Down

0 comments on commit 3518aec

Please sign in to comment.