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(wysiwyg): allow to disable markdown-it-attrs in yfm preset #690

Merged
merged 1 commit into from
Mar 25, 2025
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
7 changes: 6 additions & 1 deletion demo/components/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
import {SplitModePreview} from './SplitModePreview';

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

Check warning on line 45 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)};
};
Expand Down Expand Up @@ -79,6 +79,7 @@
onChangeSplitModeEnabled?: (splitModeEnabled: boolean) => void;
directiveSyntax?: DirectiveSyntaxValue;
disabledHTMLBlockModes?: EmbeddingMode[];
disableMarkdownItAttrs?: boolean;
} & Pick<UseMarkdownEditorProps, 'experimental' | 'wysiwygConfig'> &
Pick<
MarkdownEditorViewProps,
Expand All @@ -91,12 +92,12 @@
>;

logger.setLogger({
log: (...data) => console.log('[Deprecated logger]', ...data),

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

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
info: (...data) => console.info('[Deprecated logger]', ...data),

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

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
warn: (...data) => console.warn('[Deprecated logger]', ...data),

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

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
error: (...data) => console.error('[Deprecated logger]', ...data),

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

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
metrics: (...data) => console.info('[Deprecated logger]', ...data),

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

View workflow job for this annotation

GitHub Actions / Verify Files

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

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

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected console statement
});

export const Playground = memo<PlaygroundProps>((props) => {
Expand Down Expand Up @@ -128,6 +129,7 @@
experimental,
directiveSyntax,
disabledHTMLBlockModes,
disableMarkdownItAttrs,
} = props;
const [editorMode, setEditorMode] = useState<MarkdownEditorMode>(initialEditor ?? 'wysiwyg');
const [mdRaw, setMdRaw] = useState<MarkupString>(initial || '');
Expand All @@ -137,7 +139,7 @@
}, [mdRaw]);

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

Check warning on line 142 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 130 column 9
<SplitModePreview
getValue={getValue}
allowHTML={md.html}
Expand All @@ -146,13 +148,14 @@
breaks={md.breaks}
needToSanitizeHtml={sanitizeHtml}
plugins={getPlugins({directiveSyntax})}
disableMarkdownItAttrs={disableMarkdownItAttrs}
htmlRuntimeConfig={{disabledModes: disabledHTMLBlockModes}}
/>
),
[sanitizeHtml, disabledHTMLBlockModes],
[sanitizeHtml, disabledHTMLBlockModes, disableMarkdownItAttrs],
);

const logger = useMemo(() => new Logger2().nested({env: 'playground'}), []);

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

View workflow job for this annotation

GitHub Actions / Verify Files

'logger' is already declared in the upper scope on line 27 column 5
useLogs(logger);

const mdEditor = useMarkdownEditor(
Expand All @@ -161,6 +164,7 @@
preset: 'full',
wysiwygConfig: {
placeholderOptions: placeholderOptions,
disableMarkdownAttrs: disableMarkdownItAttrs,
extensions: (builder) => {
builder
.use(Math, {
Expand Down Expand Up @@ -250,6 +254,7 @@
experimental?.beforeEditorModeChange,
experimental?.prepareRawMarkup,
directiveSyntax,
disableMarkdownItAttrs,
],
);

Expand All @@ -270,7 +275,7 @@
setEditorMode(mode);
}
const onToolbarAction = ({id, editorMode: type}: ToolbarActionData) => {
console.info(`The '${id}' action is performed in the ${type}-editor.`);

Check warning on line 278 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);
Expand Down
1 change: 1 addition & 0 deletions demo/components/PlaygroundMini.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type PlaygroundMiniProps = Pick<
| 'onChangeSplitModeEnabled'
| 'directiveSyntax'
| 'disabledHTMLBlockModes'
| 'disableMarkdownItAttrs'
> & {withDefaultInitialContent?: boolean};

export const PlaygroundMini = memo<PlaygroundMiniProps>(
Expand Down
11 changes: 9 additions & 2 deletions demo/components/SplitModePreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ const Preview = withMermaid({runtime: MERMAID_RUNTIME})(
);

export type SplitModePreviewProps = {
plugins?: MarkdownIt.PluginSimple[];
plugins: MarkdownIt.PluginSimple[];
getValue: () => MarkupString;
allowHTML?: boolean;
breaks?: boolean;
linkify?: boolean;
linkifyTlds?: string | string[];
needToSanitizeHtml?: boolean;
htmlRuntimeConfig?: HTMLRuntimeConfig;
disableMarkdownItAttrs?: boolean;
};

export const SplitModePreview: React.FC<SplitModePreviewProps> = (props) => {
Expand All @@ -45,6 +46,7 @@ export const SplitModePreview: React.FC<SplitModePreviewProps> = (props) => {
linkifyTlds,
needToSanitizeHtml,
htmlRuntimeConfig,
disableMarkdownItAttrs,
} = props;
const [html, setHtml] = useState('');
const [meta, setMeta] = useState<object | undefined>({});
Expand All @@ -58,12 +60,17 @@ export const SplitModePreview: React.FC<SplitModePreviewProps> = (props) => {
const res = transform(getValue(), {
allowHTML,
breaks,
plugins,
linkify,
linkifyTlds,
needToSanitizeHtml,
linkAttrs: [[ML_ATTR, true]],
defaultClassName: colorClassName,
plugins: [
...plugins,
...(disableMarkdownItAttrs
? [(md: MarkdownIt) => md.core.ruler.disable('curly_attributes')]
: []),
],
}).result;
setHtml(res.html);
setMeta(res.meta);
Expand Down
1 change: 1 addition & 0 deletions demo/defaults/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ export const args: Meta<PlaygroundMiniProps>['args'] = {
height: 'initial',
directiveSyntax: 'disabled',
disabledHTMLBlockModes: [],
disableMarkdownItAttrs: true,
};
6 changes: 5 additions & 1 deletion demo/stories/playground/Playground.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {type PlaygroundProps, Playground as component} from '../../components/Pl
import {args} from '../../defaults/args';
import {getInitialMd} from '../../utils/getInitialMd';

export const Story: StoryObj<typeof component> = {};
export const Story: StoryObj<typeof component> = {
args: {
disableMarkdownItAttrs: true,
},
};
Story.storyName = 'Playground';

const meta: Meta<PlaygroundProps> = {
Expand Down
1 change: 1 addition & 0 deletions demo/stories/presets/Preset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export const Preset = memo<PresetDemoProps>((props) => {
splitModeEnabled: true,
},
wysiwygConfig: {
disableMarkdownAttrs: true,
extensionOptions: {
imgSize: {
parseInsertedUrlAsImage,
Expand Down
44 changes: 26 additions & 18 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@
"@codemirror/search": "~6.5.8",
"@codemirror/state": "~6.5.1",
"@codemirror/view": "~6.36.2",
"@diplodoc/utils": "^2.1.0",
"@gravity-ui/i18n": "^1.7.0",
"@gravity-ui/icons": "^2.12.0",
"@lezer/highlight": "~1.2.1",
Expand Down
7 changes: 7 additions & 0 deletions src/bundle/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ export type MarkdownEditorWysiwygConfig = {
extensionOptions?: ExtensionsOptions;
escapeConfig?: EscapeConfig;
placeholderOptions?: WysiwygPlaceholderOptions;
// MAJOR: remove markdown-it-attrs
/**
* Disable the markdown-it-attrs plugin in the markup parser.
*
* Note: The use of the markdown-it-attrs plugin will be removed in the next major version.
*/
disableMarkdownAttrs?: boolean;
};

export type MarkdownEditorOptions = {
Expand Down
1 change: 1 addition & 0 deletions src/bundle/useMarkdownEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export function useMarkdownEditor(
editor.emit('submit', null);
return true;
},
disableMdAttrs: wysiwygConfig.disableMarkdownAttrs,
preserveEmptyRows: experimental.preserveEmptyRows,
placeholderOptions: wysiwygConfig.placeholderOptions,
mdBreaks: md.breaks,
Expand Down
3 changes: 3 additions & 0 deletions src/bundle/wysiwyg-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export type BundlePresetOptions = ExtensionsOptions &
needToSetDimensionsForUploadedImages?: boolean;
enableNewImageSizeCalculation?: boolean;
directiveSyntax: DirectiveSyntaxContext;
// MAJOR: remove markdown-it-attrs
disableMdAttrs?: boolean;
};

declare global {
Expand Down Expand Up @@ -136,6 +138,7 @@ export const BundlePreset: ExtensionAuto<BundlePresetOptions> = (builder, opts)
};
const yfmOptions: BehaviorPresetOptions & YfmPresetOptions = {
...defaultOptions,
yfmConfigs: {disableAttrs: opts.disableMdAttrs, ...opts.yfmConfigs},
selectionContext: {config: wSelectionMenuConfigByPreset.yfm, ...opts.selectionContext},
commandMenu: {actions: wCommandMenuConfigByPreset.yfm, ...opts.commandMenu},
underline: {underlineKey: f.toPM(A.Underline), ...opts.underline},
Expand Down
13 changes: 9 additions & 4 deletions src/extensions/yfm/YfmConfigs/YfmConfigsSpecs/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import attrsPlugin, {type AttrsOptions} from 'markdown-it-attrs'; // eslint-disable-line import/no-extraneous-dependencies
import attrsPlugin, {type AttrsOptions} from 'markdown-it-attrs';

import type {ExtensionAuto} from '../../../../core';
import {noop} from '../../../../lodash';
import type {ExtensionAuto} from '#core';
import {noop} from 'src/lodash';

const defaultAttrsOpts: AttrsOptions = {
allowedAttributes: ['id'],
Expand All @@ -10,12 +10,17 @@ const defaultAttrsOpts: AttrsOptions = {
export type YfmConfigsSpecsOptions = {
/** markdown-it-attrs options */
attrs?: AttrsOptions;
/** Disable markdown-it-attrs plugin */
disableAttrs?: boolean;
};

export const YfmConfigsSpecs: ExtensionAuto<YfmConfigsSpecsOptions> = (builder, opts) => {
const attrsOpts = {...defaultAttrsOpts, ...opts.attrs};

builder.configureMd((md) => md.use<AttrsOptions>(attrsPlugin, attrsOpts), {text: false});
// MAJOR: remove markdown-it-attrs
if (!opts.disableAttrs) {
builder.configureMd((md) => md.use<AttrsOptions>(attrsPlugin, attrsOpts), {text: false});
}

// ignore yfm lint token
builder.addNode('__yfm_lint', () => ({
Expand Down
72 changes: 63 additions & 9 deletions src/extensions/yfm/YfmHeading/YfmHeading.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {builders} from 'prosemirror-test-builder';
import dd from 'ts-dedent';

import {parseDOM} from '../../../../tests/parse-dom';
import {createMarkupChecker} from '../../../../tests/sameMarkup';
Expand Down Expand Up @@ -73,21 +74,21 @@ describe('Heading extension', () => {
});

it('should parse few headings', () => {
const markup = `
# h1 {#one}
const markup = dd`
# h1 {#one}

## h2 {#two}
## h2 {#two}

### h3 {#three}
### h3 {#three}

#### h4 {#four}
#### h4 {#four}

##### h5 {#five}
##### h5 {#five}

###### h6 {#six}
###### h6 {#six}

para
`.trim();
para
`.trim();

same(
markup,
Expand All @@ -103,6 +104,59 @@ para
);
});

it('should parse headings with id without markdown-it-attrs', () => {
const markup = dd`
# h1 {#one}

## h2 {#two}

### h3 {#three}

#### h4 {#four}

##### h5 {#five}

###### h6 {#six}

para
`.trim();

const {
schema,
markupParser: parser,
serializer,
} = new ExtensionsManager({
extensions: (builder) =>
builder
.use(BaseSchemaSpecs, {})
.use(YfmConfigsSpecs, {disableAttrs: true})
.use(YfmHeadingSpecs, {}),
}).buildDeps();
const {same} = createMarkupChecker({parser, serializer});

const {doc, p, h} = builders<
'doc' | 'p' | 'h' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6',
'b'
>(schema, {
doc: {nodeType: BaseNode.Doc},
p: {nodeType: BaseNode.Paragraph},
h: {nodeType: headingNodeName},
});

same(
markup,
doc(
h({[YfmHeadingAttr.Level]: 1, [YfmHeadingAttr.Id]: 'one'}, 'h1'),
h({[YfmHeadingAttr.Level]: 2, [YfmHeadingAttr.Id]: 'two'}, 'h2'),
h({[YfmHeadingAttr.Level]: 3, [YfmHeadingAttr.Id]: 'three'}, 'h3'),
h({[YfmHeadingAttr.Level]: 4, [YfmHeadingAttr.Id]: 'four'}, 'h4'),
h({[YfmHeadingAttr.Level]: 5, [YfmHeadingAttr.Id]: 'five'}, 'h5'),
h({[YfmHeadingAttr.Level]: 6, [YfmHeadingAttr.Id]: 'six'}, 'h6'),
p('para'),
),
);
});

it.each([1, 2, 3, 4, 5, 6])('should parse html - h%s tag', (lvl) => {
parseDOM(
schema,
Expand Down
7 changes: 4 additions & 3 deletions src/extensions/yfm/YfmHeading/YfmHeadingSpecs/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type {Node, NodeSpec} from 'prosemirror-model';

import type {ExtensionAuto} from '../../../../core';
import type {ExtensionAuto} from '#core';
import type {Node, NodeSpec} from '#pm/model';

import {YfmHeadingAttr, headingNodeName} from './const';
import {headingAttrsPlugin} from './markdown/heading-attrs';
import {getNodeAttrs} from './utils';

const DEFAULT_PLACEHOLDER = (node: Node) => 'Heading ' + node.attrs[YfmHeadingAttr.Level];
Expand All @@ -18,6 +18,7 @@ export type YfmHeadingSpecsOptions = {

/** YfmHeading extension needs markdown-it-attrs plugin */
export const YfmHeadingSpecs: ExtensionAuto<YfmHeadingSpecsOptions> = (builder, opts) => {
builder.configureMd((md) => md.use(headingAttrsPlugin));
builder.addNode(headingNodeName, () => ({
spec: {
attrs: {
Expand Down
Loading