Коммит 9c9f4c73 создал по автору avathar's avatar avathar
Просмотр файлов

#102 продолжен рефакторинг

#112 базовая кнопка создана
удален файл mock.ts
владелец 6db43c8e
......@@ -43,9 +43,9 @@ const CreateItemsBox = (scene: SceneType, cards: TreeNode, registry): Sizer => {
});
itemsBox.addBackground(scene.rexUI.add.roundRectangle({}), 'background');
if (cards.getChildrens().length) {
for (let i = 0; i < cards.getChildrens().length; i++) {
itemsBox.add(CreateItem(scene, cards.getChildrens()[i].getName()), {
if (cards.childrens.length) {
for (let i = 0; i < cards.childrens.length; i++) {
itemsBox.add(CreateItem(scene, cards.childrens[i].name), {
proportion: 0,
expand: true,
});
......
......@@ -31,7 +31,7 @@ const CreateColumnPanel = (scene: SceneType, cards: TreeNode, registry) => {
background: scene.rexUI.add.roundRectangle({
strokeColor: COLOR_DARK,
}),
title: CreateTitle(scene, cards.getName(), registry),
title: CreateTitle(scene, cards.name, registry),
content: CreateItemsBox(scene, cards, registry),
proportion: {
content: 1,
......
......@@ -51,7 +51,7 @@ const CreateColumnPanelsBox = (
// 'background'
// )
item.getChildrens().forEach((child) => {
item.childrens.forEach((child) => {
const columnPanel = CreateColumnPanel(scene, child, registry);
columnPanelsBox.add(columnPanel, { proportion: 0, expand: true });
});
......
......@@ -16,11 +16,11 @@ const CreateHeader = function (
})
.addBackground(scene.rexUI.add.roundRectangle(0, 0, 20, 20, 0, COLOR_DARK));
const headerLabel = scene.rexUI.add.label({
text: scene.add.text(0, 0, objekto.getName()),
text: scene.add.text(0, 0, objekto.name),
});
registry.events.on('changedata', (parent, key, data, previousData) => {
if (data.getUuid() === objekto.getUuid()) {
headerLabel.setText(data.getName());
if (data.uuid === objekto.uuid) {
headerLabel.setText(data.name);
}
});
const dropDownButton = CreateDropDownList(scene);
......
......@@ -47,7 +47,7 @@ const CreateScrollablePanel = (
panel: {
child: CreateColumnPanelsBox(
scene,
objectTree ? objectTree[0]?.getChildrens()[0] : {},
objectTree ? objectTree[0]?.childrens[0] : {},
registry,
),
mask: {
......
import {
KanvasoObjekto,
KanvasojKanvasoObjekto,
Edge,
} from './../../types/stores/kanvaso.d';
//@ts-nocheck
export const a = {
Boards: [
{
id: 1,
BoardName: 'HeaderBoard',
},
],
Columns: [
{
id: 1,
ColumnName: 'HeaderColumn',
},
],
};
export { a as kanvaso } from './kanvaso.js';
import { a as objekto } from './objekto.js';
import { TreeNode } from './../../types/stores/kanvaso.d';
function convertToTree(flatArray: TreeNode[]): TreeNode[] {
let arr = objekto.data.kanvasojKanvasoObjekto.edges;
//@ts-ignore
arr = arr.map((item) => item.node);
// Создаем копию исходного массива, чтобы не изменять его. Глубокая копия, так как в некоторых браузерах проблемы с добавлением children
const nodes = JSON.parse(JSON.stringify(arr));
// const nodes = copy(arr);
// Создаем объект для быстрого доступа к каждому узлу по его UUID.
const nodeMap: Record<string, TreeNode> = {};
// Инициализируем nodeMap и добавляем каждому узлу пустой массив children.
nodes.forEach((node) => {
node.children = [];
nodeMap[node.uuid] = node;
});
// Фильтруем узлы, чтобы сохранить только корневые узлы в результирующем массиве.
const tree: TreeNode[] = nodes.filter((node) => {
// Если у узла есть posedantoUuid, добавляем его в children его родителя.
if (node.kanvasojKanvasoobjektoligiloLigilo) {
const parent =
nodeMap[node.kanvasojKanvasoobjektoligiloLigilo.posedanto.uuid];
if (parent) {
parent.children!.push(node);
}
// Узел не является корневым, поэтому исключаем его из результирующего массива.
return false;
}
// Узел является корневым.
return true;
});
return tree;
}
//@ts-ignore
const result = convertToTree(objekto);
export { result as objekto };
......@@ -26,25 +26,26 @@ import 'phaser';
import CreateScrollablePanel from '../kanbans/CreateScrollablePanel';
import { useKanvasoStore } from 'src/stores/kanvaso';
import { mapActions, mapState } from 'pinia';
// import { objekto } from './mock';
// import PreloadScene from './PreloadScene';
// import BootScene from './BootScene';
import { KanvasojKanvaso, TreeNode } from 'src/types/stores/kanvaso';
import { watch, computed } from 'vue';
import { Router, useRouter } from 'vue-router';
// declare const window: {
// objekto: TreeNode;
// } & Window;
declare const window: {
router: Router;
} & Window;
class EndlessCanvas extends Phaser.Scene {
[x: string]: any;
rexUI: any;
constructor() {
super({
key: 'endless-canvas',
});
//@ts-ignore
this.store = useKanvasoStore();
this.router = window.router;
}
preload() {
......@@ -56,21 +57,17 @@ class EndlessCanvas extends Phaser.Scene {
);
this.load.image('icon', 'phaser/stretching_icon.png');
//заполняем registry объектами холста
//@ts-ignore
this.store.getMap.forEach((element) => {
this.registry.set(element.getUuid(), element);
this.registry.set(element.uuid, element);
});
console.log('this.registry :>> ', this.registry);
//организуем слежение за getMap и в случае его изменения выясняем что изменилось и обновляем данные в registry
//@ts-ignore
// console.log('this.store.getMap :>> ', this.store.getMap);
//@ts-ignore
const map = computed(() => this.store.getMap);
watch(map, (newData, oldData) => {
newData.forEach((element) => {
const uuid = element.getUuid();
const oldElement = oldData.filter((el) => el.getUuid() === uuid)[0];
const uuid = element.uuid;
const oldElement = oldData.filter((el) => el.uuid === uuid)[0];
if (JSON.stringify(element) !== JSON.stringify(oldElement)) {
this.registry.set(uuid, element);
}
......@@ -79,14 +76,14 @@ class EndlessCanvas extends Phaser.Scene {
// Некоторые идеи к обдумыванию:
// Добавляем обработку добавления новых элементов
newData.forEach((element) => {
if (!oldData.some((el) => el.getUuid() === element.getUuid())) {
this.registry.set(element.getUuid(), element);
if (!oldData.some((el) => el.uuid === element.uuid)) {
this.registry.set(element.uuid, element);
}
});
// Добавляем обработку удаления элементов
oldData.forEach((element) => {
if (!newData.some((el) => el.getUuid() === element.getUuid())) {
this.registry.remove(element.getUuid());
if (!newData.some((el) => el.uuid === element.uuid)) {
this.registry.remove(element.uuid);
}
});
//Как обновлять реестр понятно. Не совсем понятно пока как убирать добавлять внутриигровые объекты
......@@ -94,15 +91,22 @@ class EndlessCanvas extends Phaser.Scene {
}
create(): void {
const back = this.add.text(0, 0, '<<', {
fontSize: '24px',
backgroundColor: '#000',
color: '#fff',
});
back.setInteractive();
back.on('pointerdown', () => {
this.router.push('/projects');
});
this.cameras.main.setBackgroundColor('#abcdef');
// Скрываем экран загрузки здесь, потому что на этом этапе preload уже завершен
document.getElementById('loading-screen').style.display = 'none';
//@ts-ignore
const topPanel = CreateScrollablePanel(
this,
//@ts-ignore
this.store.getTree,
this.registry,
)
......@@ -137,17 +141,15 @@ const config: Phaser.Types.Core.GameConfig = {
};
export default {
name: 'YourComponentName',
name: 'EndlessCanvas',
data() {
return {
wsSubscribe: null,
};
},
computed: {
...mapState(useKanvasoStore, ['getTree']),
...mapState(useKanvasoStore, {
project: 'getKanvaso',
kanvasoTree: 'getTree',
}),
// ...mapState(useCurrentUserStore, { userId: 'getUserId' }),
......@@ -158,11 +160,7 @@ export default {
return this.$route?.params?.uuid || '';
},
},
// watch: {
// getTree(val) {
// window.objekto = val;
// },
// },
methods: {
...mapActions(useKanvasoStore, [
'onGetKanvasoFull',
......@@ -203,6 +201,7 @@ export default {
};
window.addEventListener('resize', resizeHandler);
window.router = this.$router;
const game = new Phaser.Game(config);
// window.addEventListener('resize', function (event) {
......@@ -225,6 +224,8 @@ export default {
},
beforeUnmount() {
this.wsSubscribe.unsubscribe();
document.getElementsByTagName('body')[0].style.overflow = 'auto';
// delete window.objekto;
},
};
......
......@@ -5,11 +5,11 @@
<div>
<div>
<!-- {{ node.nomo.enhavo }} -->
{{ node.getName() }}
<span class="text-green">{{ node.getChildrens().length }}</span>
{{ node.name }}
<span class="text-green">{{ node.childrens.length }}</span>
<span v-if="isAdmin">
<q-icon
v-if="node.isPublished()"
v-if="node.isPublished"
color="blue"
name="published_with_changes"
/>
......@@ -18,7 +18,7 @@
<span v-if="isAdmin">
<q-icon
v-if="node.isDeleted()"
v-if="node.isDeleted"
color="orange"
name="delete_forever"
/>
......@@ -26,14 +26,14 @@
</span>
</div>
<div class="text-subtitle1">
{{ node.getDescription() }}
{{ node.description }}
</div>
<div class="text-subtitle2 text-brown">
{{ node.getUuid() }}
{{ node.uuid }}
</div>
<div class="text-subtitle2 text-green">
{{ node.getType() }}
{{ node.type }}
</div>
</div>
<!-- <pre class="text-caption text-brown">{{ node }}</pre> -->
......@@ -48,7 +48,7 @@
<q-tooltip> Редактирование </q-tooltip>
</q-btn>
<q-btn
v-if="node.getTypeId() < 4"
v-if="node.typeId < 4"
flat
round
color="teal"
......@@ -71,10 +71,10 @@
<!-- Рекурсивно отображаем дочерние узлы -->
<q-card-section
v-if="node && node.getChildrens().length"
v-if="node && node.childrens.length"
class="q-pa-md row items-start q-gutter-md"
>
<template v-for="child in node.getChildrens()" :key="child.getUuid()">
<template v-for="child in node.childrens" :key="child.uuid">
<tree-node
:node="child"
@edit="$emit('edit', $event)"
......
......@@ -29,7 +29,7 @@
flat
bordered
v-for="rootNode in kanvasoTree"
:key="rootNode.getUuid()"
:key="rootNode.uuid"
class="flex row"
>
<tree-node
......@@ -187,15 +187,15 @@ export default defineComponent({
this.dialogMessage = 'Редактирование элемента';
this.nameLabel = 'Название';
this.descriptionLabel = 'Описание';
this.name = this.oldName = node.getName();
this.description = this.oldDescription = node.getDescription();
this.name = this.oldName = node.name;
this.description = this.oldDescription = node.description;
this.payload = {
nomo: this.name,
priskribo: this.description,
kanvasoUuid: this.projectUuid,
// posedantoUzantoId: this.userId,
uuid: node.getUuid(),
uuid: node.uuid,
};
this.dialogMethod = this.updateKanvasoObjekto;
this.addOrEditDialog = true;
......@@ -223,7 +223,7 @@ export default defineComponent({
priskribo: this.description,
kanvasoUuid: this.projectUuid,
posedantoUzantoId: this.userId,
tipoId: node.getTypeId() < 4 ? node.getTypeId() + 1 : 4,
tipoId: node.typeId < 4 ? node.typeId + 1 : 4,
ligiloPosedantoUuid: node?.uuid,
};
this.dialogMethod = this.updateKanvasoObjekto;
......@@ -233,7 +233,7 @@ export default defineComponent({
this.dialogMessage = 'Удаление элемента';
this.payload = {
posedantoUzantoId: this.userId,
uuid: node.getUuid(),
uuid: node.uuid,
forigo: true,
};
this.dialogMethod = this.deleteKanvasoObjekto;
......
......@@ -19,42 +19,49 @@ import {
import { KanvasoEventoj } from 'src/queries/subscriptions.js';
class ObjectWrapper {
wrappingObject: TreeNode;
#wrappingObject: TreeNode;
constructor(wrappingObject: TreeNode) {
this.wrappingObject = wrappingObject;
this.#wrappingObject = wrappingObject;
this.#wrappingObject.childrens = [];
}
getName(): string {
return this.wrappingObject.nomo?.enhavo || 'Без имени';
get name(): string {
return this.#wrappingObject.nomo?.enhavo || 'Без имени';
}
isPublished(): boolean {
return this.wrappingObject.publikigo || true;
get isPublished(): boolean {
return this.#wrappingObject.publikigo || true;
}
isDeleted(): boolean {
return this.wrappingObject.forigo || false;
get isDeleted(): boolean {
return this.#wrappingObject.forigo || false;
}
getDescription(): string {
return this.wrappingObject.priskribo?.enhavo || 'Нет описания';
get description(): string {
return this.#wrappingObject.priskribo?.enhavo || 'Нет описания';
}
getId(): number {
return this.wrappingObject.objId || 0;
get id(): number {
return this.#wrappingObject.objId || 0;
}
getUuid(): string {
return this.wrappingObject.uuid || null;
get uuid(): string {
return this.#wrappingObject.uuid || null;
}
getType(): string {
return this.wrappingObject.tipo?.nomo?.enhavo || 'Без типа';
get type(): string {
return this.#wrappingObject.tipo?.nomo?.enhavo || 'Без типа';
}
getTypeId(): number {
return this.wrappingObject.tipo?.objId || 0;
get typeId(): number {
return this.#wrappingObject.tipo?.objId || 0;
}
getParentUuid(): string {
get parentUuid(): string {
return (
this.wrappingObject.kanvasojKanvasoobjektoligiloLigilo.posedanto?.uuid ||
this.#wrappingObject.kanvasojKanvasoobjektoligiloLigilo.posedanto?.uuid ||
null
);
}
getChildrens() {
return this.wrappingObject.children || [];
get childrens() {
return this.#wrappingObject.childrens || [];
}
setChildrens(childrens: TreeNode) {
this.#wrappingObject.childrens.push(childrens);
}
get hasParent() {
return !!this.#wrappingObject.kanvasojKanvasoobjektoligiloLigilo;
}
}
......@@ -91,17 +98,16 @@ export const useKanvasoStore = defineStore('Kanvaso', {
const nodeMap: Record<string, TreeNode> = {};
// Инициализируем nodeMap и добавляем каждому узлу пустой массив children и геттеры для получения свойств
nodes.forEach((node) => {
node.wrappingObject.children = [];
nodeMap[node.getUuid()] = node;
nodeMap[node.uuid] = node;
});
// Фильтруем узлы, чтобы сохранить только корневые узлы в результирующем массиве.
const tree: TreeNode[] = nodes.filter((node) => {
// Если у узла есть posedantoUuid, добавляем его в children его родителя.
if (node.wrappingObject.kanvasojKanvasoobjektoligiloLigilo) {
const parent = nodeMap[node.getParentUuid()];
// Если у узла есть uuid родителя, добавляем его в children его родителя.
if (node.hasParent) {
const parent = nodeMap[node.parentUuid];
if (parent) {
parent.wrappingObject.children!.push(node);
parent.setChildrens(node);
}
// Узел не является корневым, поэтому исключаем его из результирующего массива.
return false;
......
export type TreeNode = {
setChildrens(node: TreeNode): TreeNode[];
getName: () => string;
isPublished: () => true | boolean;
isDeleted: () => false | boolean;
......@@ -9,6 +10,7 @@ export type TreeNode = {
getUuid(): string;
getParentUuid(): string;
getChildrens: () => [];
hasParent: () => boolean;
wrappingObject: TreeNode;
uuid: string;
forigo: boolean;
......@@ -44,7 +46,7 @@ export type TreeNode = {
tipo: Tipo;
};
children?: TreeNode[];
childrens?: TreeNode[];
};
export interface Nomo {
......
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать