Debian Codegraph @

docs/playground/src/App.tsx

raw
1 import { AppBar, Toolbar, Typography, Box, Stack, SvgIcon, Button, TextField, Tabs, Tab, Tooltip, TooltipProps, tooltipClasses, styled, Snackbar, SnackbarCloseReason, IconButton } from '@mui/material';
2 import GitHub from '@mui/icons-material/GitHub';
3 import Share from '@mui/icons-material/Share';
4 import ContentCopy from '@mui/icons-material/ContentCopy';
5 import './App.css'
6 import YAMLIcon from '/public/yaml.svg?react';
7 import React, { useState, useRef, useEffect } from 'react';
8 import { editor } from 'monaco-editor'
9 import MonacoEditor, { loader } from '@monaco-editor/react';
10 import Grid from '@mui/material/Grid2';
11 import { FitAddon } from '@xterm/addon-fit';
12 import { Token, TokenGroup, GroupedToken, YAMLProcessResult, YAMLProcessResultType } from './YAML.ts';
13 import yamlWorker from "./worker?worker";
14 import '@xterm/xterm/css/xterm.css';
15 import { ArrowBackIosNew } from '@mui/icons-material'
16 import { Terminal } from '@xterm/xterm';
17 import json2mq from 'json2mq';
18 import useMediaQuery from '@mui/material/useMediaQuery';
19
20 const themeBlack = '#313131';
21 const themeWhite = 'white';
22
23 const isXS = (): boolean => {
24 const isNotXS = useMediaQuery(
25 json2mq({
26 minWidth: 400,
27 })
28 );
29 return !isNotXS;
30 };
31
32 const contentHeight = (): number => {
33 if (isXS()) {
34 return 200;
35 }
36 return 400;
37 }
38
39 const Header = (content: any) => {
40 const v = btoa(content.content as string);
41 const shareURL = `${window.location.origin}${window.location.pathname}?content=${v}`;
42 const [open, setOpen] = useState(false);
43 const [shareURLFieldVisibility, setShareURLFieldVisibility] = useState('hidden');
44
45 return (
46 <Box sx={{ flexGrow: 1 }}>
47 <AppBar position="fixed">
48 <Toolbar sx={{ backgroundColor: themeBlack }}>
49 <Logo />
50 <Typography sx={{ flexGrow: 1, textAlign: 'left' }}>
51 goccy/go-yaml Playground
52 </Typography>
53 <Stack sx={{
54 visibility: shareURLFieldVisibility,
55 backgroundColor: '#A0A0A0',
56 paddingLeft: 0.4,
57 paddingTop: 0.2,
58 }} direction={'row'} alignItems={'center'}>
59 <TextField value={shareURL} sx={{
60 backgroundColor: themeWhite,
61 }} variant="standard"></TextField>
62 <Button size='small' sx={{
63 backgroundColor: '#A0A0A0',
64 color: themeBlack,
65 }}
66 onClick={() => {
67 navigator.clipboard.writeText(shareURL).then(() => {
68 setOpen(true);
69 });
70 }}>
71 <ContentCopy />
72 </Button>
73 <Snackbar
74 open={open}
75 autoHideDuration={1500}
76 onClose={
77 (_: React.SyntheticEvent | Event,
78 reason?: SnackbarCloseReason) => {
79 if (reason === 'clickaway') {
80 return;
81 }
82 setOpen(false);
83 }}
84 message="Copied"
85 />
86 </Stack>
87 <ShareLink setVisibility={setShareURLFieldVisibility}></ShareLink>
88 <GitHubLink></GitHubLink>
89 </Toolbar>
90 </AppBar>
91 </Box>
92 )
93 };
94
95 const Logo = () => {
96 return <SvgIcon sx={{ xs: 1, md: 2, transform: 'scale(1.8)', marginRight: 3 }}><YAMLIcon /></SvgIcon>;
97 }
98
99 const ShareLink = (props: { setVisibility: React.Dispatch<React.SetStateAction<string>> }) => {
100 const { setVisibility } = props;
101
102 if (isXS()) {
103 return (
104 <IconButton onClick={() => {
105 setVisibility('visible');
106 }}>
107 <Share sx={{ color: themeWhite }}></Share>
108 </IconButton>
109 )
110 }
111 return (
112 <Button variant="contained" sx={{
113 backgroundColor: themeWhite,
114 color: themeBlack,
115 marginLeft: 4,
116 marginRight: 4,
117 textTransform: 'none',
118 fontWeight: 'bold',
119 paddingRight: 2,
120 paddingLeft: 2,
121 borderRadius: 0,
122 }}
123 startIcon={<Share sx={{ color: themeBlack }} />}
124 onClick={() => {
125 setVisibility('visible');
126 }}
127 >
128 Share
129 </Button>
130 )
131 }
132
133 const GitHubLink = () => {
134 if (isXS()) {
135 return (
136 <IconButton href="https://github.com/goccy/go-yaml">
137 <GitHub sx={{ color: themeWhite }}></GitHub>
138 </IconButton>
139 )
140 }
141 return (
142 <Button variant="contained" sx={{
143 color: themeBlack,
144 backgroundColor: 'white',
145 fontWeight: 'bold',
146 paddingRight: 2,
147 paddingLeft: 2,
148 textTransform: 'none',
149 }}
150 startIcon={<GitHub sx={{ color: themeBlack }}></GitHub>}
151 href="https://github.com/goccy/go-yaml"
152 >
153 Visit Our GitHub
154 </Button>
155 )
156 };
157
158 const TabPanel = (props: { children: any, value: number, index: number }) => {
159 const { children, value, index, ...other } = props;
160
161 return (
162 <div
163 role="tabpanel"
164 hidden={value !== index}
165 id={`simple-tabpanel-${index}`}
166 aria-labelledby={`simple-tab-${index}`}
167 {...other}
168 >
169 {value === index && (
170 <Box p={3}>
171 {children}
172 </Box>
173 )}
174 </div>
175 );
176 }
177
178 const TerminalComponent = (v: any) => {
179 const terminalRef = useRef<HTMLDivElement>(null)
180 const [terminalInstance, setTerminalInstance] = useState<Terminal | null>(null)
181 const fitAddon = new FitAddon();
182 const out = v.out;
183
184 useEffect(() => {
185 const instance = new Terminal({
186 cursorInactiveStyle: 'none',
187 cursorStyle: 'bar',
188 letterSpacing: 4,
189 fontFamily: 'monospace',
190 fontSize: 16,
191 fontWeightBold: 'bold',
192 convertEol: true,
193 theme: {
194 background: themeBlack,
195 cursor: themeBlack,
196 brightRed: '#da433a',
197 },
198 });
199
200 instance.loadAddon(fitAddon);
201
202 if (terminalRef.current) {
203 instance.open(terminalRef.current)
204 }
205
206 setTerminalInstance(instance)
207
208 return () => {
209 instance.dispose()
210 setTerminalInstance(null)
211 }
212 }, [
213 terminalRef,
214 ]);
215
216 useEffect(() => {
217 if (!terminalInstance) {
218 return;
219 }
220
221 terminalInstance.loadAddon(fitAddon);
222 fitAddon.fit();
223 terminalInstance.clear();
224 terminalInstance.writeln(out);
225 const handleResize = () => fitAddon.fit()
226
227 window.addEventListener('resize', handleResize)
228 return () => {
229 window.removeEventListener('resize', handleResize);
230 }
231 }, [terminalRef, terminalInstance, out]);
232
233 return (
234 <Box component="div" sx={{
235 height: contentHeight(),
236 width: '100%',
237 backgroundColor: themeBlack,
238 }}>
239 <Box
240 component="div"
241 ref={terminalRef}
242 sx={{
243 height: '100%',
244 width: '90%',
245 textAlign: 'left',
246 paddingLeft: 1,
247 paddingTop: 1,
248 }} />
249 </Box>
250 )
251 }
252
253 const CustomTooltip = styled(({ className, ...props }: TooltipProps) => (
254 <Tooltip {...props}
255 classes={{ popper: className }}
256 enterTouchDelay={0}
257 followCursor
258 arrow
259 />
260 ))({
261 [`& .${tooltipClasses.tooltip}`]: {
262 fontSize: 16,
263 whiteSpace: 'pre-wrap',
264 },
265 });
266
267 const EmptyTokenContainer = () => {
268 return (
269 <Box sx={{
270 textAlign: 'left',
271 backgroundColor: themeBlack,
272 fontSize: 16,
273 fontWeight: 'bold',
274 fontFamily: 'monospace',
275 paddingLeft: '1em',
276 height: contentHeight(),
277 }}></Box>
278 )
279 };
280
281 const TokenContainer = ({ children }: { children: any }) => {
282 return (
283 <Box sx={{
284 textAlign: 'left',
285 backgroundColor: themeBlack,
286 fontSize: 16,
287 fontWeight: 'bold',
288 fontFamily: 'monospace',
289 paddingLeft: '1em',
290 height: contentHeight(),
291 }}>{children}</Box>
292 )
293 };
294
295 const Lexer = (v: any) => {
296 if (!v.tokens) {
297 return <EmptyTokenContainer />
298 }
299 const tokens = v.tokens as Token[];
300 return (
301 <>
302 <TokenContainer>
303 {
304 tokens.map((tk, idx) => {
305 if (tokens.length > idx + 1) {
306 return tokenToComponent(tk, tokens[idx + 1]);
307 }
308 return tokenToComponent(tk, null)
309 })
310 }
311 </TokenContainer>
312 </>
313 )
314 };
315
316 const groupedTokenToComponent = (g: GroupedToken, groups: string[]) => {
317 if (g.token) {
318 return tokenToComponentWithoutTip(g.token);
319 }
320 return groupTokenToComponent(g.group, groups);
321 };
322
323 const tokenGroupToKey = (g: TokenGroup): string => {
324 return g.type + g.tokens.map(tk => groupedTokenToKey(tk)).join('-');
325 };
326
327 const groupedTokenToKey = (g: GroupedToken): string => {
328 if (g.group) {
329 return tokenGroupToKey(g.group)
330 }
331 return `${g.token.offset}`
332 }
333
334 const groupTokenToComponent = (g: TokenGroup, groups: string[]) => {
335 if (!g) {
336 return <></>
337 }
338 const groupColor = () => {
339 switch (g.type) {
340 case "directive":
341 return "dimgray";
342 case "directive_name":
343 return "orange"
344 case "document":
345 return "hotpink";
346 case "document_body":
347 return "olive"
348 case "anchor":
349 return "deepskyblue";
350 case "anchor_name":
351 return "brown"
352 case "alias":
353 return "limegreen";
354 case "literal":
355 return "gold"
356 case "folded":
357 return "gold"
358 case "scalar_tag":
359 return "blueviolet";
360 case "map_key":
361 return "coral";
362 case "map_key_value":
363 return "teal"
364 }
365 return 'white';
366 }
367 const newGroups = [...groups, g.type];
368 return (
369 <CustomTooltip
370 key={`${tokenGroupToKey(g)}-tooltip`}
371 sx={{ zIndex: 1500 + newGroups.length }}
372 title={newGroups.join(' > ')}
373 >
374 <Box
375 key={`${tokenGroupToKey(g)}`}
376 sx={{
377 backgroundColor: groupColor(),
378 borderRadius: 1,
379 paddingLeft: 1,
380 paddingRight: 1,
381 marginRight: '1em'
382 }} component="span">
383 {
384 g.tokens.map(tk => {
385 return groupedTokenToComponent(tk, newGroups);
386 })
387 }
388 </Box>
389 </CustomTooltip >
390 )
391 };
392
393 const tokenToComponent = (tk: Token, nextTk: Token | null) => {
394 if (!tk) {
395 return <></>
396 }
397 const orgs = tk.origin.split('\n').map((v, idx) => {
398 if (idx > 0) {
399 return ["\n", v];
400 }
401 return v;
402 });
403 const color = () => {
404 if (nextTk && nextTk.type === 'MappingValue') {
405 return '#008b8b';
406 }
407 switch (tk.type) {
408 case "String":
409 return '#ff7f50';
410 }
411 return 'black';
412 };
413 const prop = `type: ${tk.type}
414 origin: ${JSON.stringify(tk.origin)}
415 value: ${JSON.stringify(tk.value)}
416 line: ${tk.line}
417 column: ${tk.column}
418 `
419 return (
420 <CustomTooltip
421 key={`${tk.offset}-tooltip`}
422 title={prop}
423 >
424 <Box
425 key={`${tk.offset}`}
426 component="span"
427 sx={{
428 backgroundColor: 'white',
429 paddingRight: 1,
430 marginRight: 1,
431 borderRadius: 1,
432 color: color(),
433 }}>
434 {
435 orgs.map((v, index) => {
436 return (
437 <Box
438 key={`${tk.offset}-${index}`}
439 component="span"
440 sx={{
441 whiteSpace: "pre-wrap",
442 paddingLeft: 1,
443 }}
444 >{v}</Box>
445 )
446 })
447 }
448 </Box>
449 </CustomTooltip>
450 )
451 };
452
453 const tokenToComponentWithoutTip = (tk: Token) => {
454 if (!tk) {
455 return <></>
456 }
457 const orgs = tk.origin.split('\n').map((v, idx) => {
458 if (idx > 0) {
459 return ["\n", v];
460 }
461 return v;
462 });
463 return (
464 <Box
465 key={`${tk.offset}`}
466 component="span"
467 sx={{
468 color: 'black',
469 backgroundColor: 'white',
470 paddingRight: 1,
471 borderRadius: 1,
472 }}>
473 {
474 orgs.map((v, index) => {
475 return (
476 <Box
477 key={`${tk.offset}-${index}`}
478 component="span"
479 sx={{
480 whiteSpace: "pre-wrap",
481 paddingLeft: 1,
482 }}
483 >{v}</Box>
484 )
485 })
486 }
487 </Box>
488 )
489 };
490
491
492 const ParserGroup = (v: any) => {
493 if (!v.tokens) {
494 return <EmptyTokenContainer />
495 }
496 const tokens = v.tokens as GroupedToken[];
497 return (
498 <TokenContainer>
499 {
500 tokens.map(tk => { return groupedTokenToComponent(tk, []); })
501 }
502 </TokenContainer>
503 )
504 };
505
506 const AST = (v: any) => {
507 if (!v || !v.svg) {
508 return <Box sx={{
509 height: contentHeight(),
510 backgroundColor: themeBlack,
511 }}
512 />
513 }
514 const parser = new DOMParser()
515 const dom = parser.parseFromString(v.svg, 'text/xml');
516 const g = dom.getElementById('graph0');
517 if (!g) {
518 return <Box sx={{
519 height: contentHeight(),
520 backgroundColor: themeBlack,
521 }}
522 />
523 }
524 const viewBox = g.parentElement!.getAttribute('viewBox')!;
525 return (
526 <Box sx={{ height: contentHeight() }}>
527 <svg width={'100%'} height={'100%'} viewBox={viewBox} dangerouslySetInnerHTML={{ __html: g.outerHTML }}></svg>
528 </Box>
529 )
530 }
531
532 function App() {
533 const [content, setContent] = useState<string>('');
534 const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
535 const workerRef = useRef<Worker | null>(null);
536 const [tokens, setTokens] = useState<Token[]>([]);
537 const [groupedTokens, setGroupedTokens] = useState<GroupedToken[]>([]);
538 const [out, setOut] = useState<string>('');
539 const [svg, setSvg] = useState<string>('');
540 const [tabIndex, setTabIndex] = useState(0);
541
542 useEffect(() => {
543 workerRef.current = new yamlWorker();
544 workerRef.current.onmessage = (event) => {
545 const v = event.data as YAMLProcessResult;
546 switch (v.type) {
547 case YAMLProcessResultType.Decode:
548 setOut(v.result as string);
549 break;
550 case YAMLProcessResultType.Lexer:
551 if (typeof v.result === 'string') {
552 console.error(v.result);
553 } else {
554 setTokens(v.result as Token[]);
555 }
556 break;
557 case YAMLProcessResultType.ParserGroup:
558 if (typeof v.result === 'string') {
559 console.error(v.result);
560 } else {
561 setGroupedTokens(v.result as GroupedToken[]);
562 }
563 break;
564 case YAMLProcessResultType.Parser:
565 setSvg(v.result as string);
566 break;
567 default:
568 break;
569 }
570 }
571 return () => {
572 workerRef.current?.terminate();
573 };
574 }, []);
575 const onCodeChange = () => {
576 if (!editorRef || !editorRef.current) {
577 return
578 }
579 const code = editorRef.current.getValue()!;
580 setContent(code);
581 if (workerRef.current) {
582 workerRef.current.postMessage({
583 code: code,
584 tabIndex: tabIndex,
585 });
586 }
587 };
588 loader.init().then((monaco) => {
589 monaco.editor.defineTheme('go-yaml-theme', {
590 base: 'vs-dark',
591 inherit: true,
592 rules: [],
593 colors: {
594 'editor.background': themeBlack,
595 'editor.selectionHighlightBorder': themeBlack,
596 'editor.lineHighlightBackground': themeBlack,
597 'editor.selectionBackground': themeBlack,
598 },
599 });
600 });
601
602 const search = window.location.search;
603 const yamlDataBinary = new URLSearchParams(search).get('content');
604
605 const onMount = (editor: editor.IStandaloneCodeEditor) => {
606 editorRef.current = editor;
607 if (yamlDataBinary) {
608 const code = atob(yamlDataBinary)
609 editor.setValue(code);
610 setContent(code);
611 if (workerRef.current) {
612 workerRef.current.postMessage({
613 code: code,
614 tabIndex: tabIndex,
615 });
616 }
617 }
618 };
619
620 const onTabChange = (_: React.SyntheticEvent, newValue: number) => {
621 setTabIndex(newValue);
622 if (workerRef.current) {
623 workerRef.current.postMessage({
624 code: content,
625 tabIndex: newValue,
626 });
627 }
628 };
629
630 const tabProps = (index: number) => {
631 return {
632 id: `simple-tab-${index}`,
633 'aria-controls': `simple-tabpanel-${index}`,
634 };
635 };
636
637 return (
638 <>
639 <Header content={content} />
640 <Grid container>
641 <Grid marginTop={12} size={{ xs: 12, md: 6 }}>
642 <MonacoEditor
643 height={contentHeight()}
644 language="yaml"
645 theme="go-yaml-theme"
646 options={{
647 fontSize: 16,
648 selectOnLineNumbers: true,
649 renderWhitespace: 'all',
650 autoIndent: 'none',
651 }}
652 onChange={onCodeChange}
653 onMount={onMount}
654 />
655 </Grid>
656 <Grid size={{ xs: 12, md: 6 }}>
657 <Tabs
658 textColor='secondary'
659 indicatorColor='secondary'
660 value={tabIndex}
661 onChange={onTabChange}
662 variant="scrollable"
663 scrollButtons="auto"
664 aria-label="tabs">
665 <Tab icon={<ArrowBackIosNew />} iconPosition="end" style={{ marginLeft: 20 }} label="OUTPUT" {...tabProps(0)} />
666 <Tab icon={<ArrowBackIosNew />} iconPosition="end" style={{ marginLeft: 0 }} label="AST" {...tabProps(1)} />
667 <Tab icon={<ArrowBackIosNew />} iconPosition="end" style={{ marginLeft: 0 }} label="GROUPED TOKENS" {...tabProps(2)} />
668 <Tab style={{ marginLeft: 0 }} label="TOKENS" {...tabProps(3)} />
669 </Tabs>
670 <TabPanel value={tabIndex} index={0}>
671 <TerminalComponent out={out} />
672 </TabPanel>
673 <TabPanel value={tabIndex} index={1}>
674 <AST svg={svg}></AST>
675 </TabPanel>
676 <TabPanel value={tabIndex} index={2}>
677 <ParserGroup tokens={groupedTokens}></ParserGroup>
678 </TabPanel>
679 <TabPanel value={tabIndex} index={3}>
680 <Lexer tokens={tokens}></Lexer>
681 </TabPanel>
682 </Grid>
683 </Grid>
684 </>
685 )
686 }
687
688 export default App