improve componentId generate method

This commit is contained in:
Bowen Tan 2021-10-12 14:52:33 +08:00
parent 90d52adb71
commit 288886ce63
3 changed files with 15 additions and 8 deletions

View File

@ -11,7 +11,7 @@ import {
import { eventBus } from '../eventBus';
import { ComponentForm } from './ComponentForm';
import { ComponentList } from './ComponentsList';
import { useAppModel } from '../operations/useAppModel';
import { appModelManager, useAppModel } from '../operations/useAppModel';
import { KeyboardEventWrapper } from './KeyboardEventWrapper';
import { genComponentWrapper } from './ComponentWrapper';
@ -58,7 +58,7 @@ export const Editor = () => {
},
onDrop(id, layout, _, e) {
const component = e.dataTransfer?.getData('component') || '';
const componentId = `component${layout.length++}`;
const componentId = appModelManager.genId(component);
eventBus.send(
'operation',
new CreateComponentOperation(id, 'container', component, componentId)

View File

@ -21,19 +21,18 @@ function genSlotTrait(parentId: string, slot: string): ComponentTrait {
},
};
}
let count = 0;
function genComponent(
type: string,
parentId: string,
slot: string,
id?: string
id: string
): ApplicationComponent {
const { version, name } = parseType(type);
const cImpl = registry.getComponent(version, name);
const initProperties = cImpl.metadata.exampleProperties;
count++;
return {
id: id || `${name}${count}`,
id,
type: type,
properties: initProperties,
traits: [genSlotTrait(parentId, slot)],
@ -60,6 +59,14 @@ export class AppModelManager {
return this.app;
}
genId(componentType: string) {
const { name } = parseType(componentType);
const componentsCount = this.app.spec.components.filter(
c => c.type === componentType
).length;
return `${name}${componentsCount + 1}`;
}
updateApp(app: Application) {
eventBus.send('appChange', app);
localStorage.setItem('schema', JSON.stringify(app));
@ -83,7 +90,7 @@ export class AppModelManager {
createO.componentType,
createO.parentId,
createO.slot,
createO.componentId
createO.componentId || this.genId(createO.componentType)
);
if (!noEffect) {
const undoOperation = new RemoveComponentOperation(newComponent.id);

View File

@ -4,7 +4,7 @@ import { DefaultAppSchema } from '../constants';
import { eventBus } from '../eventBus';
import { AppModelManager } from './AppModelManager';
const appModelManager = new AppModelManager(DefaultAppSchema);
export const appModelManager = new AppModelManager(DefaultAppSchema);
export function useAppModel() {
const [app, setApp] = useState<Application>(appModelManager.getApp());