mosaic 1.0.20 → 1.1.0

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/src/index.js CHANGED
@@ -1,76 +1,38 @@
1
- #!/usr/bin/env node
2
-
3
- import { customElementIncludes } from "customelementincludes"
4
- import fs from "fs-extra"
5
- import express from "express"
6
- import { globby } from "globby"
7
- import hljs from "highlight.js"
8
- import MarkdownIt from "markdown-it"
9
-
10
- // import postcss from "postcss"
11
- // import prefixer from "postcss-prefix-selector"
12
- import { decapitate } from "./head.js"
13
- import { document } from "./document.js"
14
-
15
- let md = new MarkdownIt({
16
- html: true,
17
- highlight: function (str, language) {
18
- if (language && hljs.getLanguage(language)) {
19
- try {
20
- return (
21
- '<pre class="hljs"><code>' +
22
- hljs.highlight(str, { language, ignoreIllegals: true }).value +
23
- "</code></pre>"
24
- )
25
- } catch (__) {}
26
- }
27
- return (
28
- '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
29
- )
30
- },
31
- })
32
-
33
- ;(async () => {
34
- const app = express()
35
- const port = process.env.port || 3000
36
-
37
- app.use(express.static("public"))
38
-
39
- app.use("/components", express.static("components"))
40
-
41
- app.use(async function (req, res, next) {
42
- if (req.originalUrl.includes(".")) return next()
43
-
44
- const route = req.originalUrl.split("?")[0]
45
-
46
- const [filepath] = await globby([
47
- `./pages${route === "/" ? "/index" : route}.(md|html)`,
48
- ])
49
-
50
- if (!filepath) return next()
51
-
52
- const contents = await fs.readFile(filepath, "utf8")
1
+ import { initialise } from "./initialise.js"
2
+ import { Store } from "./store.js"
3
+ import { Message } from "./message.js"
4
+
5
+ export const Mosaic = (node, config) => {
6
+ let nextTickSubscribers = []
7
+
8
+ const api = {
9
+ nextTick: (fn) => nextTickSubscribers.push(fn),
10
+ }
11
+
12
+ const message = Message({
13
+ postPublish: () => {
14
+ nextTickSubscribers.forEach((fn) => fn(state))
15
+ nextTickSubscribers = []
16
+ },
17
+ })
53
18
 
54
- let html = ""
19
+ const onChangeCallback = (state) => message.publish(state, config)
55
20
 
56
- if (contents.includes("<!DOCTYPE")) {
57
- html = contents
58
- } else {
59
- const result = decapitate(contents)
60
- const head = result.head
61
- const main =
62
- path.extname(filepath) === ".md" ? md.render(result.body) : result.body
21
+ const store = Store({
22
+ ...config,
23
+ api,
24
+ onChangeCallback,
25
+ })
63
26
 
64
- html = document({
65
- head,
66
- main,
67
- })
68
- }
27
+ const initialState = initialise(node, message.subscribe, config, store)
69
28
 
70
- res.send(await customElementIncludes(html))
29
+ store.set({
30
+ ...(config.state || {}),
31
+ ...initialState,
71
32
  })
33
+ onChangeCallback(store.getState())
72
34
 
73
- app.listen(port, () => {
74
- console.log(`Server running on port ${port}`)
75
- })
76
- })()
35
+ return store
36
+ }
37
+
38
+ export const $ = Mosaic
@@ -0,0 +1,112 @@
1
+ import { listItems, listData, listSync } from "./list.js"
2
+ import { write } from "./xo.js"
3
+
4
+ export function initialise(rootNode, subscribe, config, store, state = {}) {
5
+ const event = {}
6
+
7
+ const { elements = [] } = config
8
+
9
+ // derive initial state from input directives...
10
+ elements
11
+ .filter(({ input }) => input)
12
+ .forEach(({ select, input }) => {
13
+ const targets = [...rootNode.querySelectorAll(select)]
14
+ targets.forEach((target) => {
15
+ state = { ...state, [input]: target.value }
16
+
17
+ event.input = event.input || []
18
+ event.input.push({
19
+ select,
20
+ callback: (event) => {
21
+ const { target } = event
22
+ store.merge({ [input]: target.value })
23
+ },
24
+ })
25
+ })
26
+ })
27
+
28
+ // find event listeners
29
+ elements.forEach((c) => {
30
+ const { select, on } = c
31
+ if (on) {
32
+ Object.entries(on).forEach(([type, callback]) => {
33
+ event[type] = event[type] || []
34
+ event[type].push({
35
+ select,
36
+ callback,
37
+ })
38
+ })
39
+ }
40
+ })
41
+
42
+ //derive initial state from lists...
43
+ elements
44
+ .filter(({ list }) => list)
45
+ .forEach(({ select, list }) => {
46
+ const targets = [...rootNode.querySelectorAll(select)]
47
+ targets.forEach((target) => {
48
+ const items = listItems(target, list.select)
49
+ const curr = listData(items)
50
+ state[list.from] = curr
51
+ })
52
+ })
53
+
54
+ // delegate from the root node
55
+ Object.entries(event).forEach(([type, listeners]) => {
56
+ rootNode.addEventListener(type, (e) => {
57
+ listeners
58
+ .filter(({ select }) => e.target.matches(select))
59
+ .forEach(({ select, callback }) => {
60
+ if (typeof callback === "function") {
61
+ callback(e, store)
62
+ }
63
+ if (typeof callback === "string") {
64
+ const { target } = e
65
+
66
+ const targets = [...rootNode.querySelectorAll(select)]
67
+
68
+ const index = targets.indexOf(target)
69
+
70
+ store.dispatch(callback, { event: e, index })
71
+ }
72
+ })
73
+ })
74
+ })
75
+
76
+ const onChange = (state) => {
77
+ // lists first
78
+ elements
79
+ .filter(({ list }) => list)
80
+ .forEach(({ select, list }) => {
81
+ const targets = [...rootNode.querySelectorAll(select)]
82
+ targets.forEach((target) => {
83
+ const items = listItems(target, list.select)
84
+ const curr = listData(items)
85
+ const next = state[list.from]
86
+ listSync(target, items, curr, next, list.template)
87
+ })
88
+ })
89
+
90
+ // then the rest...
91
+ elements.forEach((c) => {
92
+ const { select, attribute, input } = c
93
+
94
+ const targets = [...rootNode.querySelectorAll(select)]
95
+
96
+ targets.forEach((target, i) => {
97
+ if (attribute) {
98
+ write(target, attribute(state, i))
99
+ }
100
+ if (input) {
101
+ const value = state[input]
102
+
103
+ if (target.value !== value) target.value = value
104
+ }
105
+ })
106
+ })
107
+ }
108
+
109
+ subscribe(onChange)
110
+
111
+ return state
112
+ }
package/src/list.js ADDED
@@ -0,0 +1,68 @@
1
+ import { castAll, nodeFromString } from "./helpers.js"
2
+
3
+ export function listItems(listContainerNode, listItemSelector) {
4
+ return [...listContainerNode.children].filter((node) =>
5
+ node.matches(listItemSelector)
6
+ )
7
+ }
8
+
9
+ export function listData(listItems) {
10
+ return listItems.map((node) => ({
11
+ id: node.id,
12
+ ...castAll(node.dataset),
13
+ }))
14
+ }
15
+
16
+ export function listSync(parentNode, nodes, curr, next, template) {
17
+ // check if anything has changed
18
+ const currIds = curr.map(({ id }) => id)
19
+ const nextIds = next.map(({ id }) => id)
20
+
21
+ if (currIds.toString() === nextIds.toString()) return
22
+
23
+ // removals
24
+ curr
25
+ .filter((c) => {
26
+ return next.find((n) => c.id === n.id) === undefined
27
+ })
28
+ .forEach(({ id }) => nodes.find((node) => node.id === id)?.remove())
29
+
30
+ const [first, ...rest] = next
31
+
32
+ if (!first) return
33
+
34
+ let t = first && nodes.find((node) => node.id === first.id)
35
+
36
+ if (
37
+ !template &&
38
+ next.find((c) => {
39
+ return curr.find((n) => c.id === n.id) === false
40
+ })
41
+ ) {
42
+ console.error(`Missing template when trying to add items to a list`)
43
+ return
44
+ }
45
+
46
+ if (!t) {
47
+ t = nodeFromString(template(first))
48
+
49
+ if (nodes[0]) {
50
+ nodes[0].before(t)
51
+ } else {
52
+ parentNode.append(t)
53
+ }
54
+ }
55
+
56
+ rest.forEach((d) => {
57
+ let node =
58
+ nodes.find((node) => node.id === d.id) || nodeFromString(template(d))
59
+
60
+ if (node) {
61
+ if (t.nextElementSibling !== node) {
62
+ // is t.after already a no-op in this case?
63
+ t.after(node)
64
+ }
65
+ t = node
66
+ }
67
+ })
68
+ }
package/src/message.js ADDED
@@ -0,0 +1,12 @@
1
+ export const Message = (callbacks) => {
2
+ const subscribers = []
3
+ return {
4
+ subscribe(fn) {
5
+ subscribers.push(fn)
6
+ },
7
+ publish(...args) {
8
+ subscribers.forEach((fn) => fn(...args))
9
+ callbacks.postPublish?.()
10
+ },
11
+ }
12
+ }
package/src/store.js ADDED
@@ -0,0 +1,49 @@
1
+ function debounce(fn) {
2
+ let id
3
+ return (...args) => {
4
+ if (!id) {
5
+ id = requestAnimationFrame(() => {
6
+ fn(...args)
7
+ id = null
8
+ })
9
+ }
10
+ }
11
+ }
12
+
13
+ export function Store({
14
+ action: actionHandlers = {},
15
+ getState: getStateWrapper = (v) => v,
16
+ onChangeCallback,
17
+ api = {},
18
+ }) {
19
+ let state
20
+
21
+ const transition = debounce(() => onChangeCallback(getState()))
22
+
23
+ function set(o) {
24
+ state = getStateWrapper({ ...o })
25
+ }
26
+
27
+ function getState() {
28
+ return { ...state }
29
+ }
30
+
31
+ function dispatch(type, action) {
32
+ if (type in actionHandlers) {
33
+ const x = actionHandlers[type](getState(), action)
34
+ set(x)
35
+ transition()
36
+ }
37
+ }
38
+
39
+ return {
40
+ dispatch,
41
+ getState,
42
+ merge: (o) => {
43
+ set({ ...getState(), ...o })
44
+ transition()
45
+ },
46
+ set,
47
+ ...api,
48
+ }
49
+ }
package/src/xo.js ADDED
@@ -0,0 +1,69 @@
1
+ import { isPrimitive } from "./helpers.js"
2
+
3
+ const pascalToKebab = (string) =>
4
+ string.replace(/[\w]([A-Z])/g, function (m) {
5
+ return m[0] + "-" + m[1].toLowerCase()
6
+ })
7
+
8
+ const kebabToPascal = (string) =>
9
+ string.replace(/[\w]-([\w])/g, function (m) {
10
+ return m[0] + m[2].toUpperCase()
11
+ })
12
+
13
+ export const objectToClasses = (v = {}) => {
14
+ return Object.entries(v)
15
+ .reduce((c, [k, v]) => {
16
+ if (v) c.push(k)
17
+ return c
18
+ }, [])
19
+ .join(" ")
20
+ }
21
+
22
+ export const objectFromClasses = (v = "") => {
23
+ return v
24
+ .split(/\s+/)
25
+ .filter((v) => v)
26
+ .reduce((o, k) => {
27
+ o[k] = true
28
+ return o
29
+ }, {})
30
+ }
31
+
32
+ export const write = (node, attrs) => {
33
+ for (let [k, v] of Object.entries(attrs || {})) {
34
+ k = pascalToKebab(k)
35
+
36
+ if (k === "textContent" && node.textContent !== textContent) {
37
+ node.textContent = textContent
38
+ continue
39
+ }
40
+
41
+ if (k === "class") {
42
+ v = objectToClasses(v)
43
+ }
44
+
45
+ if (typeof v === "boolean") {
46
+ if (k.startsWith("aria-")) {
47
+ v = "" + v
48
+ } else if (v) {
49
+ v = ""
50
+ }
51
+ }
52
+
53
+ if (isPrimitive(v) === false) {
54
+ node[kebabToPascal(k)] = v
55
+ continue
56
+ }
57
+
58
+ let current = node.getAttribute(k)
59
+
60
+ if (v === current) continue
61
+
62
+ if (typeof v === "string" || typeof v === "number") {
63
+ node.setAttribute(k, v)
64
+ } else {
65
+ node.removeAttribute(k)
66
+ }
67
+ }
68
+ return node
69
+ }
package/src/document.js DELETED
@@ -1,23 +0,0 @@
1
- import { html } from "./utils.js"
2
-
3
- export const document = ({ title, head = "", main = "" }) => html`
4
- <!DOCTYPE html>
5
- <html lang="en">
6
- <head>
7
- <meta charset="UTF-8" />
8
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
9
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
10
- ${title && `<title>${title}</title>`} ${head}
11
- <!--<link
12
- rel="stylesheet"
13
- href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/base16/tomorrow.min.css"
14
- integrity="sha512-5D/fcZ3y3nuaeHSxDbFwWDEy1Fvj5qQKsU0tilD7bhWAA+IN/Jl9fzGdUotzvA7wgXtsnZmafcuunH+6nyuA0A=="
15
- crossorigin="anonymous"
16
- referrerpolicy="no-referrer"
17
- />-->
18
- </head>
19
- <body>
20
- <main>${main}</main>
21
- </body>
22
- </html>
23
- `
package/src/head.js DELETED
@@ -1,17 +0,0 @@
1
- const HEAD_OPEN = "<head>"
2
- const HEAD_CLOSE = "</head>"
3
-
4
- export const decapitate = (str) => {
5
- const start = str.indexOf(HEAD_OPEN)
6
- const end = str.indexOf(HEAD_CLOSE)
7
- if (start === -1)
8
- return {
9
- head: "",
10
- body: str,
11
- }
12
- return {
13
- head: str.slice(start + HEAD_OPEN.length, end).trim(),
14
- body:
15
- str.slice(0, start).trim() + str.slice(end + HEAD_CLOSE.length).trim(),
16
- }
17
- }
package/src/utils.js DELETED
@@ -1,16 +0,0 @@
1
- function _(value) {
2
- if (typeof value === "undefined") return ""
3
- return String(Array.isArray(value) ? value.join("") : value)
4
- }
5
-
6
- function identity(template, ...args) {
7
- let str = ""
8
- for (let i = 0; i < args.length; i++) {
9
- str += template[i] + _(args[i])
10
- }
11
- return str + template[template.length - 1]
12
- }
13
-
14
- export const html = identity
15
- export const css = identity
16
- export const gql = identity