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

LG-4798: code custom snippets #2672

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
129 commits
Select commit Hold shift + click to select a range
ef34493
wip
shaneeza Jan 7, 2025
b71de4e
wip - updating panel styles
shaneeza Jan 7, 2025
029a90e
updated panel styles
shaneeza Jan 7, 2025
6ef16ba
trying to combine styles
shaneeza Jan 7, 2025
794fe08
move styles to styles file
shaneeza Jan 9, 2025
2e19572
updating panel types
shaneeza Jan 9, 2025
e21b374
added context
shaneeza Jan 9, 2025
07426d1
ts docs
shaneeza Jan 9, 2025
9994560
update copy button styles in panel
shaneeza Jan 9, 2025
3af02dc
organize code style file
shaneeza Jan 9, 2025
ffb7c2f
update types
shaneeza Jan 9, 2025
db94d82
remove unused type
shaneeza Jan 9, 2025
68f6b57
wip code tests
shaneeza Jan 10, 2025
02ede13
add language prop to context
shaneeza Jan 10, 2025
56c69e5
more tests updates
shaneeza Jan 10, 2025
79f9394
remove some tests
shaneeza Jan 10, 2025
ac0cadf
delete windowChrome and CustomSelectMenuButton
shaneeza Jan 10, 2025
893f021
fix onChangeError
shaneeza Jan 10, 2025
2fd12a6
remove comment
shaneeza Jan 10, 2025
a1d68a6
check if language is in option
shaneeza Jan 10, 2025
2a35411
add copyButtonAppearance prop
shaneeza Jan 13, 2025
f7164ca
add clipboard check
shaneeza Jan 13, 2025
05f3f67
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 13, 2025
9e108d7
remove copyable prop
shaneeza Jan 13, 2025
d1ecc7b
copy button styles
shaneeza Jan 14, 2025
b1f40b1
wip adding isLoadingProp
shaneeza Jan 15, 2025
bbf2a2d
add isLoading to context
shaneeza Jan 15, 2025
5b4276f
disabled copy icon styles
shaneeza Jan 15, 2025
da970a8
isLoading tests
shaneeza Jan 16, 2025
696bcd7
added back props i initially deleted
shaneeza Jan 16, 2025
597eba3
remove props from context
shaneeza Jan 16, 2025
bf064a6
update tsdocs
shaneeza Jan 17, 2025
2b77d46
rename func and update tsdocs
shaneeza Jan 17, 2025
8a6c5e3
add todo tests
shaneeza Jan 17, 2025
e41fac7
adding more tests
shaneeza Jan 21, 2025
1e4a020
remove unused tests
shaneeza Jan 21, 2025
84c7542
merge conflict
shaneeza Jan 21, 2025
d561827
merge conflict
shaneeza Jan 22, 2025
b461adc
fix languageswitcher example
shaneeza Jan 22, 2025
85037f5
fix errors
shaneeza Jan 22, 2025
90ab34c
fix errors
shaneeza Jan 22, 2025
f35d883
remove copyable false
shaneeza Jan 22, 2025
7b04bc6
add error test
shaneeza Jan 22, 2025
c2fc2b0
update tests and tsdocs
shaneeza Jan 22, 2025
fd23e6a
clean up
shaneeza Jan 22, 2025
f45e3a7
testids
shaneeza Jan 22, 2025
eadcc1b
merge conflicts
shaneeza Jan 22, 2025
485b0fc
merge conflict
shaneeza Jan 22, 2025
a5d6008
dont skip test
shaneeza Jan 22, 2025
36972e5
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 22, 2025
f7611b1
Merge branch 'LG-4760/code-copy-button' of github.com:mongodb/leafygr…
shaneeza Jan 22, 2025
a2a44f5
update padding
shaneeza Jan 22, 2025
571a0c7
updating generate stories
shaneeza Jan 22, 2025
339e8be
fix story error
shaneeza Jan 22, 2025
3d284ed
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 22, 2025
3de4d8e
merge conflict
shaneeza Jan 23, 2025
a02a756
fix build error
shaneeza Jan 23, 2025
e88a6f9
Merge branch 'main' of github.com:mongodb/leafygreen-ui into LG-4748-…
shaneeza Jan 23, 2025
64aefdc
clean up
shaneeza Jan 23, 2025
c45e257
Merge branch 'main' of github.com:mongodb/leafygreen-ui into LG-4748-…
shaneeza Jan 23, 2025
6c42aa6
readme updates
shaneeza Jan 23, 2025
7e9898e
forgot to save
shaneeza Jan 23, 2025
500ab13
fix language type
shaneeza Jan 23, 2025
5f5ecfb
lint
shaneeza Jan 23, 2025
8a8d39c
more tests
shaneeza Jan 23, 2025
394ae5e
remove fireevent
shaneeza Jan 23, 2025
cd99321
fix dep errors
shaneeza Jan 23, 2025
db02b0e
update lock file
shaneeza Jan 23, 2025
4255681
merge conflict
shaneeza Jan 23, 2025
6ca77cb
add generated stories
shaneeza Jan 24, 2025
e1030de
lint
shaneeza Jan 24, 2025
149ff69
title fix
shaneeza Jan 24, 2025
9a45d18
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 24, 2025
62f8b52
remove unused code and add new styles for button
shaneeza Jan 24, 2025
f43f0fb
updates
shaneeza Jan 26, 2025
a5123a1
lint
shaneeza Jan 26, 2025
10b22b5
forgot to save
shaneeza Jan 26, 2025
9f0da7e
merge conflict
shaneeza Jan 26, 2025
b4cd95f
loading story
shaneeza Jan 26, 2025
b10b6f6
lint
shaneeza Jan 26, 2025
4975572
some cleanup
shaneeza Jan 26, 2025
9a8bada
update test to use context
shaneeza Jan 26, 2025
8184e9a
fix spelling
shaneeza Jan 26, 2025
a3dd9c4
Merge branch 'LG-4760/code-copy-button' of github.com:mongodb/leafygr…
shaneeza Jan 26, 2025
3ac48a6
remove comments
shaneeza Jan 26, 2025
bd339cf
lint
shaneeza Jan 27, 2025
a292195
remove comment
shaneeza Jan 27, 2025
ec6b9d4
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 27, 2025
b4dca10
update test
shaneeza Jan 27, 2025
d1f5264
merge conflict
shaneeza Jan 27, 2025
2ac9395
feedback
shaneeza Jan 27, 2025
56afc5a
changeset
shaneeza Jan 27, 2025
facac67
typos
shaneeza Jan 27, 2025
a39be45
rephrase
shaneeza Jan 27, 2025
705a6c2
update test
shaneeza Jan 27, 2025
b9da5f9
Merge branch 'LG-4748-code-panel' of github.com:mongodb/leafygreen-ui…
shaneeza Jan 27, 2025
7fcbe7f
readme
shaneeza Jan 27, 2025
e051c3c
update docs
shaneeza Jan 27, 2025
55f6527
clean up
shaneeza Jan 27, 2025
4e322db
lib changeset
shaneeza Jan 27, 2025
e05cfda
test order
shaneeza Jan 27, 2025
cf28e29
add ticket
shaneeza Jan 28, 2025
dd51f84
update docs
shaneeza Jan 28, 2025
9d6b8c7
wip - testing
shaneeza Jan 28, 2025
1168eb3
fix story props
shaneeza Jan 28, 2025
33538df
sandy feedback
shaneeza Jan 28, 2025
1d1deb3
fix build error
shaneeza Jan 28, 2025
5f1c58c
merge conflict
shaneeza Jan 28, 2025
f7a4d88
Merge branch 'LG-4749-code-isLoading' of github.com:mongodb/leafygree…
shaneeza Jan 28, 2025
912712a
wip testing
shaneeza Jan 29, 2025
adb800a
wip, figuring out custom snippets
shaneeza Jan 30, 2025
ae72b50
testing
shaneeza Jan 30, 2025
65b7cf4
forgot to save
shaneeza Jan 30, 2025
076f998
more testing
shaneeza Jan 31, 2025
821e662
first pass at double brackets
shaneeza Jan 31, 2025
e49c680
merge conflict
shaneeza Jan 31, 2025
ae55142
remove coments
shaneeza Jan 31, 2025
51da4fd
build errors
shaneeza Jan 31, 2025
ea6ed42
comments
shaneeza Jan 31, 2025
bb217e9
wip more consoles
shaneeza Feb 3, 2025
ed32770
wip
shaneeza Feb 13, 2025
12fbc2f
parse string
shaneeza Feb 13, 2025
738edb2
clean up
shaneeza Feb 13, 2025
b969dce
remove comments
shaneeza Feb 13, 2025
26306f6
add back comment
shaneeza Feb 13, 2025
e534a3f
classname not working
shaneeza Feb 13, 2025
8bc8b9f
figured out className issue
shaneeza Feb 13, 2025
a8db6a7
run checks
shaneeza Feb 13, 2025
de00000
wip, adding div in another spot, remove renderToStaticMarkup
shaneeza Feb 14, 2025
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
49 changes: 48 additions & 1 deletion packages/code/src/Code.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const customActionButtons = [
const jsSnippet = `
import datetime from './';

hello there _hi_ and ok this is _great_ yup

const myVar = 42;

var myObj = {
Expand All @@ -54,10 +56,24 @@ export default class myClass {
function greeting(entity) {
return \`Hello, \${entity}! Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper.\`;
}

console.log(greeting('World'));
`;

const jsCustomSnippet = `
hi _hi_ _--hi_

hi {{hi}} {{--hi}}

hi ~~hi~~ ~~--hi~~

whats up yall

const hey hey

mongosh "mongodb+srv://cluster0.abcde.mongodb.net/test" ~~--api~~ 1 ~~--username~~ elmo
`;

// > 5 lines to trigger expandable code block
const shortJsSnippet = `
function greeting(entity) {
Expand Down Expand Up @@ -136,6 +152,10 @@ export const LiveExample: StoryType<typeof Code, FontSizeProps> = ({
highlightLines={highlightLines ? [6, [10, 15]] : undefined}
className={css`
width: 100%;

.lg-highlight-custom {
color: red;
}
`}
>
{jsSnippet}
Expand All @@ -148,6 +168,33 @@ LiveExample.parameters = {
},
};

export const CustomWord: StoryType<typeof Code, FontSizeProps> = ({
baseFontSize,
highlightLines,
...args
}: CodeProps & FontSizeProps) => (
<LeafygreenProvider baseFontSize={baseFontSize}>
<Code
{...(args as CodeProps)}
highlightLines={highlightLines ? [6, [10, 15]] : undefined}
className={css`
width: 100%;

.lg-highlight-custom {
color: red;
}
`}
>
{jsCustomSnippet}
</Code>
</LeafygreenProvider>
);
LiveExample.parameters = {
chromatic: {
disableSnapshot: true,
},
};

export const WithCustomActions: StoryType<typeof Code, FontSizeProps> = ({
baseFontSize,
highlightLines,
Expand Down
3 changes: 2 additions & 1 deletion packages/code/src/Code/Code.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ function Code({
const { theme, darkMode } = useDarkMode(darkModeProp);
const baseFontSize = useBaseFontSize();

console.log({ className });

useIsomorphicLayoutEffect(() => {
const scrollableElement = scrollableElementRef.current;

Expand Down Expand Up @@ -233,7 +235,6 @@ function Code({
collapsedCodeHeight,
isMultiline,
showExpandButton,
className,
})}
onScroll={onScroll}
ref={scrollableElementRef}
Expand Down
6 changes: 6 additions & 0 deletions packages/code/src/Syntax/Syntax.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ function Syntax({
/>
) : (
highlightedContent.react
// highlightedContent.string
);

const { theme, darkMode } = useDarkMode();
Expand Down Expand Up @@ -140,6 +141,11 @@ function Syntax({
`}
>
<tbody>{content}</tbody>
{/* {language === Language.None ? (
<tbody>{content}</tbody>
) : (
<tbody dangerouslySetInnerHTML={{ __html: content }} />
)} */}
</table>
</code>
</SyntaxContext.Provider>
Expand Down
153 changes: 149 additions & 4 deletions packages/code/src/renderingPlugin/renderingPlugin.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import flatMap from 'lodash/flatMap';
// import ReactDOMServer from 'react-dom/server';

import { css, cx } from '@leafygreen-ui/emotion';
import { palette } from '@leafygreen-ui/palette';
Expand All @@ -17,8 +18,9 @@ interface TokenProps {
children: React.ReactNode;
}

const prefix = 'lg-highlight-';

export function generateKindClassName(...kinds: Array<any>): string {
const prefix = 'lg-highlight-';
return kinds
.filter((str): str is string => isString(str) && str.length > 0)
.map(kind => {
Expand Down Expand Up @@ -169,6 +171,33 @@ export function LineTableRow({
? palette.gray.light3
: palette.yellow.dark2;

// const childrenToHtmlString = children => {
// return ReactDOMServer.renderToStaticMarkup(<>{children}</>);
// };

// console.log({ children, string: childrenToHtmlString(children) });

// const mergeStringsIntoString = children => {
// const childArray = React.Children.toArray(children); // Ensure it's an array

// return childArray.reduce((acc, child) => {
// const lastItem = acc[acc.length - 1];

// if (typeof child === 'string') {
// if (typeof lastItem === 'string') {
// acc[acc.length - 1] = lastItem + child; // Merge consecutive strings
// } else {
// acc.push(child);
// }
// } else {
// acc.push(child); // Keep React elements untouched
// }

// return acc;
// }, []);
// };

// console.log({ mergeStringsIntoString: mergeStringsIntoString(children) });
return (
<tr className={cx({ [getHighlightedRowStyle(darkMode)]: highlighted })}>
{lineNumber && (
Expand All @@ -189,6 +218,10 @@ export function LineTableRow({
)}

<td className={cellStyle}>{children}</td>
{/* <td
className={cellStyle}
dangerouslySetInnerHTML={{ __html: childrenToHtmlString(children) }}
/> */}
</tr>
);
}
Expand Down Expand Up @@ -228,10 +261,46 @@ export function flattenNestedTree(
parentKinds = parentKinds.filter(
(str): str is string => isString(str) && str.length > 0,
);

return function (
entity: string | TokenObject,
): string | FlatTokenObject | Array<string | FlatTokenObject> {
console.log({ entity });
if (isString(entity)) {
// if (parentKinds.length > 0) {
// return {
// kind: generateKindClassName(
// kind,
// ...parentKinds,
// ...childrenAsKeywords(entity),
// ),
// children: [entity],
// };
// } else {
// // Splits up the string by underscores
// // E.g. "This is before _hi_ this is after" => ["This is before ", "_hi_", " this is after"]
// const splitContentByUnderscore = entity.split(/(~~[\w-]+~~)/);

// console.log({ entity, splitContentByUnderscore });

// // If the array is greater than one then there are underscores in the string and we want to return each item in the array as an entity.
// if (splitContentByUnderscore.length > 1) {
// return splitContentByUnderscore.map(str => {
// // If the string starts and ends with an underscore, we want to remove them and return a new entity with a custom kind.
// if (str.startsWith('~~') && str.endsWith('~~')) {
// const removeUnderscores = str.slice(2, -2);
// return {
// kind: generateKindClassName(`${prefix}custom`),
// children: [removeUnderscores],
// };
// }

// return str;
// });
// }

// return entity;
// }
return parentKinds.length > 0
? {
kind: generateKindClassName(
Expand Down Expand Up @@ -299,6 +368,8 @@ export function treeToLines(
const lines: LineDefinition = [];
let currentLineIndex = 0;

// console.log({ children });

// Create a new line, if no lines exist yet
if (lines[currentLineIndex] == null) {
lines[currentLineIndex] = [];
Expand All @@ -309,7 +380,11 @@ export function treeToLines(
lines[currentLineIndex] = [];
};

console.log({ flatArray: flattenNestedTree(children) });

flattenNestedTree(children).forEach(child => {
// console.log({ child });

// If the current element includes a line break, we need to handle it differently
if (containsLineBreak(child)) {
if (isString(child)) {
Expand Down Expand Up @@ -386,14 +461,65 @@ export function TableContent({ lines }: TableContentProps) {
const currentLineNumber = index + (lineNumberStart ?? 1);
const highlightLine = lineShouldHighlight(currentLineNumber);

const mergeStringsIntoString = children => {
return children.reduce((acc, child) => {
const lastItem = acc[acc.length - 1];

if (typeof child === 'string') {
if (typeof lastItem === 'string') {
acc[acc.length - 1] = lastItem + child; // Merge consecutive strings
} else {
acc.push(child);
}
} else {
acc.push(child); // Keep React elements untouched
}

return acc;
}, []);
};

const mergedLines = mergeStringsIntoString(line);

const newLines = mergedLines.map((line, index) => {
if (typeof line === 'string') {
const splitContentByUnderscore = line.split(/(~~[\w-]+~~)/);

if (splitContentByUnderscore.length > 1) {
return splitContentByUnderscore.map(str => {
// If the string starts and ends with an underscore, we want to remove them and return a new entity with a custom kind.
if (str.startsWith('~~') && str.endsWith('~~')) {
const removeUnderscores = str.slice(2, -2);
return {
kind: generateKindClassName(`${prefix}custom`),
children: [removeUnderscores],
};
}

return str;
});
}
}

return line;
});

// TODO: if any merged line is a string, we need to split it by the special character and add a kind. This would avoid turning the component into a string.

console.log({
line,
mergedLines,
newLines,
});

let displayLineNumber;

if (showLineNumbers) {
displayLineNumber = currentLineNumber;
}

const processedLine = line?.length ? (
line.map(processToken)
const processedLine = newLines?.length ? (
newLines.map(processToken)
) : (
// We create placeholder content when a line break appears to preserve the line break's height
// It needs to be inline-block for the table row to not collapse.
Expand All @@ -404,6 +530,8 @@ export function TableContent({ lines }: TableContentProps) {
/>
);

// console.log({ processedLine });

return (
<LineTableRow
key={currentLineNumber}
Expand All @@ -422,8 +550,25 @@ export function TableContent({ lines }: TableContentProps) {
const plugin: LeafyGreenHLJSPlugin = {
'after:highlight': function (result: LeafyGreenHighlightResult) {
const { rootNode } = result._emitter;
// console.log(JSON.stringify(rootNode.children, null, 2));
// console.log(JSON.stringify(treeToLines(rootNode.children), null, 2));
result.react = <TableContent lines={treeToLines(rootNode.children)} />;

// const transformUnderscoreWords = htmlString => {
// // console.log({ htmlString });
// // return htmlString.replace(
// // /~~([-\w]+)~~/g,
// // `<span class=${prefix}custom>$1</span>`,
// // );
// return htmlString;
// };

// // Example usage:
// const string = ReactDOMServer.renderToStaticMarkup(result.react);

// // console.log({ string });
// const transformedString = transformUnderscoreWords(string);

// result.string = transformedString;
},
};

Expand Down
Loading