diff --git a/cmd/build.go b/cmd/build.go index a370a9a4..010931c8 100644 --- a/cmd/build.go +++ b/cmd/build.go @@ -13,8 +13,8 @@ import ( "github.com/spf13/cobra" ) -// BuildDirFlag allows users to override name of default build directory (public) -var BuildDirFlag string +// OutputDirFlag allows users to override name of default build directory (public) +var OutputDirFlag string // VerboseFlag provides users with additional logging information. var VerboseFlag bool @@ -22,15 +22,12 @@ var VerboseFlag bool // BenchmarkFlag provides users with build speed statistics to help identify bottlenecks. var BenchmarkFlag bool -// NodeJSFlag let you use your systems NodeJS to build the site instead of core build. -var NodeJSFlag bool - func setBuildDir(siteConfig readers.SiteConfig) string { buildDir := siteConfig.BuildDir // Check if directory is overridden by flag. - if BuildDirFlag != "" { + if OutputDirFlag != "" { // If dir flag exists, use it. - buildDir = BuildDirFlag + buildDir = OutputDirFlag } return buildDir } @@ -127,34 +124,16 @@ func Build() error { return err } - // Run the build.js script using user local NodeJS. - if NodeJSFlag { - clientBuildStr, err := build.NodeClient(buildPath) - if err = common.CheckErr(err); err != nil { - return err - } - staticBuildStr, allNodesStr, err := build.NodeDataSource(buildPath, siteConfig) - if err = common.CheckErr(err); err != nil { - return err - } - - if err = common.CheckErr(build.NodeExec(clientBuildStr, staticBuildStr, allNodesStr)); err != nil { - return err - } - } else { - - // Prep the client SPA. - err = build.Client(buildPath, tempBuildDir, defaultsEjectedFS) - if err = common.CheckErr(err); err != nil { - return err - } - - // Build JSON from "content/" directory. - err = build.DataSource(buildPath, siteConfig, tempBuildDir) - if err = common.CheckErr(err); err != nil { - return err - } + // Prep the client SPA. + err = build.Client(buildPath, tempBuildDir, defaultsEjectedFS) + if err = common.CheckErr(err); err != nil { + return err + } + // Build JSON from "content/" directory. + err = build.DataSource(buildPath, siteConfig, tempBuildDir) + if err = common.CheckErr(err); err != nil { + return err } // Run Gopack (custom Snowpack alternative) for ESM support. @@ -186,8 +165,7 @@ func init() { // Cobra supports local flags which will only run when this command // is called directly, e.g.: // buildCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") - buildCmd.Flags().StringVarP(&BuildDirFlag, "dir", "d", "", "change name of the build directory") + buildCmd.Flags().StringVarP(&OutputDirFlag, "output", "o", "", "change name of the public build directory") buildCmd.Flags().BoolVarP(&VerboseFlag, "verbose", "v", false, "show log messages") buildCmd.Flags().BoolVarP(&BenchmarkFlag, "benchmark", "b", false, "display build time statistics") - buildCmd.Flags().BoolVarP(&NodeJSFlag, "nodejs", "n", false, "use system nodejs for build with ejectable build.js script") } diff --git a/cmd/build/client.go b/cmd/build/client.go index 3ee16a9b..c04c7c4c 100644 --- a/cmd/build/client.go +++ b/cmd/build/client.go @@ -30,8 +30,8 @@ func Client(buildPath string, tempBuildDir string, defaultsEjectedFS embed.FS) e stylePath := buildPath + "/spa/bundle.css" - // Initialize string for layout.js component list. - var allComponentsStr string + // Initialize string for layouts.js component list. + var allLayoutsStr string // Set up counter for logging output. compiledComponentCounter := 0 @@ -133,14 +133,14 @@ func Client(buildPath string, tempBuildDir string, defaultsEjectedFS embed.FS) e return err } - // Go through all file paths in the "/layout" folder. - err = filepath.Walk(tempBuildDir+"layout", func(layoutPath string, layoutFileInfo os.FileInfo, err error) error { + // Go through all file paths in the "/layouts" folder. + err = filepath.Walk(tempBuildDir+"layouts", func(layoutPath string, layoutFileInfo os.FileInfo, err error) error { if err != nil { return fmt.Errorf("can't stat %s: %w", layoutPath, err) } // Create destination path. - destFile := buildPath + "/spa" + strings.TrimPrefix(layoutPath, tempBuildDir+"layout") + destFile := buildPath + "/spa" + strings.TrimPrefix(layoutPath, tempBuildDir+"layouts") // Make sure path is a directory if layoutFileInfo.IsDir() { // Create any sub directories need for filepath. @@ -165,12 +165,12 @@ func Client(buildPath string, tempBuildDir string, defaultsEjectedFS embed.FS) e // Remove temporary theme build directory. destLayoutPath := strings.TrimPrefix(layoutPath, tempBuildDir) - // Create entry for layout.js. + // Create entry for layouts.js. layoutSignature := strings.ReplaceAll(strings.ReplaceAll((destLayoutPath), "/", "_"), ".", "_") - // Remove layout directory. - destLayoutPath = strings.TrimPrefix(destLayoutPath, "layout/") - // Compose entry for layout.js file. - allComponentsStr = allComponentsStr + "export {default as " + layoutSignature + "} from '../" + destLayoutPath + "';\n" + // Remove layouts directory. + destLayoutPath = strings.TrimPrefix(destLayoutPath, "layouts/") + // Compose entry for layouts.js file. + allLayoutsStr = allLayoutsStr + "export {default as " + layoutSignature + "} from '../" + destLayoutPath + "';\n" compiledComponentCounter++ @@ -184,10 +184,10 @@ func Client(buildPath string, tempBuildDir string, defaultsEjectedFS embed.FS) e } - // Write layout.js to filesystem. - err = ioutil.WriteFile(buildPath+"/spa/ejected/layout.js", []byte(allComponentsStr), os.ModePerm) + // Write layouts.js to filesystem. + err = ioutil.WriteFile(buildPath+"/spa/ejected/layouts.js", []byte(allLayoutsStr), os.ModePerm) if err != nil { - return fmt.Errorf("Unable to write layout.js file: %w%s", err, common.Caller()) + return fmt.Errorf("Unable to write layouts.js file: %w%s", err, common.Caller()) } @@ -349,7 +349,7 @@ func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, layoutPath string, if currentNamedImport != "" && importSignature != "" { // Only add named imports to create_ssr_component(). reCreateFunc := regexp.MustCompile(`(create_ssr_component\(\(.*\)\s=>\s\{)`) - // Entry should be block scoped, like: let count = layout_scripts_stores_svelte_count; + // Entry should be block scoped, like: let count = layouts_scripts_stores_svelte_count; blockScopedVar := "\n let " + currentNamedImport + " = " + importSignature + "_" + currentNamedImport + ";" // Add block scoped var inside create_ssr_component. ssrStr = reCreateFunc.ReplaceAllString(ssrStr, "${1}"+blockScopedVar) @@ -357,20 +357,20 @@ func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, layoutPath string, } } - // Remove allComponents object (leaving just componentSignature) for SSR. - // Match: allComponents.layout_components_grid_svelte - reAllComponentsDot := regexp.MustCompile(`allComponents\.(layout_.*_svelte)`) - ssrStr = reAllComponentsDot.ReplaceAllString(ssrStr, "${1}") - // Match: allComponents[component] - reAllComponentsBracket := regexp.MustCompile(`allComponents\[(.*)\]`) - ssrStr = reAllComponentsBracket.ReplaceAllString(ssrStr, "globalThis[${1}]") - // Match: allComponents["layout_components_decrementer_svelte"] - reAllComponentsBracketStr := regexp.MustCompile(`allComponents\[\"(.*)\"\]`) - ssrStr = reAllComponentsBracketStr.ReplaceAllString(ssrStr, "${1}") + // Remove allLayouts object (leaving just componentSignature) for SSR. + // Match: allLayouts.layouts_components_grid_svelte + reAllLayoutsDot := regexp.MustCompile(`allLayouts\.(layouts_.*_svelte)`) + ssrStr = reAllLayoutsDot.ReplaceAllString(ssrStr, "${1}") + // Match: allLayouts[component] + reAllLayoutsBracket := regexp.MustCompile(`allLayouts\[(.*)\]`) + ssrStr = reAllLayoutsBracket.ReplaceAllString(ssrStr, "globalThis[${1}]") + // Match: allLayouts["layouts_components_decrementer_svelte"] + reAllLayoutsBracketStr := regexp.MustCompile(`allLayouts\[\"(.*)\"\]`) + ssrStr = reAllLayoutsBracketStr.ReplaceAllString(ssrStr, "${1}") paginatedContent, _ := getPagination() for _, pager := range paginatedContent { - if "layout_content_"+pager.contentType+"_svelte" == componentSignature { + if "layouts_content_"+pager.contentType+"_svelte" == componentSignature { for _, paginationVar := range pager.paginationVars { // Prefix var so it doesn't conflict with other variables. globalVar := "plenti_global_pager_" + paginationVar @@ -437,7 +437,7 @@ func getPagination() ([]pager, *regexp.Regexp) { // Initialize new pager struct var pagers []pager // Check for pagination in plenti.json config file. - for configContentType, slug := range siteConfig.Types { + for configContentType, slug := range siteConfig.Routes { // Initialize list of all :paginate() vars in a given slug. replacements := []string{} // Find every instance of :paginate() in the slug. diff --git a/cmd/build/data_source.go b/cmd/build/data_source.go index ed979ec0..7a388f7a 100644 --- a/cmd/build/data_source.go +++ b/cmd/build/data_source.go @@ -151,16 +151,16 @@ func DataSource(buildPath string, siteConfig readers.SiteConfig, tempBuildDir st // Get field key/values from content source. typeFields := readers.GetTypeFields(fileContentBytes) // Setup regex to find field name. - reField := regexp.MustCompile(`:field\((.*?)\)`) + reField := regexp.MustCompile(`:fields\((.*?)\)`) // Check for path overrides from plenti.json config file. - for configContentType, slug := range siteConfig.Types { + for configContentType, slug := range siteConfig.Routes { if configContentType == contentType { // Replace :filename. slug = strings.Replace(slug, ":filename", strings.TrimSuffix(fileName, filepath.Ext(fileName)), -1) - // Replace :field(). + // Replace :fields(). fieldReplacements := reField.FindAllStringSubmatch(slug, -1) - // Loop through all :field() replacements found in config file. + // Loop through all :fields() replacements found in config file. for _, replacement := range fieldReplacements { // Loop through all top level keys found in content source file. for field, fieldValue := range typeFields.Fields { @@ -285,15 +285,15 @@ func DataSource(buildPath string, siteConfig readers.SiteConfig, tempBuildDir st } func createProps(currentContent content, allContentStr string) error { - routeSignature := "layout_content_" + currentContent.contentType + "_svelte" - _, err := SSRctx.RunScript("var props = {route: "+routeSignature+", content: "+currentContent.contentDetails+", allContent: "+allContentStr+"};", "create_ssr") + componentSignature := "layouts_content_" + currentContent.contentType + "_svelte" + _, err := SSRctx.RunScript("var props = {content: "+currentContent.contentDetails+", layout: "+componentSignature+", allContent: "+allContentStr+"};", "create_ssr") if err != nil { return fmt.Errorf("Could not create props: %w%s", err, common.Caller()) } // Render the HTML with props needed for the current content. - _, err = SSRctx.RunScript("var { html, css: staticCss} = layout_global_html_svelte.render(props);", "create_ssr") + _, err = SSRctx.RunScript("var { html, css: staticCss} = layouts_global_html_svelte.render(props);", "create_ssr") if err != nil { return fmt.Errorf("Can't render htmlComponent: %w%s", err, common.Caller()) diff --git a/cmd/build/eject_copy.go b/cmd/build/eject_copy.go index 6e233b0b..4c0febd3 100644 --- a/cmd/build/eject_copy.go +++ b/cmd/build/eject_copy.go @@ -30,19 +30,8 @@ func EjectCopy(buildPath string, tempBuildDir string, defaultsEjectedFS embed.FS if err != nil { return fmt.Errorf("can't stat %s: %w", ejectPath, err) } - // Make list of files not to copy to build. - excludedFiles := []string{ - "ejected/build.js", - } - // Check if the current file is in the excluded list. - excluded := false - for _, excludedFile := range excludedFiles { - if excludedFile == ejectPath { - excluded = true - } - } // If the file is already in .js format just copy it straight over to build dir. - if filepath.Ext(ejectPath) == ".js" && !excluded { + if filepath.Ext(ejectPath) == ".js" { destPath := buildPath + "/spa/" if err := os.MkdirAll(destPath+strings.TrimPrefix("ejected", tempBuildDir), os.ModePerm); err != nil { diff --git a/cmd/build/node_client.go b/cmd/build/node_client.go deleted file mode 100644 index 4f9a20f2..00000000 --- a/cmd/build/node_client.go +++ /dev/null @@ -1,74 +0,0 @@ -package build - -import ( - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/plentico/plenti/common" -) - -// NodeClient preps the client SPA for execution via NodeJS (NOTE: This is legacy functionality). -func NodeClient(buildPath string) (string, error) { - - defer Benchmark(time.Now(), "Prepping client SPA data") - - Log("\nPrepping client SPA for svelte compiler") - - stylePath := buildPath + "/spa/bundle.css" - - // Set up counter for logging output. - compiledComponentCounter := 0 - - // Start the string that will be sent to nodejs for compiling. - clientBuildStr := "[" - - // Go through all file paths in the "/layout" folder. - layoutFilesErr := filepath.Walk("layout", func(layoutPath string, layoutFileInfo os.FileInfo, err error) error { - if err != nil { - return fmt.Errorf("can't stat %s: %w", layoutPath, err) - } - // Create destination path. - destFile := buildPath + strings.Replace(layoutPath, "layout", "/spa", 1) - // Make sure path is a directory - if layoutFileInfo.IsDir() { - // Create any sub directories need for filepath. - if err = os.MkdirAll(destFile, os.ModePerm); err != nil { - return fmt.Errorf("cannot create sub directories need for filepath %s: %w%s", - destFile, err, common.Caller()) - } - } else { - // If the file is in .svelte format, compile it to .js - if filepath.Ext(layoutPath) == ".svelte" { - - // Replace .svelte file extension with .js. - destFile = strings.TrimSuffix(destFile, filepath.Ext(destFile)) + ".js" - - // Create string representing array of objects to be passed to nodejs. - clientBuildStr = clientBuildStr + "{ \"layoutPath\": \"" + layoutPath + "\", \"destPath\": \"" + destFile + "\", \"stylePath\": \"" + stylePath + "\"}," - - compiledComponentCounter++ - - } - } - return nil - }) - if layoutFilesErr != nil { - return "", fmt.Errorf("Could not get layout file: %w%s", layoutFilesErr, common.Caller()) - } - - // Get router from ejected core. NOTE if you remove this, trim the trailing comma below. - clientBuildStr = clientBuildStr + "{ \"layoutPath\": \"ejected/router.svelte\", \"destPath\": \"" + buildPath + "/spa/ejected/router.js\", \"stylePath\": \"" + stylePath + "\"}" - - // End the string that will be sent to nodejs for compiling. - //clientBuildStr = strings.TrimSuffix(clientBuildStr, ",") + "]" - clientBuildStr = clientBuildStr + "]" - - Log("Number of components to be compiled: " + strconv.Itoa(compiledComponentCounter)) - - return clientBuildStr, nil - -} diff --git a/cmd/build/node_data_source.go b/cmd/build/node_data_source.go deleted file mode 100644 index a73a1ab4..00000000 --- a/cmd/build/node_data_source.go +++ /dev/null @@ -1,197 +0,0 @@ -package build - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" - "time" - - "github.com/plentico/plenti/readers" -) - -// NodeDataSource gathers data json from "content/" directory to use in NodeJS build (NOTE: This is legacy). -func NodeDataSource(buildPath string, siteConfig readers.SiteConfig) (string, string, error) { - - defer Benchmark(time.Now(), "Creating data_source") - - Log("\nGathering data source from 'content/' folder") - - contentJSPath := buildPath + "/spa/ejected/content.js" - if err := os.MkdirAll(buildPath+"/spa/ejected", os.ModePerm); err != nil { - return "", "", err - } - - // Set up counter for logging output. - contentFileCounter := 0 - - // Start the string that will be sent to nodejs for compiling. - staticBuildStr := "[" - allContentStr := "[" - - // Start the new content.js file. - err := ioutil.WriteFile(contentJSPath, []byte(`const contentSource = [`), 0755) - if err != nil { - fmt.Printf("Unable to write content.js file: %v", err) - } - - // Go through all sub directories in "content/" folder. - contentFilesErr := filepath.Walk("content", func(path string, info os.FileInfo, err error) error { - - if err != nil { - return fmt.Errorf("can't stat %s: %w", path, err) - } - if !info.IsDir() { - // Get individual path arguments. - parts := strings.Split(path, "/") - contentType := parts[1] - fileName := parts[len(parts)-1] - - // Don't add _blueprint.json or other special named files starting with underscores. - if fileName[:1] != "_" && fileName[:1] != "." { - - // Get the contents of the file. - fileContentBytes, err := ioutil.ReadFile(path) - if err != nil { - fmt.Printf("Could not read content file: %s\n", err) - return err - } - fileContentStr := string(fileContentBytes) - - // Remove the "content" folder from path. - path = strings.TrimPrefix(path, "content") - - // Check for index file at any level. - if fileName == "index.json" { - // Remove entire filename from path. - path = strings.TrimSuffix(path, fileName) - // Remove trailing slash, unless it's the homepage. - if path != "/" && path[len(path)-1:] == "/" { - path = strings.TrimSuffix(path, "/") - } - } else { - // Remove file extension only from path for files other than index.json. - path = strings.TrimSuffix(path, filepath.Ext(path)) - } - - // Get field key/values from content source. - typeFields := readers.GetTypeFields(fileContentBytes) - // Setup regex to find field name. - reField := regexp.MustCompile(`:field\((.*?)\)`) - // Create regex for allowed characters when slugifying path. - reSlugify := regexp.MustCompile("[^a-z0-9/]+") - - // Check for path overrides from plenti.json config file. - for configContentType, slug := range siteConfig.Types { - if configContentType == contentType { - // Replace :filename. - slug = strings.Replace(slug, ":filename", strings.TrimSuffix(fileName, filepath.Ext(fileName)), -1) - - // Replace :field(). - fieldReplacements := reField.FindAllStringSubmatch(slug, -1) - // Loop through all :field() replacements found in config file. - for _, replacement := range fieldReplacements { - // Loop through all top level keys found in content source file. - for field, fieldValue := range typeFields.Fields { - // Check if field name in the replacement pattern is found in data source. - if replacement[1] == field { - // Use the field value in the path. - slug = strings.ReplaceAll(slug, replacement[0], fieldValue) - } - } - - } - - // Slugify output using reSlugify regex defined above. - slug = strings.Trim(reSlugify.ReplaceAllString(strings.ToLower(slug), "-"), "-") - path = slug - } - } - - // Add trailing slash. - //path = path + "/" - - // Check for files outside of a type declaration. - if len(parts) == 2 { - // Remove the extension since the filename = the type name. - contentType = strings.TrimSuffix(contentType, filepath.Ext(contentType)) - } - - destPath := buildPath + "/" + path + "/index.html" - - contentDetailsStr := "{\n" + - "\"path\": \"" + path + "\",\n" + - "\"type\": \"" + contentType + "\",\n" + - "\"filename\": \"" + fileName + "\",\n" + - "\"fields\": " + fileContentStr + "\n}" - - // Create new content.js file if it doesn't already exist, or add to it if it does. - contentJSFile, err := os.OpenFile(contentJSPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - fmt.Printf("Could not open content.js for writing: %s", err) - } - // Write to the file with info from current file in "/content" folder. - defer contentJSFile.Close() - if _, err := contentJSFile.WriteString(contentDetailsStr + ","); err != nil { - return err - } - - // Need to encode html so it can be send as string to NodeJS in exec.Command. - encodedContentDetails := contentDetailsStr - // Remove newlines. - reN := regexp.MustCompile(`\r?\n`) - encodedContentDetails = reN.ReplaceAllString(encodedContentDetails, " ") - // Remove tabs. - reT := regexp.MustCompile(`\t`) - encodedContentDetails = reT.ReplaceAllString(encodedContentDetails, " ") - // Reduce extra whitespace to a single space. - reS := regexp.MustCompile(`\s+`) - encodedContentDetails = reS.ReplaceAllString(encodedContentDetails, " ") - - // Add node info for being referenced in allContent object. - allContentStr = allContentStr + encodedContentDetails + "," - - // Create path for source .svelte template. - componentPath := "layout/content/" + contentType + ".svelte" - // Do not add a content source without a corresponding template to the build string. - if _, noEndpointErr := os.Stat(componentPath); os.IsNotExist(noEndpointErr) { - // The componentPath does not exist, go to the next content source. - // this is/should be an error? - return nil - } - // Add to list of data_source files for creating static HTML. - staticBuildStr = staticBuildStr + "{ \"content\": " + encodedContentDetails + ", \"componentPath\": \"" + componentPath + "\", \"destPath\": \"" + destPath + "\"}," - - // Increment counter for logging purposes. - contentFileCounter++ - - } - } - return nil - }) - if contentFilesErr != nil { - fmt.Printf("Could not get layout file: %s", contentFilesErr) - } - - // Complete the content.js file. - contentJSFile, err := os.OpenFile(contentJSPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - fmt.Printf("Could not open content.js for writing: %s", err) - return "", "", err - } - defer contentJSFile.Close() - if _, err := contentJSFile.WriteString("];\n\nexport default contentSource;"); err != nil { - return "", "", err - } - - // End the string that will be sent to nodejs for compiling. - staticBuildStr = strings.TrimSuffix(staticBuildStr, ",") + "]" - allContentStr = strings.TrimSuffix(allContentStr, ",") + "]" - - Log(fmt.Sprintf("Number of content files used: %d", contentFileCounter)) - - return staticBuildStr, allContentStr, nil - -} diff --git a/cmd/build/node_exec.go b/cmd/build/node_exec.go deleted file mode 100644 index 63fc2fcc..00000000 --- a/cmd/build/node_exec.go +++ /dev/null @@ -1,19 +0,0 @@ -package build - -import ( - "os" - "os/exec" - "time" -) - -// NodeExec runs a build script written in NodeJS that compiles svelte. -func NodeExec(clientBuildStr string, staticBuildStr string, allNodesStr string) error { - - defer Benchmark(time.Now(), "Compiling components and creating static HTML via NodeJS") - - svelteBuild := exec.Command("node", "ejected/build.js", clientBuildStr, staticBuildStr, allNodesStr) - svelteBuild.Stdout = os.Stdout - svelteBuild.Stderr = os.Stderr - return svelteBuild.Run() - -} diff --git a/cmd/defaults/ejected/build.js b/cmd/defaults/ejected/build.js deleted file mode 100644 index 80972967..00000000 --- a/cmd/defaults/ejected/build.js +++ /dev/null @@ -1,102 +0,0 @@ -import svelte from 'svelte/compiler.js'; -import 'svelte/register.js'; -import Module from 'module'; -import path from 'path'; -import fs from 'fs'; - -// Get the arguments from Go command execution. -const args = process.argv.slice(2) - -// ----------------- -// Helper Functions: -// ----------------- - -// Create any missing sub folders. -const ensureDirExists = filePath => { - let dirname = path.dirname(filePath); - if (fs.existsSync(dirname)) { - return true; - } - ensureDirExists(dirname); - fs.mkdirSync(dirname); -} - -// Concatenates HTML strings together. -const injectString = (order, content, element, html) => { - if (order == 'prepend') { - return html.replace(element, content + element); - } else if (order == 'append') { - return html.replace(element, element + content); - } -}; - -// ----------------------- -// Start client SPA build: -// ----------------------- - -let clientBuildStr = JSON.parse(args[0]); - -clientBuildStr.forEach(arg => { - - let layoutPath = path.join(path.resolve(), arg.layoutPath) - let component = fs.readFileSync(layoutPath, 'utf8'); - - // Create component JS that can run in the browser. - let { js, css } = svelte.compile(component, { - css: false, - hydratable: true - }); - - // Write JS to build directory. - ensureDirExists(arg.destPath); - fs.promises.writeFile(arg.destPath, js.code); - - // Write CSS to build directory. - ensureDirExists(arg.stylePath); - if (css.code && css.code != 'null') { - fs.appendFileSync(arg.stylePath, css.code); - } -}); - -// ------------------------ -// Start static HTML build: -// ------------------------ - -let staticBuildStr = JSON.parse(args[1]); -let allContent = JSON.parse(args[2]); - -// Create the component that wraps all content. -let htmlWrapper = path.join(path.resolve(), 'layout/global/html.svelte') -let root = new Module(); -let component = root.require(htmlWrapper).default; - -staticBuildStr.forEach(arg => { - - let componentPath = path.join(path.resolve(), arg.componentPath); - let destPath = path.join(path.resolve(), arg.destPath); - - // Set route used in svelte:component as "this" value. - const route = root.require(componentPath).default; - - // Set props so component can access field values, etc. - let props = { - route: route, - content: arg.content, - allContent: allContent - }; - - // Create the static HTML and CSS. - let { html, css } = component.render(props); - - // Inject Style. - let style = ""; - html = injectString('prepend', style, '', html); - // Inject SPA entry point. - let entryPoint = ''; - html = injectString('prepend', entryPoint, '', html); - - // Write .html file to filesystem. - ensureDirExists(destPath); - fs.promises.writeFile(destPath, html); - -}); \ No newline at end of file diff --git a/cmd/defaults/ejected/main.js b/cmd/defaults/ejected/main.js index db9aaffa..440b7f2d 100755 --- a/cmd/defaults/ejected/main.js +++ b/cmd/defaults/ejected/main.js @@ -1,9 +1,9 @@ import Router from './router.svelte'; import contentSource from './content.js'; -import * as allComponents from './layout.js'; +import * as allLayouts from './layouts.js'; let uri = location.pathname; -let route, content, allContent; +let layout, content, allContent; const getContent = (uri, trailingSlash = "") => { return contentSource.find(content => content.path + trailingSlash == uri); @@ -13,16 +13,16 @@ content = getContent(uri) != undefined ? getContent(uri) : getContent(uri, "/"); allContent = contentSource; import('../content/' + content.type + '.js').then(r => { - route = r.default; + layout = r.default; new Router({ target: document, hydrate: true, props: { uri: uri, - route: route, + layout: layout, content: content, allContent: allContent, - allComponents: allComponents + allLayouts: allLayouts } }); }).catch(e => console.log(e)); \ No newline at end of file diff --git a/cmd/defaults/ejected/router.svelte b/cmd/defaults/ejected/router.svelte index dd4372de..f2e4bec9 100755 --- a/cmd/defaults/ejected/router.svelte +++ b/cmd/defaults/ejected/router.svelte @@ -1,11 +1,11 @@ - + - + \ No newline at end of file diff --git a/cmd/defaults/starters/learner/content/blog/components.json b/cmd/defaults/starters/learner/content/blog/components.json index 07b53d6f..4f216f3a 100644 --- a/cmd/defaults/starters/learner/content/blog/components.json +++ b/cmd/defaults/starters/learner/content/blog/components.json @@ -1,9 +1,9 @@ { "title": "Dynamic components example", "body": [ - "The allComponents helper object holds references to all svelte templates on your site.", + "The allLayouts helper object holds references to all svelte templates on your site.", "This allows you to load components from your JSON data source without explicitly importing them.", - "Just remember to use a component signature (e.g. layout/components/ball.svelte becomes layout_components_ball_svelte)." + "Just remember to use a component signature (e.g. layouts/components/ball.svelte becomes layouts_components_ball_svelte)." ], "components": [ { diff --git a/cmd/defaults/starters/learner/layout/components/ball.svelte b/cmd/defaults/starters/learner/layouts/components/ball.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/ball.svelte rename to cmd/defaults/starters/learner/layouts/components/ball.svelte diff --git a/cmd/defaults/starters/learner/layout/components/block.svelte b/cmd/defaults/starters/learner/layouts/components/block.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/block.svelte rename to cmd/defaults/starters/learner/layouts/components/block.svelte diff --git a/cmd/defaults/starters/learner/layout/components/decrementer.svelte b/cmd/defaults/starters/learner/layouts/components/decrementer.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/decrementer.svelte rename to cmd/defaults/starters/learner/layouts/components/decrementer.svelte diff --git a/cmd/defaults/starters/learner/layout/components/grid.svelte b/cmd/defaults/starters/learner/layouts/components/grid.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/grid.svelte rename to cmd/defaults/starters/learner/layouts/components/grid.svelte diff --git a/cmd/defaults/starters/learner/layout/components/incrementer.svelte b/cmd/defaults/starters/learner/layouts/components/incrementer.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/incrementer.svelte rename to cmd/defaults/starters/learner/layouts/components/incrementer.svelte diff --git a/cmd/defaults/starters/learner/layout/components/pager.svelte b/cmd/defaults/starters/learner/layouts/components/pager.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/components/pager.svelte rename to cmd/defaults/starters/learner/layouts/components/pager.svelte diff --git a/cmd/defaults/starters/learner/layout/components/source.svelte b/cmd/defaults/starters/learner/layouts/components/source.svelte similarity index 96% rename from cmd/defaults/starters/learner/layout/components/source.svelte rename to cmd/defaults/starters/learner/layouts/components/source.svelte index 51a0ec97..20cc23ba 100644 --- a/cmd/defaults/starters/learner/layout/components/source.svelte +++ b/cmd/defaults/starters/learner/layouts/components/source.svelte @@ -21,7 +21,7 @@
Template:
-    layout/content/{content.type}.svelte
+    layouts/content/{content.type}.svelte
     
   
diff --git a/cmd/defaults/starters/learner/layout/content/404.svelte b/cmd/defaults/starters/learner/layouts/content/404.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/content/404.svelte rename to cmd/defaults/starters/learner/layouts/content/404.svelte diff --git a/cmd/defaults/starters/learner/layout/content/blog.svelte b/cmd/defaults/starters/learner/layouts/content/blog.svelte similarity index 87% rename from cmd/defaults/starters/learner/layout/content/blog.svelte rename to cmd/defaults/starters/learner/layouts/content/blog.svelte index da69ac0f..06ea1362 100755 --- a/cmd/defaults/starters/learner/layout/content/blog.svelte +++ b/cmd/defaults/starters/learner/layouts/content/blog.svelte @@ -12,7 +12,7 @@ }); // Content driven dynamic components example: - export let components, allComponents; + export let components, allLayouts;

{title}

@@ -33,7 +33,7 @@ {#if components} {#each components as { name }} - + {/each} {/if} diff --git a/cmd/defaults/starters/learner/layout/content/index.svelte b/cmd/defaults/starters/learner/layouts/content/index.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/content/index.svelte rename to cmd/defaults/starters/learner/layouts/content/index.svelte diff --git a/cmd/defaults/starters/learner/layout/content/pages.svelte b/cmd/defaults/starters/learner/layouts/content/pages.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/content/pages.svelte rename to cmd/defaults/starters/learner/layouts/content/pages.svelte diff --git a/cmd/defaults/starters/learner/layout/global/footer.svelte b/cmd/defaults/starters/learner/layouts/global/footer.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/global/footer.svelte rename to cmd/defaults/starters/learner/layouts/global/footer.svelte diff --git a/cmd/defaults/starters/learner/layout/global/head.svelte b/cmd/defaults/starters/learner/layouts/global/head.svelte similarity index 100% rename from cmd/defaults/starters/learner/layout/global/head.svelte rename to cmd/defaults/starters/learner/layouts/global/head.svelte diff --git a/cmd/defaults/starters/learner/layout/global/html.svelte b/cmd/defaults/starters/learner/layouts/global/html.svelte similarity index 90% rename from cmd/defaults/starters/learner/layout/global/html.svelte rename to cmd/defaults/starters/learner/layouts/global/html.svelte index 17f08dff..6cee4000 100755 --- a/cmd/defaults/starters/learner/layout/global/html.svelte +++ b/cmd/defaults/starters/learner/layouts/global/html.svelte @@ -4,7 +4,7 @@ import Footer from './footer.svelte'; import { makeTitle } from '../scripts/make_title.svelte'; - export let route, content, allContent, allComponents; + export let content, layout, allContent, allLayouts; @@ -13,7 +13,7 @@