Path: blob/main/src/resources/formats/revealjs/reveal/plugin/markdown/plugin.js
12923 views
/*!1* The reveal.js markdown plugin. Handles parsing of2* markdown inside of presentations as well as loading3* of external markdown documents.4*/56import { marked } from 'marked';78const DEFAULT_SLIDE_SEPARATOR = '\r?\n---\r?\n',9DEFAULT_VERTICAL_SEPARATOR = null,10DEFAULT_NOTES_SEPARATOR = '^\s*notes?:',11DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',12DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';1314const SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';1516// match an optional line number offset and highlight line numbers17// [<line numbers>] or [<offset>: <line numbers>]18const CODE_LINE_NUMBER_REGEX = /\[\s*((\d*):)?\s*([\s\d,|-]*)\]/;1920const HTML_ESCAPE_MAP = {21'&': '&',22'<': '<',23'>': '>',24'"': '"',25"'": '''26};2728const Plugin = () => {2930// The reveal.js instance this plugin is attached to31let deck;3233/**34* Retrieves the markdown contents of a slide section35* element. Normalizes leading tabs/whitespace.36*/37function getMarkdownFromSlide( section ) {3839// look for a <script> or <textarea data-template> wrapper40const template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' );4142// strip leading whitespace so it isn't evaluated as code43let text = ( template || section ).textContent;4445// restore script end tags46text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );4748const leadingWs = text.match( /^\n?(\s*)/ )[1].length,49leadingTabs = text.match( /^\n?(\t*)/ )[1].length;5051if( leadingTabs > 0 ) {52text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}(.*)','g'), function(m, p1) { return '\n' + p1 ; } );53}54else if( leadingWs > 1 ) {55text = text.replace( new RegExp('\\n? {' + leadingWs + '}(.*)', 'g'), function(m, p1) { return '\n' + p1 ; } );56}5758return text;5960}6162/**63* Given a markdown slide section element, this will64* return all arguments that aren't related to markdown65* parsing. Used to forward any other user-defined arguments66* to the output markdown slide.67*/68function getForwardedAttributes( section ) {6970const attributes = section.attributes;71const result = [];7273for( let i = 0, len = attributes.length; i < len; i++ ) {74const name = attributes[i].name,75value = attributes[i].value;7677// disregard attributes that are used for markdown loading/parsing78if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;7980if( value ) {81result.push( name + '="' + value + '"' );82}83else {84result.push( name );85}86}8788return result.join( ' ' );8990}9192/**93* Inspects the given options and fills out default94* values for what's not defined.95*/96function getSlidifyOptions( options ) {97const markdownConfig = deck?.getConfig?.().markdown;9899options = options || {};100options.separator = options.separator || markdownConfig?.separator || DEFAULT_SLIDE_SEPARATOR;101options.verticalSeparator = options.verticalSeparator || markdownConfig?.verticalSeparator || DEFAULT_VERTICAL_SEPARATOR;102options.notesSeparator = options.notesSeparator || markdownConfig?.notesSeparator || DEFAULT_NOTES_SEPARATOR;103options.attributes = options.attributes || '';104105return options;106107}108109/**110* Helper function for constructing a markdown slide.111*/112function createMarkdownSlide( content, options ) {113114options = getSlidifyOptions( options );115116const notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );117118if( notesMatch.length === 2 ) {119content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';120}121122// prevent script end tags in the content from interfering123// with parsing124content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );125126return '<script type="text/template">' + content + '</script>';127128}129130/**131* Parses a data string into multiple slides based132* on the passed in separator arguments.133*/134function slidify( markdown, options ) {135136options = getSlidifyOptions( options );137138const separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),139horizontalSeparatorRegex = new RegExp( options.separator );140141let matches,142lastIndex = 0,143isHorizontal,144wasHorizontal = true,145content,146sectionStack = [];147148// iterate until all blocks between separators are stacked up149while( matches = separatorRegex.exec( markdown ) ) {150const notes = null;151152// determine direction (horizontal by default)153isHorizontal = horizontalSeparatorRegex.test( matches[0] );154155if( !isHorizontal && wasHorizontal ) {156// create vertical stack157sectionStack.push( [] );158}159160// pluck slide content from markdown input161content = markdown.substring( lastIndex, matches.index );162163if( isHorizontal && wasHorizontal ) {164// add to horizontal stack165sectionStack.push( content );166}167else {168// add to vertical stack169sectionStack[sectionStack.length-1].push( content );170}171172lastIndex = separatorRegex.lastIndex;173wasHorizontal = isHorizontal;174}175176// add the remaining slide177( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );178179let markdownSections = '';180181// flatten the hierarchical stack, and insert <section data-markdown> tags182for( let i = 0, len = sectionStack.length; i < len; i++ ) {183// vertical184if( sectionStack[i] instanceof Array ) {185markdownSections += '<section '+ options.attributes +'>';186187sectionStack[i].forEach( function( child ) {188markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';189} );190191markdownSections += '</section>';192}193else {194markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';195}196}197198return markdownSections;199200}201202/**203* Parses any current data-markdown slides, splits204* multi-slide markdown into separate sections and205* handles loading of external markdown.206*/207function processSlides( scope ) {208209return new Promise( function( resolve ) {210211const externalPromises = [];212213[].slice.call( scope.querySelectorAll( 'section[data-markdown]:not([data-markdown-parsed])') ).forEach( function( section, i ) {214215if( section.getAttribute( 'data-markdown' ).length ) {216217externalPromises.push( loadExternalMarkdown( section ).then(218219// Finished loading external file220function( xhr, url ) {221section.outerHTML = slidify( xhr.responseText, {222separator: section.getAttribute( 'data-separator' ),223verticalSeparator: section.getAttribute( 'data-separator-vertical' ),224notesSeparator: section.getAttribute( 'data-separator-notes' ),225attributes: getForwardedAttributes( section )226});227},228229// Failed to load markdown230function( xhr, url ) {231section.outerHTML = '<section data-state="alert">' +232'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +233'Check your browser\'s JavaScript console for more details.' +234'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +235'</section>';236}237238) );239240}241else {242243section.outerHTML = slidify( getMarkdownFromSlide( section ), {244separator: section.getAttribute( 'data-separator' ),245verticalSeparator: section.getAttribute( 'data-separator-vertical' ),246notesSeparator: section.getAttribute( 'data-separator-notes' ),247attributes: getForwardedAttributes( section )248});249250}251252});253254Promise.all( externalPromises ).then( resolve );255256} );257258}259260function loadExternalMarkdown( section ) {261262return new Promise( function( resolve, reject ) {263264const xhr = new XMLHttpRequest(),265url = section.getAttribute( 'data-markdown' );266267const datacharset = section.getAttribute( 'data-charset' );268269// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes270if( datacharset !== null && datacharset !== '' ) {271xhr.overrideMimeType( 'text/html; charset=' + datacharset );272}273274xhr.onreadystatechange = function( section, xhr ) {275if( xhr.readyState === 4 ) {276// file protocol yields status code 0 (useful for local debug, mobile applications etc.)277if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {278279resolve( xhr, url );280281}282else {283284reject( xhr, url );285286}287}288}.bind( this, section, xhr );289290xhr.open( 'GET', url, true );291292try {293xhr.send();294}295catch ( e ) {296console.warn( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );297resolve( xhr, url );298}299300} );301302}303304/**305* Check if a node value has the attributes pattern.306* If yes, extract it and add that value as one or several attributes307* to the target element.308*309* You need Cache Killer on Chrome to see the effect on any FOM transformation310* directly on refresh (F5)311* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277312*/313function addAttributeInElement( node, elementTarget, separator ) {314315const markdownClassesInElementsRegex = new RegExp( separator, 'mg' );316const markdownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' );317let nodeValue = node.nodeValue;318let matches,319matchesClass;320if( matches = markdownClassesInElementsRegex.exec( nodeValue ) ) {321322const classes = matches[1];323nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( markdownClassesInElementsRegex.lastIndex );324node.nodeValue = nodeValue;325while( matchesClass = markdownClassRegex.exec( classes ) ) {326if( matchesClass[2] ) {327elementTarget.setAttribute( matchesClass[1], matchesClass[2] );328} else {329elementTarget.setAttribute( matchesClass[3], "" );330}331}332return true;333}334return false;335}336337/**338* Add attributes to the parent element of a text node,339* or the element of an attribute node.340*/341function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {342343if ( element !== null && element.childNodes !== undefined && element.childNodes.length > 0 ) {344let previousParentElement = element;345for( let i = 0; i < element.childNodes.length; i++ ) {346const childElement = element.childNodes[i];347if ( i > 0 ) {348let j = i - 1;349while ( j >= 0 ) {350const aPreviousChildElement = element.childNodes[j];351if ( typeof aPreviousChildElement.setAttribute === 'function' && aPreviousChildElement.tagName !== "BR" ) {352previousParentElement = aPreviousChildElement;353break;354}355j = j - 1;356}357}358let parentSection = section;359if( childElement.nodeName === "section" ) {360parentSection = childElement ;361previousParentElement = childElement ;362}363if ( typeof childElement.setAttribute === 'function' || childElement.nodeType === Node.COMMENT_NODE ) {364addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );365}366}367}368369if ( element.nodeType === Node.COMMENT_NODE ) {370if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) === false ) {371addAttributeInElement( element, section, separatorSectionAttributes );372}373}374}375376/**377* Converts any current data-markdown slides in the378* DOM to HTML.379*/380function convertSlides() {381382const sections = deck.getRevealElement().querySelectorAll( '[data-markdown]:not([data-markdown-parsed])');383384[].slice.call( sections ).forEach( function( section ) {385386section.setAttribute( 'data-markdown-parsed', true )387388const notes = section.querySelector( 'aside.notes' );389const markdown = getMarkdownFromSlide( section );390391section.innerHTML = marked( markdown );392addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||393section.parentNode.getAttribute( 'data-element-attributes' ) ||394DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,395section.getAttribute( 'data-attributes' ) ||396section.parentNode.getAttribute( 'data-attributes' ) ||397DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);398399// If there were notes, we need to re-add them after400// having overwritten the section's HTML401if( notes ) {402section.appendChild( notes );403}404405} );406407return Promise.resolve();408409}410411function escapeForHTML( input ) {412413return input.replace( /([&<>'"])/g, char => HTML_ESCAPE_MAP[char] );414415}416417return {418id: 'markdown',419420/**421* Starts processing and converting Markdown within the422* current reveal.js deck.423*/424init: function( reveal ) {425426deck = reveal;427428let { renderer, animateLists, ...markedOptions } = deck.getConfig().markdown || {};429430if( !renderer ) {431renderer = new marked.Renderer();432433renderer.code = ( code, language ) => {434435// Off by default436let lineNumberOffset = '';437let lineNumbers = '';438439// Users can opt in to show line numbers and highlight440// specific lines.441// ```javascript [] show line numbers442// ```javascript [1,4-8] highlights lines 1 and 4-8443// optional line number offset:444// ```javascript [25: 1,4-8] start line numbering at 25,445// highlights lines 1 (numbered as 25) and 4-8 (numbered as 28-32)446if( CODE_LINE_NUMBER_REGEX.test( language ) ) {447let lineNumberOffsetMatch = language.match( CODE_LINE_NUMBER_REGEX )[2];448if (lineNumberOffsetMatch){449lineNumberOffset = `data-ln-start-from="${lineNumberOffsetMatch.trim()}"`;450}451452lineNumbers = language.match( CODE_LINE_NUMBER_REGEX )[3].trim();453lineNumbers = `data-line-numbers="${lineNumbers}"`;454language = language.replace( CODE_LINE_NUMBER_REGEX, '' ).trim();455}456457// Escape before this gets injected into the DOM to458// avoid having the HTML parser alter our code before459// highlight.js is able to read it460code = escapeForHTML( code );461462// return `<pre><code ${lineNumbers} class="${language}">${code}</code></pre>`;463464return `<pre><code ${lineNumbers} ${lineNumberOffset} class="${language}">${code}</code></pre>`;465};466}467468if( animateLists === true ) {469renderer.listitem = text => `<li class="fragment">${text}</li>`;470}471472marked.setOptions( {473renderer,474...markedOptions475} );476477return processSlides( deck.getRevealElement() ).then( convertSlides );478479},480481// TODO: Do these belong in the API?482processSlides: processSlides,483convertSlides: convertSlides,484slidify: slidify,485marked: marked486}487488};489490export default Plugin;491492493