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

Presenter Mode #22

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 9 additions & 1 deletion demo/src/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ layout: center,
className: test
+++
# test

// test note

---

# test 2

```jsx showLineNumbers highlightLines="1,2,5-6"
function Counter({initialCount}) {
function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<>
Expand All @@ -21,8 +26,11 @@ function Counter({initialCount}) {
);
}
```

---

# test 3

<Mermaid>
{`
flowchart TD
Expand Down
44 changes: 44 additions & 0 deletions packages/presentify/__tests__/PresentifyProvider.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ const keys = [
];

const string = '+++\nlayout: normal\n+++';
const notes = '// test note';

const Test = () => (
<PresentifyProvider>
<p>{string}</p>
<p>{notes}</p>
<div />
<div />
<hr />
Expand Down Expand Up @@ -110,6 +112,19 @@ describe('PresentifyProvider', () => {
'404 - Not Found',
);
});
it('Show correct nextSlide in presenter mode', async () => {
window.history.pushState(
undefined,
'',
`${window.location
.toString()
.replace(window.location.search, '')}?page=1`,
);
render(<Test />);
await userEvent.keyboard('{alt>}{p}');
screen.debug();
expect(screen.getAllByTestId('slide')[1].children).toHaveLength(2);
});
});

describe('Keyboard', () => {
Expand Down Expand Up @@ -142,4 +157,33 @@ describe('Keyboard', () => {
await userEvent.keyboard('{Enter}');
expect(screen.getByTestId('slide').children).toHaveLength(2);
});
it('option + p key was pressed', async () => {
render(<Test />);
await userEvent.keyboard('{alt>}{p}');
screen.debug();
expect(screen.getByText('Current Slide')).toBeInTheDocument();
expect(screen.getByText('NextSlide')).toBeInTheDocument();
expect(screen.getByText('Notes')).toBeInTheDocument();
});
it('option + p key was pressed twice', async () => {
render(<Test />);
await userEvent.keyboard('{alt>}{p}');
await userEvent.keyboard('{alt>}{p}');
expect(screen.getByTestId('slide').children).toHaveLength(2);
});
it('option + p key was pressed when disablePresenterMode option wa true', async () => {
render(
<PresentifyProvider options={{ disablePresenterMode: true }}>
<p>{string}</p>
<div />
<div />
<hr />
<div />
<div />
<div />
</PresentifyProvider>,
);
await userEvent.keyboard('{alt>}{p}');
expect(screen.getByTestId('slide').children).toHaveLength(2);
});
});
17 changes: 17 additions & 0 deletions packages/presentify/src/components/NormalLayout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';

import { NotFound } from './NotFound';
import { Slide } from './Slide';
import { Layout } from '../styles/NormalLayout.styled';

export const NormalLayout = ({
slides,
currentSlide,
}: {
slides: React.ReactNode[];
currentSlide: number;
}) => (
<Layout>
<Slide>{slides[currentSlide] ? slides[currentSlide] : <NotFound />}</Slide>
</Layout>
);
53 changes: 53 additions & 0 deletions packages/presentify/src/components/PresenterLayout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react';

import { Slide } from './Slide';
import { getSlideNotes } from '../lib/getSlideNotes';
import {
Layout,
NextSlideAndNotesWrapper,
NextSlideContainer,
NextSlideWrapper,
NotesContainer,
NotesWrapper,
SlideContainer,
SlideWrapper,
} from '../styles/PresenterLayout.styled';

export const PresenterLayout = ({
slides,
currentSlide,
}: {
slides: React.ReactNode[];
currentSlide: number;
}) => {
const { notes } = getSlideNotes(slides[currentSlide]);

return (
<Layout>
<SlideContainer>
<h1>Current Slide</h1>
<SlideWrapper>
<Slide>{slides[currentSlide]}</Slide>
</SlideWrapper>
</SlideContainer>
<NextSlideAndNotesWrapper>
<NextSlideContainer>
<h1>NextSlide</h1>
<NextSlideWrapper>
{slides[currentSlide + 1] ? (
<Slide>{slides[currentSlide + 1]}</Slide>
) : (
<Slide>{slides[0]}</Slide>
)}
</NextSlideWrapper>
</NextSlideContainer>
{notes && (
<NotesContainer>
<h1>Notes</h1>
<NotesWrapper>{notes}</NotesWrapper>
</NotesContainer>
)}
</NextSlideAndNotesWrapper>
</Layout>
);
};
31 changes: 22 additions & 9 deletions packages/presentify/src/components/PresentifyProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Global } from '@emotion/react';
import { isNil } from 'lodash';
import React, {
createContext,
ReactNode,
Expand All @@ -8,12 +9,12 @@ import React, {
} from 'react';

import { Keyboard } from './Keyboard';
import { NotFound } from './NotFound';
import { Slide } from './Slide';
import { NormalLayout } from './NormalLayout';
import { PresenterLayout } from './PresenterLayout';
import { useQueryParams } from '../hooks/useQueryParams';
import { useSharedState } from '../hooks/useSharedState';
import { splitSlides } from '../lib/splitSlides';
import { globalStyles } from '../styles/GlobalStyles.styled';
import { Layout } from '../styles/Layout.styled';
import { Options, PresentifyContextProps } from '../types/types';

const PresentifyContext = createContext<PresentifyContextProps | null>(null);
Expand All @@ -28,9 +29,10 @@ export const PresentifyProvider = ({
const { getParams, setParams } = useQueryParams();
const pageFromParams = parseInt(getParams('page') || '0', 10);

const [currentSlide, setCurrentSlide] = useState<number>(
const [currentSlide, setCurrentSlide] = useSharedState<number>(
isNaN(pageFromParams) ? 0 : pageFromParams,
);
const [presenterMode, setPresenterMode] = useState<boolean>(false);

useEffect(() => {
setParams('page', currentSlide.toString());
Expand All @@ -54,23 +56,34 @@ export const PresentifyProvider = ({
return prevState - 1;
});

const togglePresenterMode = () => {
if (options?.disablePresenterMode !== true) {
setPresenterMode(prevState => !prevState);
if (!presenterMode) {
window.open(window.location.href, '_blank');
}
}
};

const contextValue = {
slides,
options,
currentSlide,
onGoNextSlide,
onGoBackSlide,
presenterMode,
togglePresenterMode,
};

return (
<PresentifyContext.Provider value={contextValue}>
<Global styles={globalStyles} />
<Keyboard />
<Layout>
<Slide>
{slides[currentSlide] ? slides[currentSlide] : <NotFound />}
</Slide>
</Layout>
{presenterMode ? (
<PresenterLayout slides={slides} currentSlide={currentSlide} />
) : (
<NormalLayout slides={slides} currentSlide={currentSlide} />
)}
</PresentifyContext.Provider>
);
};
Expand Down
4 changes: 3 additions & 1 deletion packages/presentify/src/components/Slide.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React, { ReactNode } from 'react';

import { usePresentifyContext } from './PresentifyProvider';
import { getSlideNotes } from '../lib/getSlideNotes';
import { getSlideOptions } from '../lib/getSlideOptions';
import { SliderWrapper } from '../styles/Slide.styled';

export const Slide = ({ children }: { children: ReactNode }) => {
const { slideWithoutOptions, options: SlideOptions } =
getSlideOptions(children);
const { slideWithoutNotes } = getSlideNotes(slideWithoutOptions);
const { className, backgroundColor, backgroundImg, layout } =
SlideOptions || {};
const presentifyContext = usePresentifyContext();
Expand All @@ -24,7 +26,7 @@ export const Slide = ({ children }: { children: ReactNode }) => {
backgroundImg={backgroundImg || globalBackgroundImg}
layout={layout || globalLayout}
>
{slideWithoutOptions}
{slideWithoutNotes}
</SliderWrapper>
);
};
43 changes: 28 additions & 15 deletions packages/presentify/src/hooks/useKeyboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,38 @@ import { Keys } from '../types/types';

export const useKeyboard = () => {
const context = usePresentifyContext();
const { onGoNextSlide, onGoBackSlide, currentSlide } = context || {};
const { onGoNextSlide, onGoBackSlide, currentSlide, togglePresenterMode } =
context || {};

useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.code) {
case Keys.Right:
case Keys.Up: {
e.preventDefault();
onGoNextSlide && onGoNextSlide();
break;
if (e.altKey) {
switch (e.code) {
case Keys.P: {
e.preventDefault();
togglePresenterMode && togglePresenterMode();
break;
}
default:
break;
}
case Keys.Left:
case Keys.Down: {
e.preventDefault();
onGoBackSlide && onGoBackSlide();
break;
} else {
switch (e.code) {
case Keys.Right:
case Keys.Up: {
e.preventDefault();
onGoNextSlide && onGoNextSlide();
break;
}
case Keys.Left:
case Keys.Down: {
e.preventDefault();
onGoBackSlide && onGoBackSlide();
break;
}
default:
break;
}
default:
break;
}
};

Expand All @@ -32,5 +45,5 @@ export const useKeyboard = () => {
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [currentSlide, onGoBackSlide, onGoNextSlide]);
}, [currentSlide, onGoBackSlide, onGoNextSlide, togglePresenterMode]);
};
55 changes: 55 additions & 0 deletions packages/presentify/src/hooks/useSharedState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState } from 'react';

type UseSharedReturnType<T> = [
T,
(newState: T | ((prevState: T) => T)) => void,
];
export function useSharedState<T = any>(
initialState: T,
): UseSharedReturnType<T> {
const [state, setState] = useState<T>(initialState);
const broadcastChannelEnabled = window.BroadcastChannel !== undefined;
const broadcastChannel = broadcastChannelEnabled
? new BroadcastChannel('presentifyChannel')
: undefined;

const setSharedState = (newState: T | ((prevState: T) => T)): void => {
setState((prevState: T): T => {
const updatedState =
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
typeof newState === 'function' ? newState(prevState) : newState;

broadcastChannelEnabled &&
(broadcastChannel as BroadcastChannel).postMessage(
JSON.stringify(updatedState),
);

return updatedState;
});
};

const handleMessage = (event: MessageEvent) => {
const newState: T = JSON.parse(event.data);
setState(newState);
};

useEffect(() => {
broadcastChannelEnabled &&
(broadcastChannel as BroadcastChannel).addEventListener(
'message',
handleMessage,
);

return () => {
broadcastChannelEnabled &&
(broadcastChannel as BroadcastChannel).removeEventListener(
'message',
handleMessage,
);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return [state, setSharedState];
}
Loading