@@ -8,10 +8,14 @@ import nonEnterpriseDefaultVersion from '../../non-enterprise-default-version.js
88import { allVersions } from '../../all-versions.js'
99import removeFPTFromPath from '../../remove-fpt-from-path.js'
1010import readJsonFile from '../../read-json-file.js'
11+ import findPage from '../../find-page.js'
1112
1213const supportedPlans = new Set ( Object . values ( allVersions ) . map ( ( v ) => v . plan ) )
1314const externalRedirects = readJsonFile ( './lib/redirects/external-sites.json' )
1415
16+ // Meaning it can be 'AUTOTITLE ' or ' AUTOTITLE' or 'AUTOTITLE'
17+ const AUTOTITLE = / ^ \s * A U T O T I T L E \s * $ /
18+
1519// Matches any <a> tags with an href that starts with `/`
1620const matcher = ( node ) =>
1721 node . type === 'element' &&
@@ -22,20 +26,34 @@ const matcher = (node) =>
2226
2327// Content authors write links like `/some/article/path`, but they need to be
2428// rewritten on the fly to match the current language and page version
25- export default function rewriteLocalLinks ( { languageCode, version } ) {
29+ export default function rewriteLocalLinks ( context ) {
30+ const { currentLanguage, currentVersion } = context
2631 // There's no languageCode or version passed, so nothing to do
27- if ( ! languageCode || ! version ) return
32+ if ( ! currentLanguage || ! currentVersion ) return
2833
2934 return ( tree ) => {
3035 visit ( tree , matcher , ( node ) => {
31- const newHref = getNewHref ( node , languageCode , version )
36+ const newHref = getNewHref ( node , currentLanguage , currentVersion )
3237 if ( newHref ) {
3338 node . properties . href = newHref
3439 }
40+ for ( const child of node . children ) {
41+ if ( child . value && AUTOTITLE . test ( child . value ) ) {
42+ child . value = getNewTitle ( node . properties . href , context )
43+ }
44+ }
3545 } )
3646 }
3747}
3848
49+ function getNewTitle ( href , context ) {
50+ const page = findPage ( href , context . pages , context . redirects )
51+ if ( ! page ) {
52+ throw new Error ( `Unable to find Page by href '${ href } '` )
53+ }
54+ return page . title
55+ }
56+
3957function getNewHref ( node , languageCode , version ) {
4058 const { href } = node . properties
4159 // Exceptions to link rewriting
0 commit comments