-
Notifications
You must be signed in to change notification settings - Fork 2
Introduce DI & migrate tools builders #80
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2a88a52
Introduce DI & migrate tools builders
gohabereg 151f471
Fixes after review
gohabereg 4ff6f8e
Merge branch 'main' of github.com:editor-js/document-model into feat/…
gohabereg cbeb0cd
'Fix' lint
gohabereg 6b24e7b
Add unsaved files
gohabereg 153d09e
Fix comments
gohabereg ff2fb1b
Remove log & add docs
gohabereg 33a04bc
Update packages/core/src/entities/UnifiedToolConfig.ts
gohabereg 1ab1a6a
Fixes after review
gohabereg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'> & { | ||
/** | ||
* 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; | ||
}>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './Config.js'; | ||
export * from './UnifiedToolConfig.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | ||
|
@@ -42,6 +44,11 @@ export default class Core { | |
*/ | ||
#caretAdapter: CaretAdapter; | ||
|
||
/** | ||
* Inversion of Control container for dependency injections | ||
*/ | ||
#iocContainer: ContainerInstance; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
@@ -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 }); | ||
} | ||
|
@@ -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, | ||
}); | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}, | ||
}; | ||
}; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.