Skip to content

Commit

Permalink
Merge pull request laobubu#26 from 0xGG/feat/render-preview
Browse files Browse the repository at this point in the history
feat: renderPreview is now more customizable
  • Loading branch information
shd101wyy authored Apr 5, 2020
2 parents 9a192df + 2d8ccbb commit cc10adb
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 41 deletions.
4 changes: 2 additions & 2 deletions demo/requirejs_packages.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ var requirejs_packages = [
{ name: "markdown-it-emoji", main: "dist/markdown-it-emoji.min.js" },
{
name: "markdown-it-task-lists",
main: "dist/markdown-it-task-lists.min.js"
main: "dist/markdown-it-task-lists.min.js",
},
// { name: "prismjs", main: "prism.min.js" }
// I still don't know how to import
{ name: "react-dom", main: "umd/react-dom.production.min.js" },
{ name: "react", main: "umd/react.production.min.js" }
{ name: "react", main: "umd/react.production.min.js" },

// Vega
// { name: "vega", main: "build/vega.min.js" } // <= vega AMD is not working
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vickymd",
"version": "0.1.9",
"version": "0.1.10",
"description": "An experimental WYSIWYG markdown editor built on top of HyperMD with extended Widgets support",
"main": "./everything.js",
"types": "./everything.d.ts",
Expand Down
21 changes: 12 additions & 9 deletions src/addon/fold-widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
registerFolder,
breakMark,
RequestRangeResult,
FoldStream
FoldStream,
} from "./fold";
import { Attributes } from "./attributes/index";
import { registerWidgetCreator, getWidgetCreator } from "../widget/index";
Expand All @@ -23,7 +23,7 @@ registerWidgetCreator("hello", HelloWidget);
registerWidgetCreator("error", ErrorWidget);
registerWidgetCreator("timer", TimerWidget);

export const WidgetFolder = function(
export const WidgetFolder = function (
stream: FoldStream,
token: CodeMirror.Token
): any {
Expand Down Expand Up @@ -58,10 +58,7 @@ export const WidgetFolder = function(
const firstSpaceMatch = str.match(/\s/);
const firstSpace = firstSpaceMatch ? firstSpaceMatch.index : -1;
if (firstSpace > 0) {
widgetName = str
.slice(0, firstSpace)
.trim()
.replace(/^@/, "");
widgetName = str.slice(0, firstSpace).trim().replace(/^@/, "");
try {
const j = str.slice(firstSpace + 1).trim();
if (j[0] === "{") {
Expand Down Expand Up @@ -99,7 +96,10 @@ export const WidgetFolder = function(
if (!editor || !marker) {
return;
}
let pos = marker.find();
const pos = marker.find();
if (!pos) {
return;
}
let widgetFrom: CodeMirror.Position = pos.from;
let widgetTo: CodeMirror.Position = pos.to;
const line = editor.getLine(widgetFrom.line);
Expand Down Expand Up @@ -137,6 +137,9 @@ export const WidgetFolder = function(
return;
}
const pos = marker.find();
if (!pos) {
return;
}
let widgetFrom: CodeMirror.Position = pos.from;
let widgetTo: CodeMirror.Position = pos.to;
const line = editor.getLine(widgetFrom.line);
Expand All @@ -163,7 +166,7 @@ export const WidgetFolder = function(
setAttributes: setAttributes,
removeSelf: removeSelf,
replaceSelf: replaceSelf,
isPreview: false
isPreview: false,
});
}

Expand All @@ -172,7 +175,7 @@ export const WidgetFolder = function(
replacedWith: widget,
collapsed: true,
inclusiveLeft: true,
inclusiveRight: true
inclusiveRight: true,
});

/*
Expand Down
100 changes: 71 additions & 29 deletions src/preview/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
breaks: true
breaks: true,
});

md.use(MarkdownItEmoji, { defs: EmojiDefinitions });
Expand All @@ -58,22 +58,18 @@ function renderMarkdown(markdown: string): RenderMarkdownOutput {
slideConfigs,
headings,
outputString,
frontMatterString
frontMatterString,
} = transformMarkdown(markdown, {
forPreview: true,
headingIdGenerator: new HeadingIdGenerator(),
forMarkdownExport: false,
usePandocParser: false
usePandocParser: false,
});

let yamlConfig = {};
try {
yamlConfig = YAML.parse(
frontMatterString
.trim()
.replace(/^\-+/, "")
.replace(/\-+$/, "")
.trim()
frontMatterString.trim().replace(/^\-+/, "").replace(/\-+$/, "").trim()
);
} catch (error) {
yamlConfig = {};
Expand All @@ -86,22 +82,22 @@ function renderMarkdown(markdown: string): RenderMarkdownOutput {
html,
headings,
slideConfigs,
yamlConfig
yamlConfig,
};
} else {
return {
html,
headings,
slideConfigs,
yamlConfig
yamlConfig,
};
}
} catch (error) {
return {
html: `Failed to render markdown:\n${JSON.stringify(error)}`,
headings: [],
slideConfigs: [],
yamlConfig: {}
yamlConfig: {},
};
}
}
Expand All @@ -125,7 +121,7 @@ const RevealJSThemes = {
"simple.css": "simple.css",
"sky.css": "sky.css",
"solarized.css": "solarized.css",
"white.css": "white.css"
"white.css": "white.css",
};

const AutoPrismThemeMapForPresentation = {
Expand All @@ -139,9 +135,22 @@ const AutoPrismThemeMapForPresentation = {
"simple.css": "github.css",
"sky.css": "default.css",
"solarized.css": "solarized-light.css",
"white.css": "default.css"
"white.css": "default.css",
};

interface Requires {
WaveDromSkinJS?: string;
WaveDromJS?: string;
MermaidJS?: string;
RevealJS?: string;
RevealCSS?: string;
RevealThemeCSSFunc?: (theme: string) => string;
RevealPrintPDFCSS?: string;
KaTeXCSS?: string;
PrismJS?: string;
PrismCSSFunc?: (theme: string) => string;
}

/**
* renderPreview
* @param previewElement, which should be <div> element
Expand All @@ -150,7 +159,8 @@ const AutoPrismThemeMapForPresentation = {
function renderPreview(
previewElement: HTMLElement,
markdown: string,
forRevealJSPrint: boolean = false
forRevealJSPrint: boolean = false,
requires: Requires = {}
) {
return new Promise((resolve, reject) => {
const { html, headings, slideConfigs, yamlConfig } = renderMarkdown(
Expand All @@ -172,8 +182,14 @@ function renderPreview(
let wavedromScript = "";
let wavedromInitScript = "";
if (html.indexOf("wavedrom") >= 0) {
wavedromScript += `<script src="https://cdn.jsdelivr.net/npm/wavedrom@2.3.0/skins/default.js"></script>`;
wavedromScript += `<script src="https://cdn.jsdelivr.net/npm/wavedrom@2.3.0/wavedrom.min.js"></script>`;
wavedromScript += `<script src="${
requires.WaveDromSkinJS ||
"https://cdn.jsdelivr.net/npm/wavedrom@2.3.2/skins/default.js"
}></script>`;
wavedromScript += `<script src=${
requires.WaveDromJS ||
"https://cdn.jsdelivr.net/npm/wavedrom@2.3.2/wavedrom.min.js"
}></script>`;
wavedromInitScript += `<script>
Reveal.addEventListener("ready", ()=> {
WaveDrom.ProcessAll()
Expand All @@ -185,7 +201,10 @@ function renderPreview(
let mermaidScript = "";
let mermaidInitScript = "";
if (html.indexOf("mermaid") >= 0) {
mermaidScript = `<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>`;
mermaidScript = `<script type="text/javascript" src=${
requires.MermaidJS ||
"https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"
}></script>`;
mermaidInitScript += `<script>
if (window['MERMAID_CONFIG']) {
window['MERMAID_CONFIG'].startOnLoad = false
Expand Down Expand Up @@ -238,19 +257,36 @@ function renderPreview(
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- reveal.js styles -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@3.8.0/css/reveal.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@3.8.0/css/theme/${revealJSTheme}">
<link rel="stylesheet" href=${
requires.RevealCSS ||
"https://cdn.jsdelivr.net/npm/reveal.js@3.9.2/css/reveal.css"
}>
<link rel="stylesheet" href=${
(requires.RevealThemeCSSFunc &&
requires.RevealThemeCSSFunc(revealJSTheme)) ||
`https://cdn.jsdelivr.net/npm/reveal.js@3.9.2/css/theme/${revealJSTheme}`
}>
${
forRevealJSPrint
? `<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@3.8.0/css/print/pdf.css">`
? `<link rel="stylesheet" href=${
requires.RevealPrintPDFCSS ||
"https://cdn.jsdelivr.net/npm/reveal.js@3.9.2/css/print/pdf.css"
}>`
: ""
}
<!-- katex -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css">
<link rel="stylesheet" href=${
requires.KaTeXCSS ||
"https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"
}>
<!-- prism github theme -->
<link href="https://cdn.jsdelivr.net/npm/@shd101wyy/mume@0.4.7/styles/prism_theme/${revealJSCodeBlockTheme}" rel="stylesheet">
<link href=${
(requires.PrismCSSFunc &&
requires.PrismCSSFunc(revealJSCodeBlockTheme)) ||
`https://cdn.jsdelivr.net/npm/@shd101wyy/mume@0.4.7/styles/prism_theme/${revealJSCodeBlockTheme}`
} rel="stylesheet">
<!-- mermaid -->
${mermaidScript}
Expand All @@ -271,10 +307,16 @@ function renderPreview(
`
: ""
}
<script src="https://cdn.jsdelivr.net/npm/reveal.js@3.8.0/js/reveal.min.js"></script>
<script src=${
requires.RevealJS ||
"https://cdn.jsdelivr.net/npm/reveal.js@3.9.2/js/reveal.min.js"
}></script>
<!-- prism.js -->
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.17.1/prism.min.js"></script>
<script src=${
requires.PrismJS ||
"https://cdn.jsdelivr.net/npm/prismjs@1.17.1/prism.min.js"
}></script>
<!-- mermaid -->
${mermaidInitScript}
Expand All @@ -286,15 +328,15 @@ function renderPreview(
<script>
Reveal.initialize(${JSON.stringify({
margin: 0.1,
...revealJSConfig
...revealJSConfig,
})});
Reveal.addEventListener('ready', function(event) {
parent.postMessage({event: "reveal-ready", id:"${id}"})
})
</script>
</html>`);
iframe.contentWindow.document.close();
window.addEventListener("message", function(event) {
window.addEventListener("message", function (event) {
if (
event.data &&
event.data.event === "reveal-ready" &&
Expand Down Expand Up @@ -331,7 +373,7 @@ function renderWidgets(previewElement: HTMLElement) {
}
widget = widgetCreator({
attributes: widgetAttributes,
isPreview: true
isPreview: true,
});
if (widget) {
widget.classList.add("vickymd-widget");
Expand Down Expand Up @@ -473,7 +515,7 @@ function printPDF(
restore();
return resolve();
})
.catch(error => {
.catch((error) => {
restore();
return reject(error);
});
Expand Down Expand Up @@ -538,7 +580,7 @@ function printPreview(
// elements whose positions need to be relative
const elements: HTMLElement[] = [];
const oldPositions: string[] = [];
elementsWhosePositionsToInitial.forEach(selector => {
elementsWhosePositionsToInitial.forEach((selector) => {
const elem = document.querySelector(selector) as HTMLElement;
if (elem) {
elements.push(elem);
Expand Down

0 comments on commit cc10adb

Please sign in to comment.