correctly relativize URL when target ends with a fragment identifier
authorDan Allen <dan@opendevise.com>
Thu, 8 Feb 2018 07:50:09 +0000 (00:50 -0700)
committerDan Allen <dan@opendevise.com>
Thu, 8 Feb 2018 23:23:01 +0000 (16:23 -0700)
src/helpers/relativize.js

index abab118..84615c9 100644 (file)
@@ -4,11 +4,20 @@ const { posix: path } = require('path')
 
 // TODO memoize
 module.exports = (from, to) => {
-  if (to === '#') {
-    return to
-  } else if (to.charAt(to.length - 1) === '/') {
-    return from === to ? './' : path.relative(path.dirname(from + '.'), to) + '/'
+  if (to.charAt() === '#') return to
+  let hash = ''
+  const hashIdx = to.indexOf('#')
+  if (~hashIdx) {
+    hash = to.substr(hashIdx)
+    to = to.substr(0, hashIdx)
+  }
+  if (from === to) {
+    return hash || (isDir(to) ? './' : path.basename(to))
   } else {
-    return path.relative(path.dirname(from + '.'), to)
+    return path.relative(path.dirname(from + '.'), to) + (isDir(to) ? '/' : '') + hash
   }
 }
+
+function isDir (str) {
+  return str.charAt(str.length - 1) === '/'
+}