Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
7cc0a7a
Support delimiter
TatianaFomina Apr 17, 2024
11de62f
Rename types, move types to popover-item folder
TatianaFomina Apr 19, 2024
738da13
Fix ts errors
TatianaFomina Apr 19, 2024
d73c9d4
Add tests
TatianaFomina Apr 19, 2024
10eed56
Review fixes
TatianaFomina Apr 19, 2024
eb3891a
Review fixes 2
TatianaFomina Apr 19, 2024
743c78e
Fix delimiter while search
TatianaFomina Apr 19, 2024
130c586
Fix flipper issue
TatianaFomina Apr 19, 2024
58fb475
Fix block tunes types
TatianaFomina Apr 19, 2024
abe5e6d
Fix types
TatianaFomina Apr 20, 2024
1f113da
tmp
TatianaFomina Apr 20, 2024
c8e2e01
Fixes
TatianaFomina Apr 20, 2024
6cebaf6
Merge branch 'feat/delimiter' into feat/new-convert-to
TatianaFomina Apr 20, 2024
df5ce10
Make search input emit event
TatianaFomina Apr 20, 2024
4f29cd4
Merge branch 'feat/delimiter' into feat/new-convert-to
TatianaFomina Apr 20, 2024
346a9a4
Fix types
TatianaFomina Apr 20, 2024
751e282
Merge branch 'feat/delimiter' into feat/new-convert-to
TatianaFomina Apr 20, 2024
b7080a6
Rename delimiter to separator
TatianaFomina Apr 20, 2024
e547249
Update chengelog
TatianaFomina Apr 20, 2024
e0f98e6
Merge branch 'feat/delimiter' into feat/new-convert-to
TatianaFomina Apr 20, 2024
48a50c4
Add convert to to block tunes
TatianaFomina Apr 21, 2024
5cb4b56
i18n
TatianaFomina Apr 21, 2024
112e8e0
Lint
TatianaFomina Apr 21, 2024
7b8491f
Fix tests
TatianaFomina Apr 21, 2024
18f6c68
Fix tests 2
TatianaFomina Apr 21, 2024
ffd768d
Tests
TatianaFomina Apr 21, 2024
e5e654c
Add caching
TatianaFomina Apr 21, 2024
a66d37b
Rename
TatianaFomina Apr 22, 2024
c79c029
Fix for miltiple toolbox entries
TatianaFomina Apr 24, 2024
158d68d
Merge branch 'next' into feat/new-convert-to
TatianaFomina Apr 24, 2024
8e5e992
Update changelog
TatianaFomina Apr 24, 2024
4dfa457
Update changelog
TatianaFomina Apr 25, 2024
53e4da0
Fix popover test
TatianaFomina Apr 25, 2024
49382e6
Fix flipper tests
TatianaFomina Apr 25, 2024
ab79dee
Fix popover tests
TatianaFomina Apr 25, 2024
96f8f6b
Remove type: 'default'
TatianaFomina Apr 25, 2024
ad0e9cf
Create isSameBlockData util
TatianaFomina Apr 25, 2024
65f34cf
Add testcase
TatianaFomina Apr 26, 2024
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
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

– `New` – Block Tunes now supports nesting items
– `New` – Block Tunes now supports separator items
– `New` – "Convert to" control is now also available in Block Tunes

### 2.30.0

Expand Down
81 changes: 61 additions & 20 deletions src/components/block/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ import BlockTune from '../tools/tune';
import { BlockTuneData } from '../../../types/block-tunes/block-tune-data';
import ToolsCollection from '../tools/collection';
import EventsDispatcher from '../utils/events';
import { TunesMenuConfigItem } from '../../../types/tools';
import { TunesMenuConfig, TunesMenuConfigItem } from '../../../types/tools';
import { isMutationBelongsToElement } from '../utils/mutations';
import { EditorEventMap, FakeCursorAboutToBeToggled, FakeCursorHaveBeenSet, RedactorDomChanged } from '../events';
import { RedactorDomChangedPayload } from '../events/RedactorDomChanged';
import { convertBlockDataToString } from '../utils/blocks';
import { convertBlockDataToString, isSameBlockData } from '../utils/blocks';

/**
* Interface describes Block class constructor argument
Expand Down Expand Up @@ -229,7 +229,6 @@ export default class Block extends EventsDispatcher<BlockEvents> {
tunesData,
}: BlockConstructorOptions, eventBus?: EventsDispatcher<EditorEventMap>) {
super();

this.name = tool.name;
this.id = id;
this.settings = tool.settings;
Expand Down Expand Up @@ -612,34 +611,60 @@ export default class Block extends EventsDispatcher<BlockEvents> {

/**
* Returns data to render in tunes menu.
* Splits block tunes settings into 2 groups: popover items and custom html.
*/
public getTunes(): [PopoverItemParams[], HTMLElement] {
* Splits block tunes into 3 groups: block specific tunes, common tunes
* and custom html that is produced by combining tunes html from both previous groups
*/
public getTunes(): {
toolTunes: PopoverItemParams[];
commonTunes: PopoverItemParams[];
customHtmlTunes: HTMLElement
} {
const customHtmlTunesContainer = document.createElement('div');
const tunesItems: TunesMenuConfigItem[] = [];
const commonTunesPopoverParams: TunesMenuConfigItem[] = [];

/** Tool's tunes: may be defined as return value of optional renderSettings method */
const tunesDefinedInTool = typeof this.toolInstance.renderSettings === 'function' ? this.toolInstance.renderSettings() : [];

/** Separate custom html from Popover items params for tool's tunes */
const {
items: toolTunesPopoverParams,
htmlElement: toolTunesHtmlElement,
} = this.getTunesDataSegregated(tunesDefinedInTool);

if (toolTunesHtmlElement !== undefined) {
customHtmlTunesContainer.appendChild(toolTunesHtmlElement);
}

/** Common tunes: combination of default tunes (move up, move down, delete) and third-party tunes connected via tunes api */
const commonTunes = [
...this.tunesInstances.values(),
...this.defaultTunesInstances.values(),
].map(tuneInstance => tuneInstance.render());

[tunesDefinedInTool, commonTunes].flat().forEach(rendered => {
if ($.isElement(rendered)) {
customHtmlTunesContainer.appendChild(rendered);
} else if (Array.isArray(rendered)) {
tunesItems.push(...rendered);
} else {
tunesItems.push(rendered);
/** Separate custom html from Popover items params for common tunes */
commonTunes.forEach(tuneConfig => {
const {
items,
htmlElement,
} = this.getTunesDataSegregated(tuneConfig);

if (htmlElement !== undefined) {
customHtmlTunesContainer.appendChild(htmlElement);
}

if (items !== undefined) {
commonTunesPopoverParams.push(...items);
}
});

return [tunesItems, customHtmlTunesContainer];
return {
toolTunes: toolTunesPopoverParams,
commonTunes: commonTunesPopoverParams,
customHtmlTunes: customHtmlTunesContainer,
};
}


/**
* Update current input index with selection anchor node
*/
Expand Down Expand Up @@ -711,11 +736,8 @@ export default class Block extends EventsDispatcher<BlockEvents> {
const blockData = await this.data;
const toolboxItems = toolboxSettings;

return toolboxItems.find((item) => {
return Object.entries(item.data)
.some(([propName, propValue]) => {
return blockData[propName] && _.equals(blockData[propName], propValue);
});
return toolboxItems?.find((item) => {
return isSameBlockData(item.data, blockData);
});
}

Expand All @@ -728,6 +750,25 @@ export default class Block extends EventsDispatcher<BlockEvents> {
return convertBlockDataToString(blockData, this.tool.conversionConfig);
}

/**
* Determines if tool's tunes settings are custom html or popover params and separates one from another by putting to different object fields
*
* @param tunes - tool's tunes config
*/
private getTunesDataSegregated(tunes: HTMLElement | TunesMenuConfig): { htmlElement?: HTMLElement; items: PopoverItemParams[] } {
const result = { } as { htmlElement?: HTMLElement; items: PopoverItemParams[] };

if ($.isElement(tunes)) {
result.htmlElement = tunes as HTMLElement;
} else if (Array.isArray(tunes)) {
result.items = tunes as PopoverItemParams[];
} else {
result.items = [ tunes ];
}

return result;
}

/**
* Make default Block wrappers and put Tool`s content there
*
Expand Down
3 changes: 2 additions & 1 deletion src/components/i18n/locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
},
"popover": {
"Filter": "",
"Nothing found": ""
"Nothing found": "",
"Convert to": ""
}
},
"toolNames": {
Expand Down
135 changes: 125 additions & 10 deletions src/components/modules/toolbar/blockSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ import { I18nInternalNS } from '../../i18n/namespace-internal';
import Flipper from '../../flipper';
import { TunesMenuConfigItem } from '../../../../types/tools';
import { resolveAliases } from '../../utils/resolve-aliases';
import { type Popover, PopoverDesktop, PopoverMobile } from '../../utils/popover';
import { type Popover, PopoverDesktop, PopoverMobile, PopoverItemParams, PopoverItemDefaultParams } from '../../utils/popover';
import { PopoverEvent } from '../../utils/popover/popover.types';
import { isMobileScreen } from '../../utils';
import { EditorMobileLayoutToggled } from '../../events';
import * as _ from '../../utils';
import { IconReplace } from '@codexteam/icons';
import { isSameBlockData } from '../../utils/blocks';

/**
* HTML Elements that used for BlockSettings
Expand Down Expand Up @@ -105,7 +108,7 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {
*
* @param targetBlock - near which Block we should open BlockSettings
*/
public open(targetBlock: Block = this.Editor.BlockManager.currentBlock): void {
public async open(targetBlock: Block = this.Editor.BlockManager.currentBlock): Promise<void> {
this.opened = true;

/**
Expand All @@ -120,10 +123,8 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {
this.Editor.BlockSelection.selectBlock(targetBlock);
this.Editor.BlockSelection.clearCache();

/**
* Fill Tool's settings
*/
const [tunesItems, customHtmlTunesContainer] = targetBlock.getTunes();
/** Get tool's settings data */
const { toolTunes, commonTunes, customHtmlTunes } = targetBlock.getTunes();

/** Tell to subscribers that block settings is opened */
this.eventsDispatcher.emit(this.events.opened);
Expand All @@ -132,9 +133,9 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {

this.popover = new PopoverClass({
searchable: true,
items: tunesItems.map(tune => this.resolveTuneAliases(tune)),
customContent: customHtmlTunesContainer,
customContentFlippableItems: this.getControls(customHtmlTunesContainer),
items: await this.getTunesItems(targetBlock, commonTunes, toolTunes),
customContent: customHtmlTunes,
customContentFlippableItems: this.getControls(customHtmlTunes),
scopeElement: this.Editor.API.methods.ui.nodes.redactor,
messages: {
nothingFound: I18n.ui(I18nInternalNS.ui.popover, 'Nothing found'),
Expand Down Expand Up @@ -197,6 +198,117 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {
}
};

/**
* Returns list of items to be displayed in block tunes menu.
* Merges tool specific tunes, conversion menu and common tunes in one list in predefined order
*
* @param currentBlock – block we are about to open block tunes for
* @param commonTunes – common tunes
* @param toolTunes - tool specific tunes
*/
private async getTunesItems(currentBlock: Block, commonTunes: TunesMenuConfigItem[], toolTunes?: TunesMenuConfigItem[]): Promise<PopoverItemParams[]> {
const items = [] as TunesMenuConfigItem[];

if (toolTunes !== undefined && toolTunes.length > 0) {
items.push(...toolTunes);
items.push({
type: 'separator',
});
}

const convertToItems = await this.getConvertToItems(currentBlock);

if (convertToItems.length > 0) {
items.push({
icon: IconReplace,
title: I18n.ui(I18nInternalNS.ui.popover, 'Convert to'),
children: {
items: convertToItems,
},
});
items.push({
type: 'separator',
});
}

items.push(...commonTunes);

return items.map(tune => this.resolveTuneAliases(tune));
}

/**
* Returns list of all available conversion menu items
*
* @param currentBlock - block we are about to open block tunes for
*/
private async getConvertToItems(currentBlock: Block): Promise<PopoverItemDefaultParams[]> {
Copy link
Member

Choose a reason for hiding this comment

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

It seems the comment about cache is relevant again now

Copy link
Contributor Author

Choose a reason for hiding this comment

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

can not cache. "Convert to" items list is different every time. For each block there will be different subset of tools it can be converted to. It depends on current block type and data

const conversionEntries = Array.from(this.Editor.Tools.blockTools.entries());

const resultItems: PopoverItemDefaultParams[] = [];

const blockData = await currentBlock.data;

conversionEntries.forEach(([toolName, tool]) => {
const conversionConfig = tool.conversionConfig;

/**
* Skip tools without «import» rule specified
*/
if (!conversionConfig || !conversionConfig.import) {
return;
}

tool.toolbox?.forEach((toolboxItem) => {
/**
* Skip tools that don't pass 'toolbox' property
*/
if (_.isEmpty(toolboxItem) || !toolboxItem.icon) {
return;
}

let shouldSkip = false;

if (toolboxItem.data !== undefined) {
/**
* When a tool has several toolbox entries, we need to make sure we do not add
* toolbox item with the same data to the resulting array. This helps exclude duplicates
*/
const hasSameData = isSameBlockData(toolboxItem.data, blockData);

shouldSkip = hasSameData;
} else {
shouldSkip = toolName === currentBlock.name;
}


if (shouldSkip) {
return;
}

resultItems.push({
icon: toolboxItem.icon,
title: toolboxItem.title,
name: toolName,
onActivate: () => {
const { BlockManager, BlockSelection, Caret } = this.Editor;

BlockManager.convert(this.Editor.BlockManager.currentBlock, toolName, toolboxItem.data);

BlockSelection.clearSelection();

this.close();

window.requestAnimationFrame(() => {
Caret.setToBlock(this.Editor.BlockManager.currentBlock, Caret.positions.END);
});
},
});
});
});

return resultItems;
}

/**
* Handles popover close event
*/
Expand Down Expand Up @@ -224,7 +336,10 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {
*
* @param item - item with resolved aliases
*/
private resolveTuneAliases(item: TunesMenuConfigItem): TunesMenuConfigItem {
private resolveTuneAliases(item: TunesMenuConfigItem): PopoverItemParams {
if (item.type === 'separator') {
return item;
}
const result = resolveAliases(item, { label: 'title' });

if (item.confirmation) {
Expand Down
15 changes: 14 additions & 1 deletion src/components/utils/blocks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ConversionConfig } from '../../../types/configs/conversion-config';
import type { BlockToolData } from '../../../types/tools/block-tool-data';
import type Block from '../block';
import { isFunction, isString, log } from '../utils';
import { isFunction, isString, log, equals } from '../utils';


/**
* Check if block has valid conversion config for export or import.
Expand All @@ -19,6 +20,18 @@ export function isBlockConvertable(block: Block, direction: 'export' | 'import')
return isFunction(conversionProp) || isString(conversionProp);
}

/**
* Checks that all the properties of the first block data exist in second block data with the same values.
*
* @param data1 – first block data
* @param data2 – second block data
*/
export function isSameBlockData(data1: BlockToolData, data2: BlockToolData): boolean {
return Object.entries(data1).some((([propName, propValue]) => {
return data2[propName] && equals(data2[propName], propValue);
}));
}

/**
* Check if two blocks could be merged.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface PopoverItemDefaultBaseParams {
/**
* Item type
*/
type: 'default';
type?: 'default';

/**
* Displayed text
Expand Down
Loading