Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add when a page was last updated into the Docs site #4341

Merged
merged 35 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
7a08b0a
Update husky to 8.0.0
timngyn-amzn May 16, 2022
7e69d11
Init husky
timngyn-amzn May 16, 2022
05a1ede
Update cspell to 5.20.0
timngyn-amzn May 16, 2022
31bfcb8
Add frontmatter and update cspell to not error when no files found
timngyn-amzn May 25, 2022
40a9041
Read frontmatter from mdx files to get 'lastUpdated' property
timngyn-amzn May 25, 2022
1d3ed3a
Display last updated on page
timngyn-amzn May 26, 2022
dfad42d
Remove unused import
timngyn-amzn May 26, 2022
c9ada87
Add packages to help set up frontmatter in mdx files
timngyn-amzn May 26, 2022
ab31b8a
Update custom remark plugin to remove frontmatter
timngyn-amzn May 26, 2022
4d1133c
Add a skip section into switch statement
timngyn-amzn May 26, 2022
4905b22
Find first element after frontmatter quicker
timngyn-amzn May 26, 2022
018cedd
Make LastUpdated Provider root element in page.tsx
timngyn-amzn May 27, 2022
55f973d
Add blockquote check when parsing tree during frontmatter plugin
timngyn-amzn May 27, 2022
566055f
Add last updated dates to mdx files during amplify build
timngyn-amzn May 27, 2022
eec95e9
Move addLastUpdated script to preBuild section
timngyn-amzn May 27, 2022
26bf929
Update yarn.lock
timngyn Dec 13, 2022
adfb263
Update yarn.lock
timngyn Dec 13, 2022
5b538e6
Move last updated text into left Menu component
timngyn Dec 13, 2022
3096f66
Add 'sh' to supported language for code blocks
timngyn Dec 13, 2022
9c22b99
Change text to page updated
timngyn Dec 15, 2022
cf586f6
Merge branch 'main' into page-last-updated-in-build-only
timngyn Feb 3, 2023
58815be
Add useReducer and useContext to manage state of a page's last update…
timngyn Feb 8, 2023
b9abdf7
remove comments
timngyn Feb 8, 2023
fa49683
Pass down the parent Page last updated date into the provider component
timngyn Feb 8, 2023
82f1de4
Account for fragments without filterkeys
timngyn Feb 8, 2023
40f6453
remove console log
timngyn Feb 8, 2023
f3af57e
update fragments component for tests
timngyn Feb 8, 2023
1323220
Add comment and table cases for frontmatter plugin
timngyn Feb 8, 2023
1577d96
use forwardRef and useImperativeHandle to allow use of ref on functio…
timngyn Feb 8, 2023
dde8856
Merge branch 'main' into page-last-updated-in-build-only
timngyn Feb 8, 2023
3e411a5
Remove relative file path from frontmatter
timngyn Feb 8, 2023
ae909ee
Set package version for new packages
timngyn Feb 8, 2023
b106b7e
Update the types
timngyn Feb 8, 2023
2f867ef
remove outdated code
timngyn Feb 9, 2023
0dedd80
Add id to html element for page last updated text
timngyn Feb 9, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Read frontmatter from mdx files to get 'lastUpdated' property
  • Loading branch information
timngyn-amzn authored and timngyn committed Dec 14, 2022
commit 40a904104eec7c46d9a3a2ce93ecd1c2bb7e7a7e
5 changes: 5 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@ module.exports = async (phase, { defaultConfig }) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const importPlugin = await require('./src/plugins/import.tsx');

const locateFragmentsPlugin = await require('./src/plugins/locate-fragments.tsx');

const frontmatterPlugin = await require('./src/plugins/frontmatter.tsx');

const withMDX = require('@next/mdx')({
extension: /\.mdx$/,
options: {
remarkPlugins: [
frontmatterPlugin,
importPlugin,
headingLinkPlugin,
pagePlugin,
Expand Down
30 changes: 23 additions & 7 deletions src/components/FilterChildren/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
import {useRouter} from "next/router";
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { useLastUpdatedDatesContext } from '../LastUpdatedProvider';

export default function FilterChildren({children}) {
export default function FilterChildren({ children, frontmatter }) {
const router = useRouter();

const lastUpdatedDatesContext = useLastUpdatedDatesContext();

let filterKey = "";
if ("platform" in router.query) {
useEffect(() => {
lastUpdatedDatesContext.updateLastUpdatedDate(frontmatter.lastUpdated);
}, []);

let filterKey = '';
if ('platform' in router.query) {
filterKey = router.query.platform as string;
} else if ("integration" in router.query) {
} else if ('integration' in router.query) {
filterKey = router.query.integration as string;
} else if ("framework" in router.query) {
} else if ('framework' in router.query) {
filterKey = router.query.framework as string;
}

const filteredChildren = children.filter(
(el) => el.key === filterKey || el.key === "all",
(el) => el.key === filterKey || el.key === 'all'
);

if (filteredChildren.length > 0) {
return (
<div>{filteredChildren}</div>
);
}

return filteredChildren;
}
4 changes: 3 additions & 1 deletion src/components/Fragments/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import FilterChildren from "../FilterChildren";

export default function Fragments({fragments}) {
const children = [];
let frontmatter;
for (const key in fragments) {
const fragment = fragments[key]([]);
frontmatter = fragment.props.frontmatter;
children.push(<div key={key}>{fragment}</div>);
}

return <FilterChildren>{children}</FilterChildren>;
return <FilterChildren frontmatter={frontmatter}>{children}</FilterChildren>;
}
27 changes: 27 additions & 0 deletions src/components/LastUpdatedProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createContext, useContext, useState } from 'react';

const LastUpdatedDatesContext = createContext({
updateLastUpdatedDate: (date) => {}
});

export default function LastUpdatedDatesProvider({ updateLastUpdatedDate, children }) {
const value = {updateLastUpdatedDate}

return (
<LastUpdatedDatesContext.Provider value={value}>
{children}
</LastUpdatedDatesContext.Provider>
);
}

export function useLastUpdatedDatesContext() {
const context = useContext(LastUpdatedDatesContext);
if (!context) {
console.error(
'useLastUpdatedDatesContext must be used within a LastUpdatedDatesProvider'
);
return;
}

return context;
}
80 changes: 68 additions & 12 deletions src/components/Page/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import Layout from '../Layout/index';
import Menu from '../Menu/index';
import TableOfContents from '../TableOfContents/index';
import NextPrevious from '../NextPrevious/index';
import { ContentStyle, ChapterTitleStyle } from './styles';
import { ContentStyle, ChapterTitleStyle, LastUpdatedStyle } from './styles';
import {
getChapterDirectory,
isProductRoot
} from '../../utils/getLocalDirectory';
import SidebarLayoutToggle from '../SidebarLayoutToggle';
import { useRef, useState } from 'react';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { MQTablet } from '../media';
import {
filterMetadataByOption,
Expand All @@ -22,27 +22,35 @@ import ChooseFilterPage from '../../pages/ChooseFilterPage';
import { parseLocalStorage } from '../../utils/parseLocalStorage';
import { withFilterOverrides } from '../../utils/withFilterOverrides';
import { FeedbackToggle } from '../Feedback';
import LastUpdatedDatesProvider from '../LastUpdatedProvider';

export default function Page({
children,
meta
meta,
frontmatter
}: {
children: any;
meta?: any;
frontmatter?: any;
}) {
const router = useRouter();
if (!router.isReady) {
const [menuIsOpen, setMenuIsOpen] = useState(false);
// const [lastUpdatedDate, setLastUpdatedDate] = useState('');
useRef(null);
return <></>;
}

// const [lastUpdatedDate, setLastUpdatedDate] = useState('');

let url = router.asPath;
// remove trailing slash. this is important on pages like /cli/index.mdx
// or /console/index.mdx where router.asPath has a trailing slash and
// router.pathname doesn't.
if (url.endsWith('/')) {
url = url.slice(0, -1);
}

const directoryPath = router.pathname;
let filterKey = '',
filterKind = '';
Expand All @@ -67,7 +75,7 @@ export default function Page({
const headers = traverseHeadings(children, filterKey);
let filters = gatherAllFilters(children, filterKind);
// special cases
if (url.startsWith("/sdk")) {
if (url.startsWith('/sdk')) {
filters = filters.filter(
(filter) => filter !== 'flutter' && filter !== 'js'
);
Expand Down Expand Up @@ -141,6 +149,18 @@ export function metaContent({
directoryPath,
menuIsOpen,
setMenuIsOpen
}: {
title: any;
chapterTitle: any;
headers: any;
children: any;
filters: any;
filterKey: any;
filterKind: any;
url: any;
directoryPath: any;
menuIsOpen: any;
setMenuIsOpen: any;
}) {
const menuRef = useRef(null);
// Slice off the "@media " string at the start for use in JS instead of CSS
Expand All @@ -150,7 +170,36 @@ export function metaContent({
typeof window === 'undefined'
? false
: window.matchMedia(MQTabletJS).matches;


const [lastUpdatedDate, setLastUpdatedDate] = useState('');

function toReadableDate(date) {
const dateOptions: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'long',
day: 'numeric'
};

return new Date(date).toLocaleDateString('en-US', dateOptions);
}

function displayLastUpdatedString(date) {
if (date) {
return `Last Updated: ${toReadableDate(lastUpdatedDate)}`;
}

return '';
}

function updateLastUpdatedDate(date) {
const mostRecentDate =
new Date(date).getTime() >= new Date(lastUpdatedDate).getTime()
? date
: lastUpdatedDate;
setLastUpdatedDate(mostRecentDate);
console.log('most recent date', mostRecentDate);
}

return (
<>
<Menu
Expand All @@ -164,12 +213,19 @@ export function metaContent({
></Menu>
<ContentStyle menuIsOpen={menuIsOpen}>
<div>
<ChapterTitleStyle>{chapterTitle}</ChapterTitleStyle>
<h1>{title}</h1>
<CodeBlockProvider>
{children}
<NextPrevious url={url} filterKey={filterKey} />
</CodeBlockProvider>
<LastUpdatedDatesProvider
updateLastUpdatedDate={updateLastUpdatedDate}
>
<div>{displayLastUpdatedString(lastUpdatedDate)}</div>
<ChapterTitleStyle>{chapterTitle}</ChapterTitleStyle>
<div>
<h1>{title}</h1>
</div>
<CodeBlockProvider>
{children}
<NextPrevious url={url} filterKey={filterKey} />
</CodeBlockProvider>
</LastUpdatedDatesProvider>
</div>
</ContentStyle>
<TableOfContents title={title}>{headers}</TableOfContents>
Expand All @@ -187,7 +243,7 @@ export function metaContent({
/>
</SidebarLayoutToggle>
)}
<FeedbackToggle/>
<FeedbackToggle />
</>
);
}
38 changes: 38 additions & 0 deletions src/plugins/frontmatter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
module.exports = (async () => {
const matter = require('gray-matter');
const { visit } = await import('unist-util-visit');

const frontmatterPlugin = () => (tree, file) => {
// Goes through the markdown tree and builds the frontmatter
console.log("\ninside frontmatter plugin for file: ", file.path);
visit(tree, 'thematicBreak', (node, index) => {
// Only visit the 'thematicBreak' at index 0 because that's where the frontmatter will be
if (index === 0) {
const { data: frontmatter, content } = matter(file.contents);

tree.children.push({
type: 'export',
value: `export const frontmatter = ${JSON.stringify(
frontmatter,
null,
2
)}`
});

if (tree.children[0].type === 'thematicBreak') {
// Find the index of the closing thematicBreak to "remove" the frontmatter from the mdx tree
const closingThematicBreakIndex = tree.children.findIndex(
(element, currIndex) => currIndex > 0 && element.type === 'thematicBreak'
);

if (closingThematicBreakIndex !== -1) {
// Remove the frontmatter
tree.children.splice(0, closingThematicBreakIndex + 1);
}
}
}
});
};

return frontmatterPlugin;
})();
2 changes: 1 addition & 1 deletion src/plugins/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = (async () => {
type: 'export',
default: true,
value:
'export default ({ children }) => <Page meta={meta}>{children}</Page>'
'export default ({ children }) => <Page frontmatter={frontmatter} meta={meta}>{children}</Page>'
});
}
});
Expand Down
Loading