Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce DI & migrate tools builders #80

Merged
merged 9 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
"@editorjs/dom": "^1.0.0",
"@editorjs/dom-adapters": "workspace:^",
"@editorjs/editorjs": "^2.30.5",
"@editorjs/helpers": "^1.0.0",
"@editorjs/model": "workspace:^",
"@editorjs/sdk": "workspace:^"
"@editorjs/sdk": "workspace:^",
"reflect-metadata": "^0.2.2",
"typedi": "^0.10.0"
}
}
27 changes: 27 additions & 0 deletions packages/core/src/entities/UnifiedToolConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { ToolSettings, ToolConstructable } from '@editorjs/editorjs';
import type { BlockToolConstructor, InlineToolConstructor } from '@editorjs/sdk';

/**
* Users can pass tool's config in two ways:
* toolName: ToolClass
* or
* toolName: {
* class: ToolClass,
* // .. other options
* }
*
* This interface unifies these variants to a single format
*/
export type UnifiedToolConfig = Record<string, Omit<ToolSettings, 'class'> & {
gohabereg marked this conversation as resolved.
Show resolved Hide resolved
/**
* Tool constructor
*/
class: ToolConstructable | BlockToolConstructor | InlineToolConstructor;

/**
* Specifies if tool is internal
neSpecc marked this conversation as resolved.
Show resolved Hide resolved
*
* Internal tools set it to true, external tools omit it
*/
isInternal?: boolean;
}>;
1 change: 1 addition & 0 deletions packages/core/src/entities/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './Config.js';
export * from './UnifiedToolConfig.js';
39 changes: 30 additions & 9 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { ModelEvents } from '@editorjs/model';
import { BlockAddedEvent, EditorJSModel, EventType } from '@editorjs/model';
import type { ContainerInstance } from 'typedi';
import { Container } from 'typedi';
import { composeDataFromVersion2 } from './utils/composeDataFromVersion2.js';
import ToolsManager from './tools/ToolsManager.js';
import { BlockToolAdapter, CaretAdapter, InlineToolsAdapter } from '@editorjs/dom-adapters';
import type { BlockAPI, BlockToolData, API as EditorjsApi, ToolConfig } from '@editorjs/editorjs';
import type { BlockAPI, BlockToolData } from '@editorjs/editorjs';
import { InlineToolbar } from './ui/InlineToolbar/index.js';
import type { CoreConfigValidated } from './entities/Config.js';
import type { BlockTool, CoreConfig } from '@editorjs/sdk';
Expand Down Expand Up @@ -42,6 +44,11 @@ export default class Core {
*/
#caretAdapter: CaretAdapter;

/**
* Inversion of Control container for dependency injections
*/
#iocContainer: ContainerInstance;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docs missing


/**
* Inline tool adapter is responsible for handling model formatting updates
* Applies format, got from inline toolbar to the model
Expand All @@ -61,19 +68,32 @@ export default class Core {
* @param config - Editor configuration
*/
constructor(config: CoreConfig) {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.#iocContainer = Container.of(Math.floor(Math.random() * 1e10).toString());

this.validateConfig(config);
this.#config = config as CoreConfigValidated;

this.#iocContainer.set('EditorConfig', this.#config);

const { blocks } = composeDataFromVersion2(config.data ?? { blocks: [] });

this.#model = new EditorJSModel();

this.#iocContainer.set(EditorJSModel, this.#model);

this.#model.addEventListener(EventType.Changed, (event: ModelEvents) => this.handleModelUpdate(event));

this.#toolsManager = new ToolsManager(this.#config.tools);
this.#toolsManager = this.#iocContainer.get(ToolsManager);

this.#caretAdapter = new CaretAdapter(this.#config.holder, this.#model);
this.#iocContainer.set(CaretAdapter, this.#caretAdapter);

this.#inlineToolsAdapter = new InlineToolsAdapter(this.#model, this.#caretAdapter);
this.#iocContainer.set(InlineToolsAdapter, this.#inlineToolsAdapter);

this.#inlineToolbar = new InlineToolbar(this.#model, this.#inlineToolsAdapter, this.#toolsManager.getInlineTools(), this.#config.holder);
this.#inlineToolbar = new InlineToolbar(this.#model, this.#inlineToolsAdapter, this.#toolsManager.inlineTools, this.#config.holder);
this.#iocContainer.set(InlineToolbar, this.#inlineToolbar);

this.#model.initializeDocument({ blocks });
}
Expand Down Expand Up @@ -160,14 +180,15 @@ export default class Core {
*/
data: BlockToolData<Record<string, unknown>>;
}, blockToolAdapter: BlockToolAdapter): BlockTool {
const tool = this.#toolsManager.resolveBlockTool(name);
const block = new tool({
const tool = this.#toolsManager.blockTools.get(name);

if (!tool) {
throw new Error(`Block Tool ${name} not found`);
}

const block = tool.create({
adapter: blockToolAdapter,
data: data,

// @todo
api: {} as EditorjsApi,
config: {} as ToolConfig<Record<string, unknown>>,
block: {} as BlockAPI,
readOnly: false,
});
Expand Down
235 changes: 216 additions & 19 deletions packages/core/src/tools/ToolsManager.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,239 @@
import type { BlockToolConstructor, InlineToolsConfig } from '@editorjs/sdk';
import 'reflect-metadata';
import { deepMerge, isFunction, isObject, PromiseQueue } from '@editorjs/helpers';
import { Inject, Service } from 'typedi';
import {
BlockToolFacade, BlockTuneFacade,
InlineToolFacade,
ToolsCollection,
ToolsFactory
} from './facades/index.js';
import { Paragraph } from './internal/block-tools/paragraph/index.js';
import type { EditorConfig } from '@editorjs/editorjs';
import type {
EditorConfig,
ToolConstructable,
ToolSettings
} from '@editorjs/editorjs';
import BoldInlineTool from './internal/inline-tools/bold/index.js';
import ItalicInlineTool from './internal/inline-tools/italic/index.js';
import { BlockToolConstructor, InlineTool, InlineToolConstructor } from '@editorjs/sdk';
import { UnifiedToolConfig } from '../entities/index.js';

/**
* Works with tools
* @todo - validate tools configurations
* @todo - merge internal tools
*/
@Service()
export default class ToolsManager {
#tools: EditorConfig['tools'];
/**
* ToolsFactory instance
*/
#factory: ToolsFactory;

/**
* Unified config with internal and internal tools
*/
#config: UnifiedToolConfig;

/**
* Tools available for use
*/
#availableTools = new ToolsCollection();

/**
* Tools loaded but unavailable for use
*/
#unavailableTools = new ToolsCollection();

/**
* Returns available Tools
*/
public get available(): ToolsCollection {
return this.#availableTools;
}

/**
* Returns unavailable Tools
*/
public get unavailable(): ToolsCollection {
return this.#unavailableTools;
}

/**
* Return Tools for the Inline Toolbar
*/
public get inlineTools(): ToolsCollection<InlineToolFacade> {
return this.available.inlineTools;
}

/**
* Return editor block tools
*/
public get blockTools(): ToolsCollection<BlockToolFacade> {
return this.available.blockTools;
}

/**
* Return available Block Tunes
* @returns - object of Inline Tool's classes
*/
public get blockTunes(): ToolsCollection<BlockTuneFacade> {
return this.available.blockTunes;
}

/**
* @param tools - Tools configuration passed by user
* Returns internal tools
*/
constructor(tools: EditorConfig['tools']) {
this.#tools = tools;
public get internal(): ToolsCollection {
return this.available.internalTools;
}

/**
* Returns a block tool by its name
* @param toolName - name of a tool to resolve
* @param editorConfig - EditorConfig object
* @param editorConfig.tools - Tools configuration passed by user
*/
public resolveBlockTool(toolName: string): BlockToolConstructor {
switch (toolName) {
case 'paragraph':
return Paragraph;
default:
throw new Error(`Unknown tool: ${toolName}`);
constructor(@Inject('EditorConfig') editorConfig: EditorConfig) {
this.#config = this.#prepareConfig(editorConfig.tools ?? {});

this.#validateTools();

this.#factory = new ToolsFactory(this.#config, editorConfig, {});

void this.prepareTools();
}

/**
* Calls tools prepare method if it exists and adds tools to relevant collection (available or unavailable tools)
* @returns Promise<void>
*/
public async prepareTools(): Promise<void> {
const promiseQueue = new PromiseQueue();

Object.entries(this.#config).forEach(([toolName, config]) => {
if (isFunction(config.class.prepare)) {
void promiseQueue.add(async () => {
try {
/**
* TypeScript doesn't get type guard here, so non-null assertion is used
*/
await config.class.prepare!({
toolName: toolName,
neSpecc marked this conversation as resolved.
Show resolved Hide resolved
config: config,
});

const tool = this.#factory.get(toolName);

if (tool.isInline()) {
/**
* Some Tools validation
*/
const inlineToolRequiredMethods = ['render'];
const notImplementedMethods = inlineToolRequiredMethods.filter(method => tool.create()[method as keyof InlineTool] !== undefined);
e11sy marked this conversation as resolved.
Show resolved Hide resolved

if (notImplementedMethods.length) {
/**
* @todo implement logger
*/
console.log(
`Incorrect Inline Tool: ${tool.name}. Some of required methods is not implemented %o`,
'warn',
notImplementedMethods
);

this.#unavailableTools.set(tool.name, tool);

return;
}
}

this.#availableTools.set(toolName, tool);
} catch (e) {
console.error(`Tool ${toolName} failed to prepare`, e);

this.#unavailableTools.set(toolName, this.#factory.get(toolName));
}
});
} else {
this.#availableTools.set(toolName, this.#factory.get(toolName));
}
});

await promiseQueue.completed;
}

/**
* Unify tools config
* @param config - user's tools config
*/
#prepareConfig(config: EditorConfig['tools']): UnifiedToolConfig {
const unifiedConfig: UnifiedToolConfig = {} as UnifiedToolConfig;

/**
* Save Tools settings to a map
*/
for (const toolName in config) {
/**
* If Tool is an object not a Tool's class then
* save class and settings separately
*/
if (isObject(config)) {
unifiedConfig[toolName] = config[toolName] as UnifiedToolConfig[string];
} else {
unifiedConfig[toolName] = { class: config[toolName] as ToolConstructable };
}
}

deepMerge(unifiedConfig, this.#internalTools);

return unifiedConfig;
}

/**
* Returns inline tools got from the EditorConfig tools
* Validate Tools configuration objects and throw Error for user if it is invalid
*/
public getInlineTools(): InlineToolsConfig {
#validateTools(): void {
/**
* Check Tools for a class containing
*/
for (const toolName in this.#config) {
if (Object.prototype.hasOwnProperty.call(this.#config, toolName)) {
// if (toolName in this.internalTools) {
// return;
// }

const tool = this.#config[toolName];

if (!isFunction(tool) && !isFunction((tool as ToolSettings).class)) {
throw Error(
`Tool «${toolName}» must be a constructor function or an object with function in the «class» property`
);
}
}
}
}

/**
* Returns internal tools
* Includes Bold, Italic, Link and Paragraph
*/
get #internalTools(): UnifiedToolConfig {
return {
bold: BoldInlineTool,
italic: ItalicInlineTool,
paragraph: {
/**
* @todo solve problems with types
*/
class: Paragraph as unknown as BlockToolConstructor,
inlineToolbar: true,
isInternal: true,
},
bold: {
class: BoldInlineTool as unknown as InlineToolConstructor,
isInternal: true,
},
italic: {
class: ItalicInlineTool as unknown as InlineToolConstructor,
isInternal: true,
},
};
};
}
}
Loading
Loading