2019-03-08 19:14:17 +02:00
const Entities = require ( 'html-entities' ) . AllHtmlEntities ;
2019-07-29 15:43:53 +02:00
const htmlentities = new Entities ( ) . encode ;
2019-07-16 20:05:47 +02:00
const utils = require ( '../../utils' ) ;
2019-09-09 19:16:00 +02:00
const urlUtils = require ( 'lib/urlUtils.js' ) ;
2019-03-08 19:14:17 +02:00
function installRule ( markdownIt , mdOptions , ruleOptions ) {
2019-09-13 00:16:42 +02:00
markdownIt . renderer . rules . link _open = function ( tokens , idx ) {
2019-03-08 19:14:17 +02:00
const token = tokens [ idx ] ;
let href = utils . getAttr ( token . attrs , 'href' ) ;
2019-09-09 19:16:00 +02:00
const resourceHrefInfo = urlUtils . parseResourceUrl ( href ) ;
2019-09-10 10:25:58 +02:00
const isResourceUrl = ! ! resourceHrefInfo ;
2019-03-08 19:14:17 +02:00
const title = isResourceUrl ? utils . getAttr ( token . attrs , 'title' ) : href ;
2019-07-29 15:43:53 +02:00
let resourceIdAttr = '' ;
let icon = '' ;
2019-03-08 19:14:17 +02:00
let hrefAttr = '#' ;
if ( isResourceUrl ) {
2019-09-09 19:16:00 +02:00
const resourceId = resourceHrefInfo . itemId ;
2019-05-22 16:56:07 +02:00
const result = ruleOptions . resources [ resourceId ] ;
const resourceStatus = utils . resourceStatus ( result ) ;
2019-05-27 20:49:18 +02:00
if ( result && resourceStatus !== 'ready' ) {
2019-05-22 16:56:07 +02:00
const icon = utils . resourceStatusFile ( resourceStatus ) ;
2019-09-19 23:51:18 +02:00
return ` <a class="not-loaded-resource resource-status- ${ resourceStatus } " data-resource-id=" ${ resourceId } "> ` + ` <img src="data:image/svg+xml;utf8, ${ htmlentities ( icon ) } "/> ` ;
2019-05-22 16:56:07 +02:00
} else {
2019-09-19 23:51:18 +02:00
href = ` joplin:// ${ resourceId } ` ;
if ( resourceHrefInfo . hash ) href += ` # ${ resourceHrefInfo . hash } ` ;
resourceIdAttr = ` data-resource-id=' ${ resourceId } ' ` ;
2019-05-22 16:56:07 +02:00
icon = '<span class="resource-icon"></span>' ;
}
2019-03-08 19:14:17 +02:00
} else {
// If the link is a plain URL (as opposed to a resource link), set the href to the actual
2019-07-29 15:43:53 +02:00
// link. This allows the link to be exported too when exporting to PDF.
2019-03-08 19:14:17 +02:00
hrefAttr = href ;
}
2019-09-19 23:51:18 +02:00
let js = ` ${ ruleOptions . postMessageSyntax } ( ${ JSON . stringify ( href ) } ); return false; ` ;
2019-03-08 19:14:17 +02:00
if ( hrefAttr . indexOf ( '#' ) === 0 && href . indexOf ( '#' ) === 0 ) js = '' ; // If it's an internal anchor, don't add any JS since the webview is going to handle navigating to the right place
2019-09-19 23:51:18 +02:00
return ` <a data-from-md ${ resourceIdAttr } title=' ${ htmlentities ( title ) } ' href=' ${ hrefAttr } ' onclick=' ${ js } '> ${ icon } ` ;
2019-03-08 19:14:17 +02:00
} ;
}
module . exports = function ( context , ruleOptions ) {
return function ( md , mdOptions ) {
installRule ( md , mdOptions , ruleOptions ) ;
} ;
2019-07-29 15:43:53 +02:00
} ;