@codecademy/codebytes 0.2.1-alpha.5fb230.0 → 0.2.1-alpha.62069b.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,7 +3,7 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
- ### [0.2.1-alpha.5fb230.0](https://github.com/Codecademy/client-modules/compare/@codecademy/codebytes@0.2.0...@codecademy/codebytes@0.2.1-alpha.5fb230.0) (2022-01-11)
6
+ ### [0.2.1-alpha.62069b.0](https://github.com/Codecademy/client-modules/compare/@codecademy/codebytes@0.3.0...@codecademy/codebytes@0.2.1-alpha.62069b.0) (2022-01-14)
7
7
 
8
8
  **Note:** Version bump only for package @codecademy/codebytes
9
9
 
@@ -11,6 +11,15 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
11
11
 
12
12
 
13
13
 
14
+ ## [0.3.0](https://github.com/Codecademy/client-modules/compare/@codecademy/codebytes@0.2.0...@codecademy/codebytes@0.3.0) (2022-01-12)
15
+
16
+
17
+ ### Features
18
+
19
+ * **Codebytes:** add simple monaco editor disc 353 ([#16](https://github.com/Codecademy/client-modules/issues/16)) ([eec98ba](https://github.com/Codecademy/client-modules/commit/eec98ba9aad45f07fb5f3417e3da1e1935985deb))
20
+
21
+
22
+
14
23
  ## [0.2.0](https://github.com/Codecademy/client-modules/compare/@codecademy/codebytes@0.1.0...@codecademy/codebytes@0.2.0) (2022-01-04)
15
24
 
16
25
 
package/jest.config.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('../../jest.config.base')('codebytes');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codecademy/codebytes",
3
3
  "description": "Codebytes Code Editor",
4
- "version": "0.2.1-alpha.5fb230.0",
4
+ "version": "0.2.1-alpha.62069b.0",
5
5
  "author": "Codecademy Engineering <dev@codecademy.com>",
6
6
  "sideEffects": [
7
7
  "**/*.css",
@@ -40,13 +40,16 @@
40
40
  },
41
41
  "license": "MIT",
42
42
  "devDependencies": {
43
+ "@codecademy/gamut-tests": "*",
43
44
  "@emotion/jest": "^11.3.0",
44
45
  "@testing-library/dom": "^7.31.2",
45
46
  "@testing-library/react": "^11.0.4",
46
- "@types/loadable__component": "^5.13.2"
47
+ "@testing-library/react-hooks": "3.2.1",
48
+ "@testing-library/user-event": "13.1.1",
49
+ "monaco-editor-webpack-plugin": "1.9.1"
47
50
  },
48
51
  "publishConfig": {
49
52
  "access": "public"
50
53
  },
51
- "gitHead": "1d7c7131bb2c8e8147bf9927c71bb07816fa7c29"
54
+ "gitHead": "644608025776c10ef5db464c2cbc8e2c00da48f2"
52
55
  }
@@ -25,11 +25,14 @@ export const SimpleMonacoEditor: React.FC<SimpleMonacoEditorProps> = ({
25
25
  onChange,
26
26
  }) => {
27
27
  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
28
- const editorOnMount = useCallback((editor: ThemedEditor, monaco: Monaco) => {
29
- editorRef.current = editor;
30
- monaco.editor.defineTheme('dark', dark);
31
- monaco.editor.setTheme('dark');
32
- }, []);
28
+ const editorWillMount = useCallback(
29
+ (editor: ThemedEditor, monaco: Monaco) => {
30
+ editorRef.current = editor;
31
+ monaco.editor.defineTheme('dark', dark);
32
+ monaco.editor.setTheme('dark');
33
+ },
34
+ []
35
+ );
33
36
  return (
34
37
  <>
35
38
  <ResizeObserver
@@ -41,7 +44,7 @@ export const SimpleMonacoEditor: React.FC<SimpleMonacoEditorProps> = ({
41
44
  }}
42
45
  />
43
46
  <ReactMonacoEditor
44
- onMount={editorOnMount}
47
+ onMount={editorWillMount}
45
48
  onChange={onChange}
46
49
  options={{ minimap: { enabled: false } }}
47
50
  theme="vs-dark"
@@ -0,0 +1,71 @@
1
+ import { setupRtl } from '@codecademy/gamut-tests';
2
+ import userEvent from '@testing-library/user-event';
3
+ import React from 'react';
4
+
5
+ import { CodeByteEditor } from '..';
6
+ import { helloWorld, validLanguages } from '../consts';
7
+
8
+ const mockEditorTestId = 'mock-editor-test-id';
9
+
10
+ jest.mock('react-resize-observer');
11
+ // This is a super simplified mock capable of render value and trigger onChange.
12
+ jest.mock('../MonacoEditor', () => ({
13
+ SimpleMonacoEditor: ({
14
+ value,
15
+ onChange,
16
+ }: {
17
+ value: string;
18
+ onChange?: (value: string) => void;
19
+ }) => (
20
+ <>
21
+ {value}
22
+ <input
23
+ data-testid={mockEditorTestId}
24
+ type="text"
25
+ onChange={(e) => {
26
+ onChange?.(e.target.value);
27
+ }}
28
+ value={value}
29
+ />
30
+ </>
31
+ ),
32
+ }));
33
+
34
+ const renderWrapper = setupRtl(CodeByteEditor, {});
35
+
36
+ describe('CodeBytes', () => {
37
+ it('has a language-specific "hello world" program defined for each language', () => {
38
+ validLanguages.forEach((language) => {
39
+ expect(helloWorld[language]).toBeDefined();
40
+ });
41
+ });
42
+
43
+ it('initializes with a language-specific "hello world" program when there is no language prop', () => {
44
+ const { view } = renderWrapper();
45
+ const selectedLanguage = view.getByRole('combobox') as Element;
46
+ userEvent.selectOptions(selectedLanguage, ['javascript']);
47
+ view.getByText(helloWorld.javascript);
48
+ });
49
+
50
+ it('initializes with a language-specific "hello world" program when there is a language prop but no text prop', () => {
51
+ const { view } = renderWrapper({ language: 'javascript' });
52
+ view.getByText(helloWorld.javascript);
53
+ });
54
+
55
+ it('initializes with deserialized text when there is a text prop but no language prop', () => {
56
+ const testString = 'yes hello';
57
+ const { view } = renderWrapper({ text: testString });
58
+ const selectedLanguage = view.getByRole('combobox') as Element;
59
+ userEvent.selectOptions(selectedLanguage, ['javascript']);
60
+ view.getByText(testString);
61
+ });
62
+
63
+ it('initializes with deserialized text when there is both a language and text prop', () => {
64
+ const testString = 'yes hello';
65
+ const { view } = renderWrapper({
66
+ text: testString,
67
+ language: 'javascript',
68
+ });
69
+ view.getByText(testString);
70
+ });
71
+ });
@@ -0,0 +1,59 @@
1
+ import { setupRtl } from '@codecademy/gamut-tests';
2
+ import userEvent from '@testing-library/user-event';
3
+ import React from 'react';
4
+
5
+ import { Editor } from '../editor';
6
+
7
+ jest.mock('../MonacoEditor', () => ({
8
+ SimpleMonacoEditor: ({ value }: { value: string }) => <>{value}</>,
9
+ }));
10
+
11
+ jest.mock('react-resize-observer');
12
+
13
+ const renderWrapper = setupRtl(Editor, {
14
+ hideCopyButton: false,
15
+ language: 'javascript',
16
+ text: 'hello world',
17
+ onChange: jest.fn(),
18
+ snippetsBaseUrl: '',
19
+ });
20
+
21
+ Object.defineProperty(navigator, 'clipboard', {
22
+ value: {
23
+ writeText: jest.fn(),
24
+ },
25
+ });
26
+
27
+ describe('Editor', () => {
28
+ (global as any).fetch = jest.fn();
29
+ afterEach(() => {
30
+ (global as any).fetch.mockClear();
31
+ });
32
+
33
+ it('shows a prompt tooltip when the CodeByte has __not__ been copied via the button', () => {
34
+ const { view } = renderWrapper();
35
+ expect(view.queryByTestId('copy-confirmation-tooltip')).toBeFalsy();
36
+ view.getByTestId('copy-prompt-tooltip');
37
+ });
38
+
39
+ it('shows a confirmation tooltip when the CodeByte has been copied via the button', () => {
40
+ const { view } = renderWrapper();
41
+ const copyBtn = view.getByTestId('copy-codebyte-btn');
42
+ userEvent.click(copyBtn as HTMLButtonElement);
43
+ expect(view.queryByTestId('copy-prompt-tooltip')).toBeFalsy();
44
+ view.getByTestId('copy-confirmation-tooltip');
45
+ });
46
+
47
+ it('hides the copy codebyte button if hideCopyButton prop is true"', () => {
48
+ const { view } = renderWrapper({
49
+ hideCopyButton: true,
50
+ });
51
+ expect(view.queryByTestId('copy-codebyte-btn')).toBeNull();
52
+ });
53
+
54
+ it('shows the copy codebyte button if hideCopyButton prop is not set', () => {
55
+ const { view } = renderWrapper();
56
+
57
+ view.getByTestId('copy-codebyte-btn');
58
+ });
59
+ });
@@ -0,0 +1,14 @@
1
+ import { setupRtl } from '@codecademy/gamut-tests';
2
+
3
+ import { LanguageSelection } from '../languageSelection';
4
+
5
+ const renderWrapper = setupRtl(LanguageSelection, {
6
+ onChange: () => null,
7
+ });
8
+
9
+ describe('LanguageSelection', () => {
10
+ it('has placeholder text', () => {
11
+ const { view } = renderWrapper();
12
+ view.getByText('Select your language');
13
+ });
14
+ });
package/src/consts.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // key = language param to send to snippets service
2
2
  // val = label in language selection drop down
3
3
  export const languageOptions = {
4
- '': 'Select your language',
4
+ '': 'Select a language',
5
5
  cpp: 'C++',
6
6
  csharp: 'C#',
7
7
  golang: 'Go',
@@ -16,7 +16,7 @@ export type languageOption = keyof typeof languageOptions;
16
16
 
17
17
  export const validLanguages = Object.keys(languageOptions).filter(
18
18
  (option) => !!option
19
- ) as languageOption[];
19
+ ) as Exclude<languageOption, ''>[];
20
20
 
21
21
  const cpp = `#include <iostream>
22
22
  int main() {
@@ -52,7 +52,7 @@ const scheme = `(begin
52
52
  (display "Hello world!")
53
53
  (newline))`;
54
54
 
55
- export const helloWorld: { [key in languageOption]?: string } = {
55
+ export const helloWorld = {
56
56
  cpp,
57
57
  csharp,
58
58
  golang,
@@ -61,4 +61,4 @@ export const helloWorld: { [key in languageOption]?: string } = {
61
61
  python,
62
62
  ruby,
63
63
  scheme,
64
- };
64
+ } as const;
package/src/editor.tsx CHANGED
@@ -9,11 +9,11 @@ import { CopyIcon } from '@codecademy/gamut-icons';
9
9
  import styled from '@emotion/styled';
10
10
  import React, { useState } from 'react';
11
11
 
12
- import { CodebytesChangeHandlerMap } from '.';
13
12
  import { postSnippet } from './api';
14
13
  import type { languageOption } from './consts';
15
14
  import { Drawers } from './drawers';
16
15
  import { SimpleMonacoEditor } from './MonacoEditor';
16
+ import { CodebytesChangeHandlerMap } from './types';
17
17
 
18
18
  const Output = styled.pre<{ hasError: boolean }>`
19
19
  width: 100%;
@@ -39,10 +39,8 @@ type EditorProps = {
39
39
  hideCopyButton: boolean;
40
40
  language: languageOption;
41
41
  text: string;
42
-
43
- // eslint-disable-next-line react/no-unused-prop-types
44
42
  onChange: (text: string) => void;
45
- on?: Pick<CodebytesChangeHandlerMap, 'copy' | 'run'>;
43
+ on?: CodebytesChangeHandlerMap;
46
44
  snippetsBaseUrl?: string;
47
45
  };
48
46
 
@@ -50,7 +48,7 @@ export const Editor: React.FC<EditorProps> = ({
50
48
  language,
51
49
  text,
52
50
  hideCopyButton,
53
- on,
51
+ on = {},
54
52
  onChange,
55
53
  snippetsBaseUrl,
56
54
  }) => {
@@ -59,11 +57,9 @@ export const Editor: React.FC<EditorProps> = ({
59
57
  const [isCodeByteCopied, setIsCodeByteCopied] = useState(false);
60
58
  const onCopyClick = () => {
61
59
  if (!isCodeByteCopied) {
62
- navigator.clipboard
63
- .writeText(text)
64
- // eslint-disable-next-line no-console
65
- .catch(() => console.error('Failed to copy'));
66
- on?.copy?.(text, language);
60
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
61
+ navigator.clipboard.writeText(text);
62
+ on.copy?.(text, language);
67
63
  setIsCodeByteCopied(true);
68
64
  }
69
65
  };
@@ -83,7 +79,7 @@ export const Editor: React.FC<EditorProps> = ({
83
79
  };
84
80
  setStatus('waiting');
85
81
  setOutput('');
86
- on?.run?.();
82
+ on.run?.();
87
83
 
88
84
  try {
89
85
  const response = await postSnippet(data, snippetsBaseUrl);
@@ -134,15 +130,20 @@ export const Editor: React.FC<EditorProps> = ({
134
130
  variant="secondary"
135
131
  onClick={onCopyClick}
136
132
  onBlur={() => setIsCodeByteCopied(false)}
133
+ data-testid="copy-codebyte-btn"
137
134
  >
138
135
  <CopyIconStyled aria-hidden="true" /> Copy Codebyte
139
136
  </TextButton>
140
137
  }
141
138
  >
142
139
  {isCodeByteCopied ? (
143
- <span role="alert">Copied!</span>
140
+ <span data-testid="copy-confirmation-tooltip" role="alert">
141
+ Copied!
142
+ </span>
144
143
  ) : (
145
- <span>Copy to your clipboard</span>
144
+ <span data-testid="copy-prompt-tooltip">
145
+ Copy to your clipboard
146
+ </span>
146
147
  )}
147
148
  </ToolTip>
148
149
  ) : null}
package/src/index.tsx CHANGED
@@ -3,29 +3,12 @@ import { FaviconIcon } from '@codecademy/gamut-icons';
3
3
  import { Background, states, system } from '@codecademy/gamut-styles';
4
4
  import { StyleProps } from '@codecademy/variance';
5
5
  import styled from '@emotion/styled';
6
- import React, { useState } from 'react';
6
+ import React, { useEffect, useState } from 'react';
7
7
 
8
8
  import { helloWorld, languageOption } from './consts';
9
9
  import { Editor } from './editor';
10
10
  import { LanguageSelection } from './languageSelection';
11
-
12
- type CodebytesChangeHandler = (text: string, language: languageOption) => void;
13
- export type CodebytesChangeHandlerMap = {
14
- logoClick?: () => void;
15
- edit?: CodebytesChangeHandler;
16
- languageChange?: CodebytesChangeHandler;
17
- copy?: CodebytesChangeHandler;
18
- run?: () => void;
19
- };
20
-
21
- export interface CodeByteEditorProps {
22
- text: string;
23
- language: languageOption;
24
- hideCopyButton: boolean;
25
- isIFrame?: boolean;
26
- snippetsBaseUrl?: string /* TODO in DISC-353: Determine best way to host and include snippets endpoint for both staging and production in both the monolith and next.js repo. */;
27
- on?: CodebytesChangeHandlerMap;
28
- }
11
+ import { CodeByteEditorProps } from './types';
29
12
 
30
13
  const editorStates = states({
31
14
  isIFrame: { height: '100vh' },
@@ -52,13 +35,22 @@ const EditorContainer = styled(Background)<EditorStyleProps>(
52
35
  export const CodeByteEditor: React.FC<CodeByteEditorProps> = ({
53
36
  text: initialText,
54
37
  language: initialLanguage,
55
- hideCopyButton,
38
+ hideCopyButton = false,
56
39
  isIFrame = false,
57
- on,
40
+ on = {},
58
41
  snippetsBaseUrl = process.env.CONTAINER_API_BASE,
59
42
  }) => {
60
- const [text, setText] = useState<string>(initialText);
61
- const [language, setLanguage] = useState<languageOption>(initialLanguage);
43
+ const [text, setText] = useState<string>(initialText ?? '');
44
+ const [language, setLanguage] = useState<languageOption>(
45
+ initialLanguage ?? ''
46
+ );
47
+
48
+ useEffect(() => {
49
+ if (language) {
50
+ setText(initialText ?? (helloWorld[language] || ''));
51
+ }
52
+ }, [language, initialText]);
53
+
62
54
  return (
63
55
  <EditorContainer bg="black" as="main" isIFrame={isIFrame}>
64
56
  <Box borderBottom={1} borderColor="gray-900" py={4} pl={8}>
@@ -69,7 +61,7 @@ export const CodeByteEditor: React.FC<CodeByteEditorProps> = ({
69
61
  target="_blank"
70
62
  rel="noreferrer"
71
63
  aria-label="visit codecademy.com"
72
- onClick={() => on?.logoClick?.()}
64
+ onClick={() => on.logoClick?.()}
73
65
  />
74
66
  </Box>
75
67
  {language ? (
@@ -79,7 +71,7 @@ export const CodeByteEditor: React.FC<CodeByteEditorProps> = ({
79
71
  hideCopyButton={hideCopyButton}
80
72
  onChange={(newText: string) => {
81
73
  setText(newText);
82
- on?.edit?.(newText, language);
74
+ on.edit?.(newText, language);
83
75
  }}
84
76
  on={on}
85
77
  snippetsBaseUrl={snippetsBaseUrl}
@@ -87,10 +79,11 @@ export const CodeByteEditor: React.FC<CodeByteEditorProps> = ({
87
79
  ) : (
88
80
  <LanguageSelection
89
81
  onChange={(newLanguage) => {
90
- const newText: string = text || helloWorld[newLanguage] || '';
82
+ const newText: string =
83
+ text || (newLanguage ? helloWorld[newLanguage] : '');
91
84
  setLanguage(newLanguage);
92
85
  setText(newText);
93
- on?.languageChange?.(newText, newLanguage);
86
+ on.languageChange?.(newText, newLanguage);
94
87
  }}
95
88
  />
96
89
  )}
@@ -36,7 +36,7 @@ export const LanguageSelection: React.FC<LanguageSelectionProps> = ({
36
36
  Which language do you want to code in?
37
37
  <StyledSelect
38
38
  id="language-select"
39
- aria-label="Select your language"
39
+ aria-label="Select a language"
40
40
  options={languageOptions}
41
41
  onChange={(e) => onChange(e.target.value as languageOption)}
42
42
  />
package/src/types.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { languageOption } from './consts';
2
+
3
+ type CodebytesChangeHandler = (text: string, language: languageOption) => void;
4
+
5
+ export type CodebytesChangeHandlerMap = {
6
+ logoClick?: () => void;
7
+ edit?: CodebytesChangeHandler;
8
+ languageChange?: CodebytesChangeHandler;
9
+ copy?: CodebytesChangeHandler;
10
+ run?: () => void;
11
+ };
12
+
13
+ export interface CodeByteEditorProps {
14
+ text?: string;
15
+ language?: languageOption;
16
+ hideCopyButton?: boolean;
17
+ isIFrame?: boolean;
18
+ snippetsBaseUrl?: string /* TODO in DISC-353: Determine best way to host and include snippets endpoint for both staging and production in both the monolith and next.js repo. */;
19
+ on?: CodebytesChangeHandlerMap;
20
+ }