Skip to content

Commit

Permalink
feat: introduces prism-editor package; implements read-only usage (#588)
Browse files Browse the repository at this point in the history
* adds prism editor package and implements in runit

* changes package name

* adds codedisplay util test

* adds tests and minor improvements

* fixes editor font

* removes unused files
  • Loading branch information
noahamac authored Apr 20, 2021
1 parent 11e924f commit 863c88d
Show file tree
Hide file tree
Showing 17 changed files with 395 additions and 50 deletions.
2 changes: 1 addition & 1 deletion packages/api-explorer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"@looker/sdk-codegen": "^21.0.12",
"@looker/sdk-rtl": "^21.0.12",
"ace": "^1.3.0",
"prism-react-renderer": "^1.2.0",
"@looker/code-display": "^0.0.1",
"ace-builds": "^1.4.11",
"history": "^4.10.1",
"lodash": "^4.17.19",
Expand Down
4 changes: 2 additions & 2 deletions packages/api-explorer/src/components/DocCode/DocCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@
import React, { FC, useContext } from 'react'
import AceEditor from 'react-ace'
import { findGenerator } from '@looker/sdk-codegen'
import { CodeDisplay } from '@looker/code-display'
import { SearchContext } from '../../context/search'
import { highlightSourceCode } from './utils'
import { PrismEditor } from './PrismEditor'

// TODO Use webpack resolver instead.
/* eslint-disable @typescript-eslint/ban-ts-comment,@typescript-eslint/no-unused-vars,@typescript-eslint/no-var-requires,import/no-extraneous-dependencies */
Expand Down Expand Up @@ -92,6 +92,6 @@ export const DocCode: FC<DocCodeProps> = ({
}}
/>
) : (
<PrismEditor language={language} code={code} pattern={pattern} />
<CodeDisplay language={language} code={code} pattern={pattern} />
)
}
21 changes: 21 additions & 0 deletions packages/code-display/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Looker Data Sciences, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
36 changes: 36 additions & 0 deletions packages/code-display/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

const base = require('../../jest.config')
const packageName = require('./package.json').name.split('/')[1]

module.exports = {
...base,
displayName: packageName,
name: packageName,
rootDir: '../..',
testMatch: [`<rootDir>/packages/${packageName}/**/*.(spec|test).(ts|js)?(x)`],
}
57 changes: 57 additions & 0 deletions packages/code-display/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@looker/code-display",
"version": "0.0.1",
"description": "A syntax highlighter for Looker apps.",
"main": "lib/esm/index.js",
"typings": "lib/index.d.ts",
"files": [
"lib"
],
"author": "Looker",
"license": "MIT",
"private": true,
"repository": {
"type": "git",
"url": "git+https://github.com/looker-open-source/sdk-codegen.git",
"directory": "packages/code-display"
},
"homepage": "https://github.com/looker-open-source/sdk-codegen/tree/main/packages/code-display",
"bugs": {
"url": "https://github.com/looker-open-source/sdk-codegen/issues"
},
"scripts": {
"test": "jest",
"watch": "yarn lerna exec --scope @looker/code-display --stream 'BABEL_ENV=build babel src --root-mode upward --out-dir lib/esm --source-maps --extensions .ts,.tsx --no-comments --watch'"
},
"devDependencies": {
"@looker/components-test-utils": "^0.9.29",
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.6.0",
"@types/lodash": "^4.14.157",
"@types/react": "^16.14.2",
"@types/react-dom": "^16.9.6",
"@types/react-router": "^5.1.11",
"@types/react-router-dom": "^5.1.5",
"@types/react-test-renderer": "^17.0.0",
"@types/styled-components": "^5.1.7",
"enzyme": "^3.11.0",
"jest-config": "^25.3.0",
"react-router-dom": "^5.2.0",
"react-test-renderer": "^17.0.1",
"style-loader": "^1.1.3",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"@looker/components": "^0.9.30",
"@looker/design-tokens": "0.9.27",
"@looker/sdk-codegen": "^21.0.11",
"prism-react-renderer": "^1.2.0",
"lodash": "^4.17.19",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-is": "^16.13.1",
"styled-components": "^5.2.1"
}
}
73 changes: 73 additions & 0 deletions packages/code-display/src/CodeDisplay.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import React from 'react'
import { screen } from '@testing-library/react'
import { renderWithTheme } from '@looker/components-test-utils'

import { CodeDisplay } from './CodeDisplay'

describe('CodeDisplay', () => {
const code = `
# GET /lookml_models -> Sequence[models.LookmlModel]
def all_lookml_models(
self,
# Requested fields.
fields: Optional[str] = None,
transport_options: Optional[transport.TransportOptions] = None,
) -> Sequence[models.LookmlModel]:
"""Get All LookML Models"""
response = self.get(
f"/lookml_models",
Sequence[models.LookmlModel],
query_params={"fields": fields},
transport_options=transport_options
)
assert isinstance(response, list)
return response
`
test('it syntax highlights', () => {
renderWithTheme(<CodeDisplay code={code} language="python" />)
expect(screen.getByText('all_lookml_models').closest('span')).toHaveClass(
'function'
)
expect(screen.getByText('def').closest('span')).toHaveClass('keyword')
expect(
screen
.getByText('# GET /lookml_models -> Sequence[models.LookmlModel]')
.closest('span')
).toHaveClass('comment')
})

test('it highlights text matching search pattern', () => {
const highlightPattern = 'lookml_models'
renderWithTheme(
<CodeDisplay code={code} language="python" pattern={highlightPattern} />
)
expect(screen.getByText('all_lookml_models').closest('span')).toHaveClass(
'match'
)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -26,80 +26,82 @@

import React, { FC } from 'react'
import styled from 'styled-components'
import Highlight, { defaultProps, Language } from 'prism-react-renderer'
import { Span } from '@looker/components'
import Highlight, { defaultProps } from 'prism-react-renderer'
// import { Prism } from "prism-react-renderer"
import dracula from 'prism-react-renderer/themes/dracula'

import { getPrismLanguage, getOverridenTheme } from './utils'
// TODO enable kotlin, csharp, swift highlighting
// (typeof global !== "undefined" ? global : window).Prism = Prism
// require("prismjs/components/prism-kotlin")
// require("prismjs/components/prism-csharp")
// require("prismjs/components/prism-swift")

interface PrismEditorProps {
language: string
/** SDK programming language */
language?: string
/** Code blob to be highlighted */
code: string
pattern: string
/** Pattern to be search (if applicable) */
pattern?: string
}

const Pre = styled.pre`
padding: 1rem;
overflow: auto;
white-space: pre-wrap;
.match {
border: 1px yellow solid;
border-radius: 4px;
}
`

const Line = styled.div`
display: table-row;
`

const LineNo = styled.span`
const LineNo = styled(Span)`
display: table-cell;
text-align: right;
padding-right: 1em;
user-select: none;
opacity: 0.5;
`

const LineContent = styled.span`
const LineContent = styled(Span)`
display: table-cell;
font-family: monospace;
`

export const PrismEditor: FC<PrismEditorProps> = ({
language,
/**
* The PrismEditor provides a useful implementation of prism-react-renderer
* for Looker apps. Syntax highlighting is available for all supported SDK languages.
* TODO: LookML syntax highlighting
*/
export const CodeDisplay: FC<PrismEditorProps> = ({
language = 'json',
code,
pattern,
pattern = '',
}) => {
const getPrismLanguage = (language: string) => {
const unstyled = ['kotlin', 'csharp', 'swift']
// TODO revert back to `go` in generator language definitions instead of using this
if (language === 'golang') {
return 'go'
} else if (unstyled.includes(language)) {
return 'clike'
}
return language as Language
}

const highlighterLang = getPrismLanguage(language)
return (
<Highlight
{...defaultProps}
code={code}
language={getPrismLanguage(language)}
theme={dracula}
language={highlighterLang}
theme={getOverridenTheme()}
>
{({ className, style, tokens, getLineProps, getTokenProps }) => (
<Pre className={className} style={style}>
{tokens.map((line, i) => (
<Line key={i} {...getLineProps({ line, key: i })}>
<LineNo>{i + 1}</LineNo>
{language === 'json' || <LineNo>{i + 1}</LineNo>}
<LineContent>
{line.map((token, key) => {
const tokenProps = getTokenProps({ token, key })
const text = tokenProps.children
if (pattern !== '' && text.includes(pattern)) {
tokenProps.style = {
...tokenProps.style,
border: '1px yellow solid',
borderRadius: '4px',
}
tokenProps.className += ' match'
}
return <span key={key} {...tokenProps} />
})}
Expand Down
26 changes: 26 additions & 0 deletions packages/code-display/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
export { CodeDisplay } from './CodeDisplay'
26 changes: 26 additions & 0 deletions packages/code-display/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
export { getPrismLanguage, getOverridenTheme } from './utils'
Loading

0 comments on commit 863c88d

Please sign in to comment.