Skip to content

Commit

Permalink
Added listeners to array-hook in JDOM-Template
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianFun123 committed Mar 9, 2024
1 parent 5da5c7e commit edbc285
Show file tree
Hide file tree
Showing 15 changed files with 97 additions and 62 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# JDOM `3.1.7`
# JDOM `3.1.8`
## A wrapper for query selector and html elements + templating & reactivity framework

- [Installation or embedding](#install)
Expand Down Expand Up @@ -28,12 +28,12 @@ npm install jdomjs

### Module
```js
import { $, $n, $c, $r, $h, JDOM } from 'https://cdn.jsdelivr.net/npm/jdomjs@3.1.7'
import { $, $n, $c, $r, $h, JDOM } from 'https://cdn.jsdelivr.net/npm/jdomjs@3.1.8'
```

### HTML import
```js
<script src="https://cdn.jsdelivr.net/npm/jdom@3.1.7/dist/jdom.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jdom@3.1.8/dist/jdom.js"></script>
```

## DOM Manipulation
Expand Down
2 changes: 1 addition & 1 deletion dist/jdom.js

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions ex/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<html>
<head></head>
<body>
<script type=module src="main.js"></script>
</body>
</html>
17 changes: 17 additions & 0 deletions ex/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { JDOMComponent, html, $r, $, computed, Hook } from 'https://esm.run/jdomjs@3.1.7'

class MyComponent extends JDOMComponent {
example = new Hook('Hello World')

render() {
setTimeout(() => this.example.value = "Yooo", 5000)

return html`
<div>${computed(() => this.example.value, [this.example])}</div>
`
}
}

$r('my-component', MyComponent)

$(document).append(html`<my-component></my-component>`)
13 changes: 0 additions & 13 deletions examples/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,14 @@
import Hook from "../src/Hook.js";
import { ForEach, Awaiting } from "../src/template/helper/components.js";

const a = state(0)

function Test(props) {
console.log(props)
return html`
<h3>Halloooo</h3>
`
}

html`
<button @click=${()=> a.value++}>Plus</button>
<h1 :if=${computed(() => a.value === 0, [a])}>Hallo</h1>
<${Test} :else-if=${computed(() => a.value === 3, [a])} />
<h1 :else>ESLE</h1>
`.appendTo(document)

/*
const paste = fetch(`https://pastefy.app/api/v2/paste/9XH0KD7g`)
.then(r => r.json())
.then(r => JSON.parse(r.content))
Expand Down
1 change: 1 addition & 0 deletions examples/js-components/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Hook from "../../src/Hook.js";
class ToDoApp extends JDOMComponent {
tasks = new Hook([]);
newTaskText = new Hook('');

constructor() {
super();
}
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jdomjs",
"version": "3.1.7",
"version": "3.1.8",
"description": "A wrapper for query selector and html elements",
"main": "./index.js",
"types": "./types/index.d.ts",
Expand Down
6 changes: 3 additions & 3 deletions src/Hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ export default class Hook {
set: (target, prop, value) => {
if (Object.hasOwn(target, prop) || prop in target || prop === 'value') {
if (target[prop] === value)
return;
return true;

return Reflect.set(target, prop, value);
}
if (typeof target._value === 'object' && !Array.isArray(target._value) && target._value !== null) {
if (target._value[prop] === value)
return;
return true;

return Reflect.set(target._value, prop, value);
}
Expand All @@ -69,7 +69,7 @@ export default class Hook {
return new Proxy(val, {
set: (target, prop, value) => {
if (val === val[prop])
return;
return true;

val[prop] = value
this.setValue(val)
Expand Down
8 changes: 4 additions & 4 deletions src/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ import Hook from './Hook.js'
/**
* @template T
* @param {T} initialValue
* @return {Hook}
* @return {Hook<T>}
*/
export function state(initialValue) {
return new Hook(initialValue)
}

/**
*
* @param {function()} callable
* @template T
* @param {function(): T} callable
* @param {Hook[]} dependencies
* @return {Hook}
* @return {Hook<T>}
*/
export function computed(callable, dependencies = []) {
const hook = new Hook(callable())
Expand Down
51 changes: 32 additions & 19 deletions src/template/TemplateDOMAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export default class TemplateDOMAdapter {
}
})

model.listeners.push(val => {
model.addListener(val => {
if (elem.value !== model.value) {
elem.value = val
elem.dispatchEvent(new InputEvent('input:value'))
Expand Down Expand Up @@ -329,18 +329,15 @@ export default class TemplateDOMAdapter {
})

if (isArray) {
const comment = document.createComment('JDOM-Templating:arrhook')
const comment = document.createComment('JDOM-Templating:arrhook1')
outputElement = comment

let elements = []

removeEl = () => elements.forEach(e => e.forEach(i => this.removeElement(i)))
const setElements = () => {
for (const item of elements) {
item.elements.forEach(e => this.removeElement(e))
elements = elements.filter(e => e !== item)
this.removeElement(item)
}
let i = 0

if (!Array.isArray(state.value)) {
this.replaceElement(outputElement, this.createFromValue({ value: state.value }))
Expand All @@ -349,17 +346,37 @@ export default class TemplateDOMAdapter {
}

let lastEl = comment
let i = 0
for (const item of state.value) {
let itemEls = this.createFromValue({value: item})
if (!Array.isArray(itemEls))
itemEls = [itemEls]

elements = [...elements, {
key: ++i,
elements: itemEls
}]
const currentIndex = i++
elements = [...elements, ...itemEls]

itemEls.forEach(e => lastEl = this.afterElement(lastEl, e))
itemEls.forEach((e) => {
lastEl = this.afterElement(lastEl, e)

const addReplaceListener = toRepl => {
toRepl.addEventListener(':replaced_with', ({detail: {to}}) => {
for (const e of to) {
addReplaceListener(e)
elements.push(e)
}
})

toRepl.addEventListener(':attached', () => {
elements.push(toRepl)
})

toRepl.addEventListener(':detached', () => {
elements = elements.filter(e => e !== toRepl)
})
}

addReplaceListener(lastEl)
})
}
}

Expand All @@ -369,12 +386,7 @@ export default class TemplateDOMAdapter {

setElements()

let out = []

for (const item of elements) {
item.elements.forEach(e => out = [...out, e])
}
return [comment, ...out]
return [comment, ...elements]
} else if (typeof state.value === 'string' || typeof state.value === 'number' || typeof state.value === 'boolean') {
outputElement = this.createText({value: state.value})

Expand Down Expand Up @@ -446,6 +458,7 @@ export default class TemplateDOMAdapter {
replaceElement(from, to) {
const replElements = Array.isArray(from) ? [...from] : [from]
const endElements = Array.isArray(to) ? [...to] : [to]
const finalEndElements = [...endElements]

if (endElements.length === 0)
endElements.push(document.createComment('JDOM-Templating:REPLACEMENT'))
Expand All @@ -456,7 +469,7 @@ export default class TemplateDOMAdapter {
const firstEndEl = endElements.shift()


firstEl.dispatchEvent(new CustomEvent(':replace_with', { to }))
firstEl.dispatchEvent(new CustomEvent(':replace_with', { detail: { to: finalEndElements } }))
firstEl.dispatchEvent(new CustomEvent(':detach'))
firstEndEl.dispatchEvent(new CustomEvent(':child_attach'))
firstEl.replaceWith(firstEndEl)
Expand All @@ -468,7 +481,7 @@ export default class TemplateDOMAdapter {
lastEl = this.afterElement(lastEl, e)
})

firstEl.dispatchEvent(new CustomEvent(':replaced_with', { to }))
firstEl.dispatchEvent(new CustomEvent(':replaced_with', { detail: { to: finalEndElements } }))
firstEl.dispatchEvent(new CustomEvent(':detached'))
firstEndEl.dispatchEvent(new CustomEvent(':child_attached'))

Expand Down
16 changes: 10 additions & 6 deletions src/template/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,20 @@ import Hook from '../Hook.js'
* @return {JDOM}
*/
export function html(strings, ...values) {
// console.time("myFunction");
const parser = JDOMTemplateParser.fromTemplate(strings, ...values)

const parsed = parser.parse()

const adapter = new TemplateJDOMAdapter(parsed)
// console.timeEnd("myFunction");
return adapter.create()
}

/**
* Usage: css`h1 {font-size: 20px}`
*
* @param strings
* @param values
* @return string
*/
export function css(strings, ...values) {
let out = ''
let i = 0
Expand All @@ -45,9 +49,9 @@ export function css(strings, ...values) {
* `
* ```
*
* @param {string[]} strings
* @param {...any} values
* @return {Hook}
* @param strings
* @param values
* @return {Hook<string>}
*/
export function comp(strings, ...values) {
return computed(() => {
Expand Down
12 changes: 6 additions & 6 deletions types/src/hooks.d.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
/**
* @template T
* @param {T} initialValue
* @return {Hook}
* @return {Hook<T>}
*/
export function state<T>(initialValue: T): Hook<any>;
export function state<T>(initialValue: T): Hook<T>;
/**
*
* @param {function()} callable
* @template T
* @param {function(): T} callable
* @param {Hook[]} dependencies
* @return {Hook}
* @return {Hook<T>}
*/
export function computed(callable: () => any, dependencies?: Hook<any>[]): Hook<any>;
export function computed<T>(callable: () => T, dependencies?: Hook<any>[]): Hook<T>;
/**
* @param {Hook[]} hooks
* @param {function()} callable
Expand Down
2 changes: 1 addition & 1 deletion types/src/router/Router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default class Router {
* @type Route[]
*/
routes: Route[];
view: import("src/Hook.js").default<any>;
view: import("src/Hook.js").default<null>;
link: (to: any, text: any) => any;
/**
* @param to
Expand Down
15 changes: 11 additions & 4 deletions types/src/template/template.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
* @return {JDOM}
*/
export function html(strings: any, ...values: any[]): JDOM;
/**
* Usage: css`h1 {font-size: 20px}`
*
* @param strings
* @param values
* @return string
*/
export function css(strings: any, ...values: any[]): string;
/**
* usage:
Expand All @@ -18,9 +25,9 @@ export function css(strings: any, ...values: any[]): string;
* `
* ```
*
* @param {string[]} strings
* @param {...any} values
* @return {Hook}
* @param strings
* @param values
* @return {Hook<string>}
*/
export function comp(strings: string[], ...values: any[]): Hook<any>;
export function comp(strings: any, ...values: any[]): Hook<string>;
import Hook from '../Hook.js';

0 comments on commit edbc285

Please sign in to comment.