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

feat(toolbars): restructured toolbar configuration and presets #509

Merged
merged 6 commits into from
Dec 19, 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
104 changes: 47 additions & 57 deletions demo/components/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
type UseMarkdownEditorProps,
WysiwygPlaceholderOptions,
logger,
markupToolbarConfigs,
useMarkdownEditor,
wysiwygToolbarConfigs,
} from '../../src';
Expand All @@ -29,8 +28,8 @@
import {Mermaid} from '../../src/extensions/additional/Mermaid';
import {YfmHtmlBlock} from '../../src/extensions/additional/YfmHtmlBlock';
import {getSanitizeYfmHtmlBlock} from '../../src/extensions/additional/YfmHtmlBlock/utils';
import {cloneDeep} from '../../src/lodash';
import type {CodeEditor} from '../../src/markup';
import {ToolbarsPreset} from '../../src/modules/toolbars/types';
import {VERSION} from '../../src/version';
import {getPlugins} from '../defaults/md-plugins';
import useYfmHtmlBlockStyles from '../hooks/useYfmHtmlBlockStyles';
Expand All @@ -47,24 +46,11 @@

const b = block('playground');
const fileUploadHandler: FileUploadHandler = async (file) => {
console.info('[Playground] Uploading file: ' + file.name);

Check warning on line 49 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
await randomDelay(1000, 3000);
return {url: URL.createObjectURL(file)};
};

const mToolbarConfig = [
...markupToolbarConfigs.mToolbarConfig,
[markupToolbarConfigs.mMermaidButton, markupToolbarConfigs.mYfmHtmlBlockButton],
];
mToolbarConfig[2].push(markupToolbarConfigs.mMathListItem);

const wToolbarConfig = cloneDeep(wysiwygToolbarConfigs.wToolbarConfig);
wToolbarConfig[2].push(wysiwygToolbarConfigs.wMathListItem);
wToolbarConfig.push([
wysiwygToolbarConfigs.wMermaidItemData,
wysiwygToolbarConfigs.wYfmHtmlBlockItemData,
]);

const wCommandMenuConfig = wysiwygToolbarConfigs.wCommandMenuConfig.concat(
wysiwygToolbarConfigs.wMathInlineItemData,
wysiwygToolbarConfigs.wMathBlockItemData,
Expand Down Expand Up @@ -92,6 +78,7 @@
escapeConfig?: EscapeConfig;
wysiwygCommandMenuConfig?: wysiwygToolbarConfigs.WToolbarItemData[];
markupToolbarConfig?: ToolbarGroupData<CodeEditor>[];
toolbarsPreset?: ToolbarsPreset;
onChangeEditorType?: (mode: MarkdownEditorMode) => void;
onChangeSplitModeEnabled?: (splitModeEnabled: boolean) => void;
directiveSyntax?: DirectiveSyntaxValue;
Expand All @@ -114,8 +101,8 @@
>;

logger.setLogger({
metrics: console.info,

Check warning on line 104 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
action: (data) => console.info(`Action: ${data.action}`, data),

Check warning on line 105 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
...console,
});

Expand All @@ -137,6 +124,7 @@
height,
extraExtensions,
extensionOptions,
toolbarsPreset,
wysiwygToolbarConfig,
wysiwygCommandMenuConfig,
markupConfigExtensions,
Expand All @@ -159,7 +147,7 @@
}, [mdRaw]);

const renderPreview = useCallback<RenderPreview>(
({getValue, md, directiveSyntax}) => (

Check warning on line 150 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

'directiveSyntax' is already declared in the upper scope on line 138 column 9
<SplitModePreview
getValue={getValue}
allowHTML={md.html}
Expand All @@ -175,6 +163,47 @@

const mdEditor = useMarkdownEditor(
{
preset: 'full',
wysiwygConfig: {
escapeConfig,
placeholderOptions: placeholderOptions,
extensions: (builder) => {
builder
.use(Math, {
loadRuntimeScript: () => {
import(
/* webpackChunkName: "latex-runtime" */ '@diplodoc/latex-extension/runtime'
);
import(
// @ts-expect-error // no types for styles
/* webpackChunkName: "latex-styles" */ '@diplodoc/latex-extension/runtime/styles'
);
},
})
.use(Mermaid, {
loadRuntimeScript: () => {
import(
/* webpackChunkName: "mermaid-runtime" */ '@diplodoc/mermaid-extension/runtime'
);
},
})
.use(FoldingHeading)
.use(YfmHtmlBlock, {
useConfig: useYfmHtmlBlockStyles,
sanitize: getSanitizeYfmHtmlBlock({options: defaultOptions}),
head: `
<base target="_blank" />
<style>
html, body {
margin: 0;
padding: 0;
}
</style
`,
});
if (extraExtensions) builder.use(extraExtensions);
},
},
allowHTML,
linkify,
linkifyTlds,
Expand All @@ -184,13 +213,9 @@
initialSplitModeEnabled: initialSplitModeEnabled,
initialToolbarVisible: true,
splitMode: splitModeOrientation,
escapeConfig: escapeConfig,
needToSetDimensionsForUploadedImages,
renderPreview: renderPreviewDefined ? renderPreview : undefined,
fileUploadHandler,
wysiwygConfig: {
placeholderOptions: placeholderOptions,
},
experimental: {
...experimental,
directiveSyntax,
Expand All @@ -209,42 +234,6 @@
extensions: markupConfigExtensions,
parseInsertedUrlAsImage,
},
extraExtensions: (builder) => {
builder
.use(Math, {
loadRuntimeScript: () => {
import(
/* webpackChunkName: "latex-runtime" */ '@diplodoc/latex-extension/runtime'
);
import(
// @ts-expect-error // no types for styles
/* webpackChunkName: "latex-styles" */ '@diplodoc/latex-extension/runtime/styles'
);
},
})
.use(Mermaid, {
loadRuntimeScript: () => {
import(
/* webpackChunkName: "mermaid-runtime" */ '@diplodoc/mermaid-extension/runtime'
);
},
})
.use(FoldingHeading)
.use(YfmHtmlBlock, {
useConfig: useYfmHtmlBlockStyles,
sanitize: getSanitizeYfmHtmlBlock({options: defaultOptions}),
head: `
<base target="_blank" />
<style>
html, body {
margin: 0;
padding: 0;
}
</style
`,
});
if (extraExtensions) builder.use(extraExtensions);
},
},
[
allowHTML,
Expand Down Expand Up @@ -282,14 +271,14 @@
setEditorMode(mode);
}
const onToolbarAction = ({id, editorMode: type}: ToolbarActionData) => {
console.info(`The '${id}' action is performed in the ${type}-editor.`);

Check warning on line 274 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
};
function onChangeSplitModeEnabled({splitModeEnabled}: {splitModeEnabled: boolean}) {
props.onChangeSplitModeEnabled?.(splitModeEnabled);
console.info(`Split mode enabled: ${splitModeEnabled}`);

Check warning on line 278 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
}
function onChangeToolbarVisibility({visible}: {visible: boolean}) {
console.info('Toolbar visible: ' + visible);

Check warning on line 281 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
}

mdEditor.on('cancel', onCancel);
Expand All @@ -309,7 +298,7 @@
mdEditor.off('change-split-mode-enabled', onChangeSplitModeEnabled);
mdEditor.off('change-toolbar-visibility', onChangeToolbarVisibility);
};
}, [mdEditor]);

Check warning on line 301 in demo/components/Playground.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect

return (
<div className={b()}>
Expand Down Expand Up @@ -394,8 +383,9 @@
toaster={toaster}
className={b('editor-view')}
stickyToolbar={Boolean(stickyToolbar)}
wysiwygToolbarConfig={wysiwygToolbarConfig ?? wToolbarConfig}
markupToolbarConfig={markupToolbarConfig ?? mToolbarConfig}
toolbarsPreset={toolbarsPreset}
wysiwygToolbarConfig={wysiwygToolbarConfig}
markupToolbarConfig={markupToolbarConfig}
settingsVisible={settingsVisible}
editor={mdEditor}
enableSubmitInPreview={enableSubmitInPreview}
Expand Down
4 changes: 4 additions & 0 deletions demo/stories/presets/Preset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
logger,
useMarkdownEditor,
} from '../../../src';
import {ToolbarsPreset} from '../../../src/modules/toolbars/types';
import type {FileUploadHandler} from '../../../src/utils/upload';
import {VERSION} from '../../../src/version';
// ---
Expand Down Expand Up @@ -41,6 +42,7 @@ export type PresetDemoProps = {
splitModeOrientation?: 'horizontal' | 'vertical' | false;
stickyToolbar?: boolean;
height?: CSSProperties['height'];
toolbarsPreset?: ToolbarsPreset;
};

logger.setLogger({
Expand All @@ -60,6 +62,7 @@ export const Preset = React.memo<PresetDemoProps>((props) => {
splitModeOrientation,
stickyToolbar,
height,
toolbarsPreset,
} = props;
const [editorMode, setEditorMode] = React.useState<MarkdownEditorMode>('wysiwyg');
const [mdRaw, setMdRaw] = React.useState<MarkupString>('');
Expand Down Expand Up @@ -130,6 +133,7 @@ export const Preset = React.memo<PresetDemoProps>((props) => {
<div className={b('editor')} style={{height: height ?? 'initial'}}>
<MarkdownEditorView
autofocus
toolbarsPreset={toolbarsPreset}
toaster={toaster}
className={b('editor-view')}
stickyToolbar={Boolean(stickyToolbar)}
Expand Down
62 changes: 62 additions & 0 deletions demo/stories/presets/Presets.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import {StoryObj} from '@storybook/react';

import {ActionName as Action} from '../../../src/bundle/config/action-names';
import {ToolbarName as Toolbar} from '../../../src/modules/toolbars/constants';
import {
boldItemView,
boldItemWysiwyg,
colorifyItemMarkup,
colorifyItemView,
colorifyItemWysiwyg,
italicItemMarkup,
italicItemView,
redoItemMarkup,
redoItemView,
redoItemWysiwyg,
undoItemMarkup,
undoItemView,
undoItemWysiwyg,
} from '../../../src/modules/toolbars/items';

import {Preset as component} from './Preset';

export const Zero: StoryObj<typeof component> = {
Expand All @@ -22,6 +40,50 @@ export const Full: StoryObj<typeof component> = {
args: {preset: 'full'},
};

export const Custom: StoryObj<typeof component> = {
args: {
toolbarsPreset: {
items: {
[Action.undo]: {
view: undoItemView,
wysiwyg: undoItemWysiwyg,
markup: undoItemMarkup,
},
[Action.redo]: {
view: redoItemView,
wysiwyg: redoItemWysiwyg,
markup: redoItemMarkup,
},
[Action.bold]: {
view: boldItemView,
wysiwyg: boldItemWysiwyg,
},
[Action.italic]: {
view: italicItemView,
markup: italicItemMarkup,
},
[Action.colorify]: {
view: colorifyItemView,
wysiwyg: colorifyItemWysiwyg,
markup: colorifyItemMarkup,
},
},
orders: {
[Toolbar.wysiwygMain]: [
[Action.colorify],
[Action.bold],
[Action.undo, Action.redo],
],
[Toolbar.markupMain]: [
[Action.colorify],
[Action.italic],
[Action.undo, Action.redo],
],
},
},
},
};

export default {
component,
title: 'Extensions / Presets',
Expand Down
62 changes: 48 additions & 14 deletions src/bundle/MarkdownEditorView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {useEnsuredForwardedRef, useKey, useUpdate} from 'react-use';
import {ClassNameProps, cn} from '../classname';
import {i18n} from '../i18n/bundle';
import {logger} from '../logger';
import type {ToolbarsPreset} from '../modules/toolbars/types';
import {ToasterContext, useBooleanState, useSticky} from '../react-utils';
import {isMac} from '../utils';

Expand All @@ -15,19 +16,11 @@ import {HorizontalDrag} from './HorizontalDrag';
import {MarkupEditorView} from './MarkupEditorView';
import {SplitModeView} from './SplitModeView';
import {WysiwygEditorView} from './WysiwygEditorView';
import {
MToolbarData,
MToolbarItemData,
WToolbarData,
WToolbarItemData,
mHiddenDataByPreset,
mToolbarConfigByPreset,
wHiddenDataByPreset,
wToolbarConfigByPreset,
} from './config';
import {MToolbarData, MToolbarItemData, WToolbarData, WToolbarItemData} from './config';
import {useMarkdownEditorContext} from './context';
import {EditorSettings, EditorSettingsProps} from './settings';
import {stickyCn} from './sticky';
import {getToolbarsConfigs} from './toolbar/utils';
import type {MarkdownEditorMode} from './types';

import '../styles/styles.scss';
Expand All @@ -39,9 +32,22 @@ const b = cnEditorComponent;
export type MarkdownEditorViewProps = ClassNameProps & {
editor?: Editor;
autofocus?: boolean;
toolbarsPreset?: ToolbarsPreset;
/**
* @deprecated use `toolbarsPreset` instead
*/
markupToolbarConfig?: MToolbarData;
/**
* @deprecated use `toolbarsPreset` instead
*/
wysiwygToolbarConfig?: WToolbarData;
/**
* @deprecated use `toolbarsPreset` instead
*/
markupHiddenActionsConfig?: MToolbarItemData[];
/**
* @deprecated use `toolbarsPreset` instead
*/
wysiwygHiddenActionsConfig?: WToolbarItemData[];
/** @default true */
settingsVisible?: boolean;
Expand Down Expand Up @@ -73,16 +79,44 @@ export const MarkdownEditorView = React.forwardRef<HTMLDivElement, MarkdownEdito
autofocus,
className,
settingsVisible = true,
markupToolbarConfig = mToolbarConfigByPreset[editor.preset],
wysiwygToolbarConfig = wToolbarConfigByPreset[editor.preset],
markupHiddenActionsConfig = mHiddenDataByPreset[editor.preset],
wysiwygHiddenActionsConfig = wHiddenDataByPreset[editor.preset],
toolbarsPreset,
toaster,
stickyToolbar,
wysiwygToolbarConfig: initialWysiwygToolbarConfig,
markupToolbarConfig: initialMarkupToolbarConfig,
wysiwygHiddenActionsConfig: initialWysiwygHiddenActionsConfig,
markupHiddenActionsConfig: initialMarkupHiddenActionsConfig,
enableSubmitInPreview = true,
hidePreviewAfterSubmit = false,
} = props;

const {
wysiwygToolbarConfig,
markupToolbarConfig,
wysiwygHiddenActionsConfig,
markupHiddenActionsConfig,
} = useMemo(
() =>
getToolbarsConfigs({
toolbarsPreset,
props: {
wysiwygToolbarConfig: initialWysiwygToolbarConfig,
markupToolbarConfig: initialMarkupToolbarConfig,
wysiwygHiddenActionsConfig: initialWysiwygHiddenActionsConfig,
markupHiddenActionsConfig: initialMarkupHiddenActionsConfig,
},
preset: editor.preset,
}),
[
toolbarsPreset,
initialWysiwygToolbarConfig,
initialMarkupToolbarConfig,
initialWysiwygHiddenActionsConfig,
initialMarkupHiddenActionsConfig,
editor.preset,
],
);

const rerender = useUpdate();
React.useLayoutEffect(() => {
editor.on('rerender', rerender);
Expand Down
Loading
Loading