mosaic 1.0.9 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md ADDED
@@ -0,0 +1,19 @@
1
+ # Design
2
+
3
+ two types of components.
4
+
5
+ those without js factory will not be defined but styles still loaded in the same way.
6
+
7
+ this allows you to define components effectively as HTML/CSS partials whilst still using bindings from the root component, because you don't necessarily want everything to expose a public api down the tree, sometimes you just want to break things up a bit.
8
+
9
+ ## component loading
10
+
11
+ each folder has - an index.js which return the factory as default export - an index.html which has the template - (optional) and index.css file that contains component-specific styles
12
+
13
+ we want...something like an entry module which will return { js, html, css } or { factory, template, styles } that we can then import mosaic once and define each component
14
+
15
+ we can easily serve an entry module over an api endpoint for dev, but these entry modules also need to be written to disk as part of the build.
16
+
17
+ possible approaches...
18
+
19
+ 1. script that enumerates the components, loading the source code via the api endpoint, and then saves to disk. yea, why not.
package/README.md CHANGED
@@ -1,73 +1,7 @@
1
1
  # mosaic
2
2
 
3
- ## [![npm](https://img.shields.io/npm/v/mosaic.svg)](http://npm.im/mosaic) [![Build Status](https://travis-ci.com/defx/mosaic.svg?branch=master)](https://travis-ci.com/defx/mosaic) [![Coverage Status](https://coveralls.io/repos/github/defx/mosaic/badge.svg?branch=master)](https://coveralls.io/github/defx/mosaic?branch=master) [![gzip size](https://img.badgesize.io/https://unpkg.com/mosaic/dist/mosaic.min.js?compression=gzip&label=gzip)]()
4
-
5
- Mosaic is a framework for building user interfaces for the web
6
-
7
- ## Features
8
-
9
- - Simple templates for declarative data & event binding
10
- - Reactive data bindings update your view efficiently and
11
- automatically
12
- - Full component workflow using standard Custom Elements
13
- - Small footprint (~4k)
14
- - No special compiler, plugins, required
15
- - Minimal learning curve (almost entirely standard HTML, JS,
16
- and CSS!)
17
- - Interoperable with other libraries and frameworks
18
-
19
- [Learn how to use Mosaic in your own project](https://mosaicjs.org/learn/introduction).
20
-
21
- ## Installation
22
-
23
- Mosaic is available from npm:
24
-
25
- ```bash
26
- $ npm i mosaic
27
- ```
28
-
29
- You can also import Mosaic directly in the browser via CDN:
30
-
31
- ```html
32
- <script type="module">
33
- import { define } from "https://unpkg.com/mosaic@1.0.4"
34
- </script>
35
- ```
36
-
37
- ## Browser Support
38
-
39
- (todo)
3
+ 🚧 This library is currently under construction and not ready for public use 🚧
40
4
 
41
- ## Documentation
42
-
43
- (todo)
44
-
45
- ## Example
46
-
47
- ### Step 1. Define your custom element
48
-
49
- ```html
50
- <script type="module">
51
- import { define } from "https://unpkg.com/mosaic@1.0.4"
52
-
53
- define("hello-world", () => ({ name }), "<p>Hello {{ name }}!</p>")
54
- </script>
55
- ```
56
-
57
- ### Step 2. Use the Custom Element
58
-
59
- ```html
60
- <hello-world name="kimberley"></hello-world>
61
- ```
62
-
63
- This example will render "Hello Kimberley!" into a container
64
- on the page.
65
-
66
- You'll notice that everything here is valid HTML and JS, and
67
- you can copy and paste this example and run it directly in
68
- the browser with no need to compile or install anything
69
- special to make it work.
70
-
71
- ### License
5
+ ## [![npm](https://img.shields.io/npm/v/mosaic.svg)](http://npm.im/mosaic) [![Build Status](https://travis-ci.com/defx/mosaic.svg?branch=master)](https://travis-ci.com/defx/mosaic) [![Coverage Status](https://coveralls.io/repos/github/defx/mosaic/badge.svg?branch=master)](https://coveralls.io/github/defx/mosaic?branch=master) [![gzip size](https://img.badgesize.io/https://unpkg.com/mosaic/dist/mosaic.min.js?compression=gzip&label=gzip)]()
72
6
 
73
- Mosaic is [MIT licensed](./LICENSE).
7
+ Mosaic is CLI for building web sites and apps with Synergy components
package/SCRATCH.md ADDED
@@ -0,0 +1,58 @@
1
+ ## By Feature
2
+
3
+ - declarative data and event binding
4
+
5
+ - functional state management
6
+
7
+ - highly predictable and testable
8
+ - integrated into the component model so that the same solution used for managing the state of a single component can also be used as a central "state container" for a larger tree of components
9
+ - components can broadcast actions publicly or privately, making light work of component intercoms
10
+
11
+ - Simple yet powerful CLI
12
+
13
+ - build components and pages with plain .html, .css, and .js files
14
+
15
+ - separation of concerns
16
+
17
+ - declarative / logic-less templates
18
+
19
+ - no javascript knowledge required to work on the template
20
+ - can be expressed in pure HTML / no compiler necessary
21
+
22
+ - sensible constraints
23
+
24
+ ## By Goal
25
+
26
+ > one of the nice qualities of the Mosaic framework design is that everything can be expressed using standard HTML, CSS, and JS without requiring any compilation or transpilation. of course, you can still use a transpiler if you specifically _want_ to use js that isn't part of the language yet, but it isn't required in any way.
27
+
28
+ - The CLI allows you to get even closer to the metal by writing your components in plain .html, .css, and .js
29
+
30
+ components/
31
+ app/
32
+ index.html
33
+ index.css
34
+ index.js
35
+ header/
36
+ index.html
37
+ index.css
38
+ index.js
39
+ footer/
40
+ index.html
41
+ index.css
42
+ index.js
43
+
44
+ the CLI simply generates an entry module that defines a Mosaic component from the raw html, css, and js files.
45
+
46
+ - With the CLI, components can be _active_ (control their own state) or _passive_ (have no state of their own). Think of Passive components like HTML includes, because sometimes you just want to reuse chunks of HTML and/or CSS without having to wire tens to hundreds of components together with props. When the CLI sees a component that has no .js file, it assumes this to be a _passive_ component and simply rolls it into the component that included it. the child and parent share the same scope meaning that all data values available in the parent are also available in the child without any prop wiring required.
47
+
48
+ components/
49
+ app/
50
+ index.html
51
+ index.css
52
+ index.js
53
+ header/
54
+ index.html
55
+ index.css
56
+ footer/
57
+ index.html
58
+ index.css
package/css.js ADDED
@@ -0,0 +1,71 @@
1
+ import path from "path"
2
+
3
+ import postcss from "postcss"
4
+ import atImport from "postcss-import"
5
+
6
+ export function resolveImports(css, filepath) {
7
+ return postcss()
8
+ .use(atImport())
9
+ .process(css, {
10
+ from: filepath,
11
+ })
12
+ .then(({ css }) => css)
13
+ }
14
+
15
+ function nextWord(css, count) {
16
+ return css.slice(count - 1).split(/[\s+|\n+|,]/)[0]
17
+ }
18
+
19
+ export function prefixSelectors(prefix, css) {
20
+ let insideBlock = false
21
+ let look = true
22
+ let output = ""
23
+ let count = 0
24
+
25
+ for (let char of css) {
26
+ if (char === "}") {
27
+ insideBlock = false
28
+ look = true
29
+ } else if (char === ",") {
30
+ look = true
31
+ } else if (char === "{") {
32
+ insideBlock = true
33
+ } else if (look && !insideBlock && !char.match(/\s/)) {
34
+ let w = nextWord(css, count + 1)
35
+
36
+ // console.log({ w })
37
+
38
+ if (
39
+ w !== prefix &&
40
+ w.charAt(0) !== "@" &&
41
+ w.charAt(0) !== ":" &&
42
+ w.charAt(0) !== "*" &&
43
+ w !== "html" &&
44
+ w !== "body"
45
+ ) {
46
+ output += prefix + " "
47
+ }
48
+ look = false
49
+ }
50
+ output += char
51
+ count += 1
52
+ }
53
+
54
+ return output
55
+ }
56
+
57
+ function tagName(v) {
58
+ return path.dirname(v.filepath).split(path.sep).pop()
59
+ }
60
+
61
+ export function scopeComponentCSSWithElementSelectors(v) {
62
+ return {
63
+ ...v,
64
+ componentCSS: v.componentCSS.map((v) => {
65
+ return {
66
+ ...v,
67
+ content: prefixSelectors(tagName(v), v.content),
68
+ }
69
+ }),
70
+ }
71
+ }
package/helix.js ADDED
@@ -0,0 +1,40 @@
1
+ import chokidar from "chokidar"
2
+ import fs from "fs-extra"
3
+ import glob from "glob-promise"
4
+ import path from "path"
5
+
6
+ export const helix = (config) => {
7
+ const cache = {}
8
+
9
+ const updateCache = (key, filepath) =>
10
+ fs.promises.readFile(filepath, "utf8").then((content) => {
11
+ let { transform = {} } = config
12
+ ;(transform[key] || [])
13
+ .reduce((p, f) => p.then(f), Promise.resolve({ content, filepath }))
14
+ .then((v) => {
15
+ cache[key][filepath] = v
16
+ transform.afterEach?.(v, cache)
17
+ })
18
+ })
19
+
20
+ const populateCache = () =>
21
+ Promise.all(
22
+ Object.entries(config.input).map(([key, globPath]) => {
23
+ cache[key] = {}
24
+ return glob(globPath).then((paths) =>
25
+ Promise.all(paths.map((f) => updateCache(key, path.normalize(f))))
26
+ )
27
+ })
28
+ )
29
+
30
+ return populateCache().then(() => {
31
+ if (config.watch) {
32
+ Object.entries(config.input).forEach(([key, glob]) => {
33
+ chokidar.watch(glob).on("change", (filepath) => {
34
+ updateCache(key, filepath)
35
+ })
36
+ })
37
+ }
38
+ return cache
39
+ })
40
+ }
package/helpers.js ADDED
@@ -0,0 +1,67 @@
1
+ import fs from "fs-extra"
2
+ import path from "path"
3
+
4
+ export async function write({ filepath, content }) {
5
+ return fs
6
+ .ensureDir(path.dirname(filepath))
7
+ .then(() => fs.promises.writeFile(filepath, content))
8
+ }
9
+
10
+ export const tagName = (filepath) => {
11
+ return path.dirname(filepath).split(path.sep).pop()
12
+ }
13
+
14
+ const ANON = /<([a-z]\w*-\w*)/gm
15
+
16
+ export function customTags(html = "") {
17
+ return (html.match(ANON) || []).map((v) => v.slice(1))
18
+ }
19
+
20
+ export function resolveTagNames(
21
+ component,
22
+ components,
23
+ o = { [component.tagName]: true },
24
+ f = true
25
+ ) {
26
+ for (let k of component.tags) {
27
+ let c = components.find(({ tagName }) => tagName === k)
28
+ if (c && !(k in o)) {
29
+ o[k] = true
30
+ o = resolveTagNames(c, components, o, false)
31
+ }
32
+ }
33
+ return f ? Object.keys(o) : o
34
+ }
35
+
36
+ export function groupBy(key, arr) {
37
+ return arr.reduce((a, v) => {
38
+ let k = v[key]
39
+ a[k] = a[k] || []
40
+ a[k].push(v)
41
+ return a
42
+ }, {})
43
+ }
44
+
45
+ export function withTemplate({ filepath, content }) {
46
+ return `
47
+ <template id="${tagName(filepath)}">
48
+ ${content}
49
+ </template>
50
+ `
51
+ }
52
+
53
+ export const splice = (str, START_MARKER, END_MARKER) => {
54
+ let start = str.indexOf(START_MARKER)
55
+
56
+ if (start === -1) return str
57
+
58
+ let end = str.indexOf(END_MARKER, start)
59
+
60
+ if (end === -1) return str
61
+
62
+ return splice(
63
+ str.slice(0, start) + str.slice(end + END_MARKER.length),
64
+ START_MARKER,
65
+ END_MARKER
66
+ )
67
+ }
package/index.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from "path"
4
+ import { start } from "./server.js"
5
+
6
+ const [cmd] = process.argv.slice(2)
7
+
8
+ switch (cmd) {
9
+ default: {
10
+ import(path.resolve("./mosaic.config.js")).then(({ default: config }) =>
11
+ start(config)
12
+ )
13
+ break
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,53 +1,27 @@
1
1
  {
2
2
  "name": "mosaic",
3
- "version": "1.0.9",
4
- "description": "The Web UI Framework",
5
- "main": "dist/mosaic.min.js",
6
- "browser": "dist/mosaic.min.js",
7
- "unpkg": "dist/mosaic.min.js",
8
- "module": "src/index.js",
9
- "types": "types/index.d.ts",
10
- "files": [
11
- "src",
12
- "dist",
13
- "cjs"
14
- ],
15
- "directories": {
16
- "test": "test"
17
- },
3
+ "type": "module",
4
+ "version": "1.0.12",
5
+ "description": "",
6
+ "main": "index.js",
18
7
  "scripts": {
19
- "test": "mocha-express --coverage",
20
- "test:watch": "mocha-express --watch",
21
- "build": "rm -rf dist && rollup -c && npm run size",
22
- "size": "gzip -c9 ./dist/mosaic.min.js | wc -c",
23
- "coveralls": "cat ./coverage/lcov-report/lcov.info | coveralls",
24
- "prepublishOnly": "npm t && npm run build",
25
- "release": "npm t && standard-version"
26
- },
27
- "repository": {
28
- "type": "git",
29
- "url": "git+https://github.com/defx/mosaic.git"
8
+ "test": "echo \"Error: no test specified\" && exit 1"
30
9
  },
31
- "keywords": [
32
- "simple",
33
- "declarative",
34
- "dom",
35
- "ui",
36
- "user interface",
37
- "web components",
38
- "framework"
39
- ],
40
- "author": "Matt Donkin",
10
+ "keywords": [],
11
+ "author": "",
41
12
  "license": "MIT",
42
- "bugs": {
43
- "url": "https://github.com/defx/mosaic/issues"
13
+ "dependencies": {
14
+ "chokidar": "^3.5.3",
15
+ "express": "^4.17.3",
16
+ "fs-extra": "^10.0.1",
17
+ "glob": "^7.2.0",
18
+ "glob-promise": "^4.2.2",
19
+ "html-minifier-terser": "^7.0.0-alpha.2",
20
+ "http-proxy-middleware": "^2.0.5",
21
+ "postcss": "^8.4.14",
22
+ "postcss-import": "^14.1.0"
44
23
  },
45
- "homepage": "https://github.com/defx/mosaic",
46
- "devDependencies": {
47
- "coveralls": "^3.1.0",
48
- "mocha-express": "^0.1.2",
49
- "rollup": "^2.26.4",
50
- "rollup-plugin-terser": "^7.0.1",
51
- "standard-version": "^9.1.1"
24
+ "bin": {
25
+ "mosaic": "index.js"
52
26
  }
53
27
  }
package/router.js ADDED
@@ -0,0 +1,33 @@
1
+ export function matchRoute(pathname, routes) {
2
+ let a = pathname.split("/")
3
+ for (let route of routes) {
4
+ let b = (route.match || "").split("/")
5
+ if (b.length !== a.length) continue
6
+ if (b.every((x, i) => x.charAt(0) === ":" || x === a[i])) {
7
+ return route
8
+ }
9
+ }
10
+ }
11
+
12
+ export function getParamsAsObject(pathname, route) {
13
+ let a = pathname.split("/")
14
+ let b = route.match.split("/")
15
+ return b.reduce((o, k, i) => {
16
+ if (k.charAt(0) === ":") {
17
+ o[k.slice(1)] = a[i]
18
+ }
19
+ return o
20
+ }, {})
21
+ }
22
+
23
+ export function getParams(pathname, route) {
24
+ let a = pathname.split("/")
25
+ let b = route.match.split("/")
26
+ let result = ""
27
+ b.forEach((k, i) => {
28
+ if (k.charAt(0) === ":") {
29
+ result += ` ${k.slice(1)}="${a[i]}"`
30
+ }
31
+ })
32
+ return result
33
+ }
package/server.js ADDED
@@ -0,0 +1,186 @@
1
+ import path from "path"
2
+ import express from "express"
3
+
4
+ import { helix } from "./helix.js"
5
+ import { prefixSelectors, resolveImports } from "./css.js"
6
+ import { tagName, customTags, resolveTagNames } from "./helpers.js"
7
+ import { matchRoute, getParams } from "./router.js"
8
+ import { createProxyMiddleware } from "http-proxy-middleware"
9
+
10
+ export const start = async (config) => {
11
+ let port = config.port || 3000
12
+ let app = express()
13
+
14
+ let components = await helix({
15
+ watch: true,
16
+ input: {
17
+ mosaicjs: "./node_modules/synergy/dist/synergy.js",
18
+ html: "./components/**/index.html",
19
+ css: "./components/**/index.css",
20
+ js: "./components/**/index.js",
21
+ },
22
+ transform: {
23
+ html: [
24
+ (v) => {
25
+ let { filepath, content } = v
26
+
27
+ return {
28
+ ...v,
29
+ tags: customTags(content),
30
+ tagName: tagName(filepath),
31
+ }
32
+ },
33
+ ],
34
+ css: [
35
+ (v) => {
36
+ let { filepath, content } = v
37
+ return {
38
+ ...v,
39
+ content: prefixSelectors(tagName(filepath), content),
40
+ }
41
+ },
42
+ ],
43
+ js: [],
44
+ synergyjs: [],
45
+ afterEach: (v, cache) => {
46
+ let { filepath } = v
47
+ let k = tagName(filepath)
48
+ let ext = path.extname(filepath).slice(1)
49
+ cache[k] = cache[k] || {}
50
+ cache[k][ext] = v
51
+ },
52
+ },
53
+ })
54
+
55
+ app.use("/components", express.static("components"))
56
+ app.use(express.static("public"))
57
+
58
+ function expandPartials(html) {
59
+ let tags = customTags(html)
60
+
61
+ for (let tag of tags) {
62
+ if (components[tag] && !components[tag].js && components[tag].html) {
63
+ // this component has no js module so lets treat it as a partial...
64
+ html = html.replaceAll(
65
+ `</${tag}>`,
66
+ `${expandPartials(components[tag].html.content)}</${tag}>`
67
+ )
68
+ }
69
+ }
70
+ return html
71
+ }
72
+
73
+ app.get("/components/:id/entry.js", (req, res, next) => {
74
+ let name = req.params.id
75
+
76
+ if (name in components) {
77
+ let component = components[name]
78
+
79
+ let tags = resolveTagNames(component.html, Object.values(components.html))
80
+
81
+ res.type(".js")
82
+ res.send(`
83
+ import factory from "./index.js";
84
+ const template = \`${expandPartials(component.html.content, tags)}\`;
85
+ export { factory, template }
86
+ `)
87
+ } else {
88
+ next()
89
+ }
90
+ })
91
+
92
+ app.get("/synergy.js", (_, res) => {
93
+ res.type(".js")
94
+ res.send(
95
+ components.synergyjs["node_modules/synergy/dist/synergy.js"].content
96
+ )
97
+ })
98
+
99
+ app.use(async function (req, res, next) {
100
+ let k = "/" + req.originalUrl.split("?")[0].replace(/^\/|\/$/g, "")
101
+
102
+ let route = matchRoute(k, config.routes)
103
+
104
+ if (!route) return next()
105
+
106
+ let params = getParams(k, route)
107
+
108
+ let templates = Object.values(components.html)
109
+
110
+ let pageTemplate = templates.find(
111
+ ({ tagName }) => tagName === route.component
112
+ )
113
+
114
+ let tagNames = resolveTagNames(pageTemplate, templates)
115
+
116
+ if (config.wrapper) tagNames.unshift(config.wrapper)
117
+
118
+ let cssComponents = tagNames.reduce((styles, t) => {
119
+ let x = Object.values(components.css).find(
120
+ ({ filepath }) => tagName(filepath) === t
121
+ )
122
+ if (x) styles.push(x)
123
+ return styles
124
+ }, [])
125
+
126
+ let componentStyles = ""
127
+
128
+ for (let { content, filepath } of cssComponents) {
129
+ let css = await resolveImports(content, filepath)
130
+ componentStyles += css
131
+ }
132
+
133
+ let componentHTML = `<${route.component}${params}></${route.component}>`
134
+
135
+ let html = `
136
+ <!DOCTYPE html>
137
+ <html lang="en">
138
+ <head>
139
+ <meta charset="UTF-8">
140
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
141
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
142
+ <style>${componentStyles}</style>
143
+ </head>
144
+ <body>
145
+
146
+ ${componentHTML}
147
+ <script type="module">
148
+
149
+ import { define } from "/synergy.js";
150
+
151
+ ${JSON.stringify(
152
+ tagNames.filter((name) => components[name].js)
153
+ )}.forEach(name => import(\`/components/\${name}/entry.js\`).then(({ factory, template }) => define(name, factory, template)));
154
+ </script>
155
+ </body>
156
+ </html>
157
+ `
158
+
159
+ res.send(html)
160
+ })
161
+
162
+ app.use("/node_modules", express.static("node_modules"))
163
+
164
+ app.use(
165
+ "/api",
166
+ createProxyMiddleware({
167
+ target: {
168
+ host: "localhost",
169
+ port: 4000,
170
+ },
171
+ secure: false,
172
+ pathRewrite: {
173
+ [`^/api`]: "",
174
+ },
175
+ })
176
+ )
177
+
178
+ app.listen(port, () =>
179
+ console.log(`Express server listening on port ${port}`)
180
+ )
181
+
182
+ return {
183
+ config,
184
+ components,
185
+ }
186
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2020 Matt Donkin
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.