Skip to content

Commit

Permalink
fix PR
Browse files Browse the repository at this point in the history
  • Loading branch information
PMAWorks committed Dec 16, 2024
1 parent 4ef6f8d commit 533d944
Show file tree
Hide file tree
Showing 11 changed files with 136 additions and 150 deletions.
6 changes: 3 additions & 3 deletions demo/components/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export type PlaygroundProps = {
allowHTML?: boolean;
settingsVisible?: boolean;
initialEditor?: MarkdownEditorMode;
allowEmptyRows?: boolean;
preserveEmptyRows?: boolean;
breaks?: boolean;
linkify?: boolean;
linkifyTlds?: string | string[];
Expand Down Expand Up @@ -127,7 +127,7 @@ export const Playground = React.memo<PlaygroundProps>((props) => {
allowHTML,
breaks,
linkify,
allowEmptyRows,
preserveEmptyRows,
linkifyTlds,
sanitizeHtml,
prepareRawMarkup,
Expand Down Expand Up @@ -192,7 +192,7 @@ export const Playground = React.memo<PlaygroundProps>((props) => {
directiveSyntax,
},
md: {
allowEmptyRows: allowEmptyRows,
preserveEmptyRows: preserveEmptyRows,
},
prepareRawMarkup: prepareRawMarkup
? (value) => '**prepare raw markup**\n\n' + value
Expand Down
2 changes: 1 addition & 1 deletion src/bundle/Editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ export class EditorImpl extends SafeEventEmitter<EventMapInt> implements EditorI
keymaps: this.#markupConfig.keymaps,
yfmLangOptions: {
languageData: getAutocompleteConfig({
allowEmptyRows: this.#mdOptions.allowEmptyRows,
preserveEmptyRows: this.#mdOptions.preserveEmptyRows,
}),
},
autocompletion: this.#markupConfig.autocompletion,
Expand Down
2 changes: 1 addition & 1 deletion src/bundle/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export type ParseInsertedUrlAsImage = (text: string) => {imageUrl: string; title

export type MarkdownEditorMdOptions = {
html?: boolean;
allowEmptyRows?: boolean;
preserveEmptyRows?: boolean;
breaks?: boolean;
linkify?: boolean;
linkifyTlds?: string | string[];
Expand Down
8 changes: 4 additions & 4 deletions src/bundle/useMarkdownEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function useMarkdownEditor<T extends object = {}>(
} = props;

const breaks = md.breaks ?? props.breaks;
const allowEmptyRows = md.allowEmptyRows;
const preserveEmptyRows = md.preserveEmptyRows;
const preset: MarkdownEditorPreset = props.preset ?? 'full';
const renderStorage = new ReactRenderStorage();
const uploadFile = handlers.uploadFile ?? props.fileUploadHandler;
Expand All @@ -44,7 +44,7 @@ export function useMarkdownEditor<T extends object = {}>(
const enableNewImageSizeCalculation = experimental.enableNewImageSizeCalculation;

const pmTransformers = getPMTransformers({
emptyRowTransformer: allowEmptyRows,
emptyRowTransformer: preserveEmptyRows,
});

const directiveSyntax = new DirectiveSyntaxContext(experimental.directiveSyntax);
Expand All @@ -65,7 +65,7 @@ export function useMarkdownEditor<T extends object = {}>(
editor.emit('submit', null);
return true;
},
allowEmptyRows: allowEmptyRows,
preserveEmptyRows: preserveEmptyRows,
mdBreaks: breaks,
fileUploadHandler: uploadFile,
needToSetDimensionsForUploadedImages,
Expand All @@ -89,7 +89,7 @@ export function useMarkdownEditor<T extends object = {}>(
html: md.html ?? props.allowHTML,
linkify: md.linkify ?? props.linkify,
linkifyTlds: md.linkifyTlds ?? props.linkifyTlds,
pmTransformers: pmTransformers,
pmTransformers,
},
initial: {
...initial,
Expand Down
4 changes: 2 additions & 2 deletions src/bundle/wysiwyg-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export type BundlePresetOptions = ExtensionsOptions &
EditorModeKeymapOptions & {
preset: MarkdownEditorPreset;
mdBreaks?: boolean;
allowEmptyRows?: boolean;
preserveEmptyRows?: boolean;
fileUploadHandler?: FileUploadHandler;
/**
* If we need to set dimensions for uploaded images
Expand Down Expand Up @@ -68,7 +68,7 @@ export const BundlePreset: ExtensionAuto<BundlePresetOptions> = (builder, opts)
!node.text && parent?.type.name === BaseNode.Doc && parent.childCount === 1;
return isDocEmpty ? i18nPlaceholder('doc_empty') : null;
},
allowEmptyRows: opts.allowEmptyRows,
preserveEmptyRows: opts.preserveEmptyRows,
...opts.baseSchema,
},
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// TODO: add a new method to the ExtensionBuilder
import {transformEmptyParagraph} from './emptyRowParser';

import {TransformFn} from '.';
Expand Down
17 changes: 14 additions & 3 deletions src/extensions/base/BaseSchema/BaseSchemaSpecs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const pType = nodeTypeFactory(BaseNode.Paragraph);
export type BaseSchemaSpecsOptions = {
// This cannot be passed through placeholder option of BehaviorPreset because BasePreset initializes first
paragraphPlaceholder?: NonNullable<NodeSpec['placeholder']>['content'];
allowEmptyRows?: boolean;
preserveEmptyRows?: boolean;
};

export const BaseSchemaSpecs: ExtensionAuto<BaseSchemaSpecsOptions> = (builder, opts) => {
Expand Down Expand Up @@ -64,8 +64,19 @@ export const BaseSchemaSpecs: ExtensionAuto<BaseSchemaSpecsOptions> = (builder,
},
fromMd: {tokenSpec: {name: BaseNode.Paragraph, type: 'block'}},
toMd: (state, node, parent) => {
if (opts.allowEmptyRows && !node.content.size) {
const isParentEmpty = parent.content.size / parent.content.childCount === 2;
if (opts.preserveEmptyRows && !node.content.size) {
let isParentEmpty = true;

for (let index = 0; index < parent.content.childCount; index++) {
const parentChild = parent.content.child(index);
if (
parentChild.content.size !== 0 ||
parentChild.type.name !== 'paragraph'
) {
isParentEmpty = false;
}
}

if (!isParentEmpty) {
state.write('&nbsp;\n\n');
}
Expand Down
109 changes: 0 additions & 109 deletions src/markup/codemirror/autocomplete/directive.ts

This file was deleted.

11 changes: 6 additions & 5 deletions src/markup/codemirror/autocomplete/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import {directiveAutocomplete} from './directive';
import {mdAutocomplete} from '../yfm';

import {emptyRowAutocomplete} from './emptyRow';

type GetAutocompleteConfig = {
allowEmptyRows?: boolean;
preserveEmptyRows?: boolean;
};

export const getAutocompleteConfig = ({allowEmptyRows}: GetAutocompleteConfig) => {
export const getAutocompleteConfig = ({preserveEmptyRows}: GetAutocompleteConfig) => {
const autocompleteItems = [];

if (allowEmptyRows) {
if (preserveEmptyRows) {
autocompleteItems.push(emptyRowAutocomplete);
}

autocompleteItems.push(directiveAutocomplete);
autocompleteItems.push(mdAutocomplete);

return autocompleteItems;
};
102 changes: 100 additions & 2 deletions src/markup/codemirror/yfm.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import {CompletionSource} from '@codemirror/autocomplete';
import {Completion, CompletionSource, snippet} from '@codemirror/autocomplete';
import {markdown, markdownLanguage} from '@codemirror/lang-markdown';
import type {Extension} from '@codemirror/state';
import {Tag, tags} from '@lezer/highlight';
import type {DelimiterType, MarkdownConfig} from '@lezer/markdown';

import {capitalize} from '../../lodash';

import {DirectiveSyntaxFacet} from './directive-facet';

export const customTags = {
underline: Tag.define(),
monospace: Tag.define(),
Expand Down Expand Up @@ -60,6 +64,23 @@ const MarkedExtension = mdInlineFactory({
tag: customTags.marked,
});

export type YfmNoteType = 'info' | 'tip' | 'warning' | 'alert';
export const yfmNoteTypes: readonly YfmNoteType[] = ['info', 'tip', 'warning', 'alert'];
export const yfmNoteSnippetTemplate = (type: YfmNoteType) =>
`{% note ${type} %}\n\n#{}\n\n{% endnote %}\n\n` as const;
export const yfmNoteSnippets: Record<YfmNoteType, ReturnType<typeof snippet>> = {
info: snippet(yfmNoteSnippetTemplate('info')),
tip: snippet(yfmNoteSnippetTemplate('tip')),
warning: snippet(yfmNoteSnippetTemplate('warning')),
alert: snippet(yfmNoteSnippetTemplate('alert')),
};

export const yfmCutSnippetTemplate = '{% cut "#{title}" %}\n\n#{}\n\n{% endcut %}\n\n';
export const yfmCutSnippet = snippet(yfmCutSnippetTemplate);

export const yfmCutDirectiveSnippetTemplate = ':::cut [#{title}]\n#{}\n:::\n\n';
export const yfmCutDirectiveSnippet = snippet(yfmCutDirectiveSnippetTemplate);

export interface LanguageData {
autocomplete: CompletionSource;
[key: string]: any;
Expand All @@ -69,6 +90,79 @@ export interface YfmLangOptions {
languageData?: LanguageData[];
}

export const mdAutocomplete: LanguageData = {
autocomplete: (context) => {
const directiveContext = context.state.facet(DirectiveSyntaxFacet);

// TODO: add more actions and re-enable
// let word = context.matchBefore(/\/.*/);
// if (word) {
// return {
// from: word.from,
// options: [
// ...yfmNoteTypes.map<Completion>((type, index) => ({
// label: `/yfm note ${type}`,
// displayLabel: `YFM Note ${capitalize(type)}`,
// type: 'text',
// apply: yfmNoteSnippets[type],
// boost: -index,
// })),
// {
// label: '/yfm cut',
// displayLabel: 'YFM Cut',
// type: 'text',
// apply: directiveFacet.shouldInsertDirectiveMarkup('yfmCut')
// ? yfmCutDirectiveSnippet
// : yfmCutSnippet,
// },
// ],
// };
// }

const word = context.matchBefore(/^.*/);
if (directiveContext.option !== 'only' && word?.text.startsWith('{%')) {
return {
from: word.from,
options: [
...yfmNoteTypes.map<Completion>((type, index) => ({
label: `{% note ${type}`,
displayLabel: capitalize(type),
type: 'text',
section: 'YFM Note',
apply: yfmNoteSnippets[type],
boost: -index,
})),
{
label: '{% cut',
displayLabel: 'YFM Cut',
type: 'text',
apply: directiveContext.shouldInsertDirectiveMarkup('yfmCut')
? yfmCutDirectiveSnippet
: yfmCutSnippet,
},
],
};
}
if (directiveContext.option !== 'disabled' && word?.text.startsWith(':')) {
const options: Completion[] = [];

if (directiveContext.valueFor('yfmCut') !== 'disabled') {
options.push({
label: ':::cut',
displayLabel: 'YFM Cut',
type: 'text',
apply: yfmCutDirectiveSnippet,
});
}

if (options.length) {
return {from: word.from, options};
}
}
return null;
},
};

export function yfmLang({languageData = []}: YfmLangOptions = {}): Extension {
const mdSupport = markdown({
// defaultCodeLanguage: markdownLanguage,
Expand All @@ -78,5 +172,9 @@ export function yfmLang({languageData = []}: YfmLangOptions = {}): Extension {
extensions: [UnderlineExtension, MonospaceExtension, MarkedExtension],
});

return [mdSupport, languageData.map((item) => mdSupport.language.data.of(item))];
return [
mdSupport,
mdSupport.language.data.of(mdAutocomplete),
languageData.map((item) => mdSupport.language.data.of(item)),
];
}
Loading

0 comments on commit 533d944

Please sign in to comment.