Skip to content

Commit

Permalink
feat: modify dispatch event. Add recursive dispatching event to child…
Browse files Browse the repository at this point in the history
…ren depends.
  • Loading branch information
Jenesius committed May 23, 2023
1 parent 35e4b53 commit e57777e
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 41 deletions.
9 changes: 6 additions & 3 deletions project/pages/test/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<button @click = "setDefaultValues">set default values</button>

<div :key = "count">{{values}}</div>
<div :key = "count">{{count}}</div>
</div>
</template>

Expand All @@ -19,6 +19,7 @@ import FormField from "./../../../src/widgets/form-field.vue";
import {ref} from "vue";
import WidgetComposite from "./widget-composite.vue";
import WidgetAddress from "./widget-address.vue"
import copyObject from "./../../../src/utils/copy-object";
const form = new Form({
name: "main"
Expand All @@ -27,8 +28,9 @@ const form = new Form({
window.form = form
const count = ref(0);
setInterval(() => count.value++, 50);
const values = ref(form.values);
setInterval(() => {
count.value = copyObject(form.values);
}, 50);
const name = ref('username');
Expand All @@ -41,6 +43,7 @@ function clean() {
function setDefaultValues() {
return form.cleanValues({
username: "Jenesius",
"coordinate.x": "123"
})
}
Expand Down
8 changes: 6 additions & 2 deletions project/pages/test/input-coord.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<template>
<div>
<div class = "widget-coordinate">
<p>Coordinate</p>
<input-field name = "X" label = "X"/>
<input-field name = "Y" label = "Y"/>
<button @click = "random">test</button>
Expand Down Expand Up @@ -28,5 +29,8 @@ const values = useFormValues(form)
</script>

<style scoped>
.widget-coordinate {
padding: 4px;
background-color: #eab0f5;
}
</style>
8 changes: 6 additions & 2 deletions project/pages/test/widget-composite.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<template>
<div>
<div class = "widget-composite">
<p>Coordinate</p>
<form-field name="x"/>
<form-field name="y"/>

Expand Down Expand Up @@ -29,5 +30,8 @@ const values = ref(form.values);
</script>

<style scoped>
.widget-composite{
padding: 5px;
background-color: rgba(194, 154, 49, 0.13);
}
</style>
13 changes: 13 additions & 0 deletions src/classes/CompareEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ export default class CompareEvent extends FormEvent{
* Используется для передачи только части объекта изменений в дочерний элемент.
* */
static restoreByName(compareEvent: CompareEvent, name: string) {

const array: CompareItem[] = [];

compareEvent.comparison.forEach(item => {
if (!item.name.startsWith(name)) return;

array.push({
...item,
name: item.name.slice(name.length + 1)
})
})
return new CompareEvent(array)

return new CompareEvent(
compareEvent.comparison
.filter(comp => comp.name.startsWith(name))
Expand Down
13 changes: 6 additions & 7 deletions src/classes/DependencyQueue.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Form from "./Form";

export default class DependencyQueue<T extends DependencyItem> {
private array: DependencyItem[] = []
private array: T[] = []
private readonly form: Form

constructor(form: Form) {
Expand All @@ -16,20 +16,19 @@ export default class DependencyQueue<T extends DependencyItem> {
object.parent = parentForm
this.array.push(object);



parentForm.oninput(object.name, (event: any) => {
object.notify('value', event)
})
}
remove(object: T) {
console.log('Псевдо удаление ')
}

forEach(callback: (elem: T) => void) {
this.array.forEach(callback);
}
}

export interface DependencyItem {
parent?: Form | undefined,
name?: string,
notify: any
notify: any,
dispatchEvent?: any
}
87 changes: 60 additions & 27 deletions src/classes/Form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import iteratePoints from "../utils/iterate-points";
import debug from "../debug/debug";
import getCastObject from "../utils/get-cast-object";
import copyObject from "../utils/copy-object";
import {compareDifference} from "../utils/compare-changes";
import {compareDifference, compareMergeChanges} from "../utils/compare-changes";
import DependencyQueue from "./DependencyQueue";
import CompareEvent from "./CompareEvent";
/**
* Main principe : GMN
* G - Grand
Expand Down Expand Up @@ -48,17 +49,15 @@ export default class Form extends EventEmitter implements FormDependence {
};
private set values(values: any) {

const oldValues = copyObject(this.values);
// const oldValues = copyObject(this.values);

console.group('%csetting values', 'color: purple');
console.log(this.values, values)
console.log(compareDifference(values, oldValues))

const grandValues = grandObject(values);
const event = new CompareEvent(grandValues, this.values);
this.dispatchEvent(event);

this.notify('value', )
this.setValues(values || {});

this.#values = values;
this.#values = grandValues;

console.groupEnd()
}
Expand Down Expand Up @@ -86,16 +85,13 @@ export default class Form extends EventEmitter implements FormDependence {
if (currentInstance) provideVue(Form.PROVIDE_NAME, this); // Default providing current form for children.
}

private mergeValues(data: any) {
mergeObjects(this.values, data);
}
private notify(event: FormEvent['type'], model: any ) {

switch (event) {
case "value": {
console.log('New changes', model); //Changes
console.log(`%c[${Form.restoreFullName(this)}]%c Generation new global event %c${event}%c`,'color: blue', 'color: black', 'color: red', 'color: black', model);
this.emit(Form.EVENT_VALUE, FormEvent.newValue(model)); // Generate global event
// this.emit(Form.EVENT_VALUE, FormEvent.newValue(model)); // Generate global event

// Generate event-value for each point
iteratePoints(model).forEach(point => {
Expand All @@ -112,19 +108,32 @@ export default class Form extends EventEmitter implements FormDependence {
}
}

setValues(data: any):void {
setValues(changes: any):void {
if (this.parent) {
console.log(`[%c${this.name}%c] emit changes to parent [%c${this.parent.name}%c]`, 'color: red', 'color: black', 'color: red', 'color: black');
return void this.parent.setValues({
[this.name as string]: data
[this.name as string]: changes
});
}

const grandData = grandObject(data);
this.mergeValues(grandData);
this.notify('value', grandData);
}
console.group('[SET VALUES]');

changes = grandObject(changes);
console.log('%cGrand Object:', 'color: blue', changes);
console.log('%cValues Object(copied):', 'color: blue', copyObject(this.values));
console.log('%cCompare Merge Changes', 'color: blue', compareMergeChanges(this.values, changes))

const event = new CompareEvent(compareMergeChanges(this.values, changes));
mergeObjects(this.values, changes);

console.log('%cEvent:', 'color: blue', event);
console.log('%cNew Values', 'color: blue', this.values)

console.groupEnd();

this.dispatchEvent(event);

}

getValueByName(name: string) {
return getPropFromObject(this.values, name);
Expand All @@ -144,17 +153,28 @@ export default class Form extends EventEmitter implements FormDependence {
oninput(name: string, callback: (newValue: any) => void) {
return this.on(Form.getEventValueByName(name), callback)
}
cleanValues(values?: any) {
debug.msg('Cleaning values')
dispatchEvent<T extends FormEvent>(event: T) {


if (event instanceof CompareEvent) {
console.log(`[%c${this.name}%c]: %c${event?.comparison.length ? '' : 'NOT EFFECT'}%c`, 'color: red', 'color: black', 'color: purple', 'color: black', 'Dispatch event', event)

// Проходим по всем дочерним элементам и уведомляем их
this.dependencies.forEach(dep => {
if (dep.name) {
dep?.dispatchEvent(CompareEvent.restoreByName(event, dep.name));
}
})

event.comparison.forEach(item => {
console.log(`[%c${this.name}%c] Emit new value event to %c${item.name}`, 'color: red', 'color: black', 'color: red');
this.emit(Form.getEventValueByName(item.name), item.newValue);
})

}


/**
* WARNING WARNING WARNING WARNING WARNING
* в данном случаем мы сперва устанавливаем пустое значение, а потому уже нужное.
* Эффективнее сразу устанавливать нужно значение
* WARNING WARNING WARNING WARNING WARNING
* */

this.values = values || {};

}
/**
Expand All @@ -170,6 +190,19 @@ export default class Form extends EventEmitter implements FormDependence {

return getCastObject(this.values, grandObject(cast));
}
cleanValues(values?: any) {
debug.msg('Cleaning values')

/**
* WARNING WARNING WARNING WARNING WARNING
* в данном случаем мы сперва устанавливаем пустое значение, а потому уже нужное.
* Эффективнее сразу устанавливать нужно значение
* WARNING WARNING WARNING WARNING WARNING
* */

this.values = values || {};

}
}

interface FormParams {
Expand Down

0 comments on commit e57777e

Please sign in to comment.