You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ma...@apache.org on 2025/07/02 19:38:27 UTC
(superset) 01/02: chore: refactor react-syntax-highlither to handle dark themes
This is an automated email from the ASF dual-hosted git repository.
maximebeauchemin pushed a commit to branch syntax-highlither-themed
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 89d0b54139291765762a6dd2e90730ebf7ce2eff
Author: Maxime Beauchemin <ma...@gmail.com>
AuthorDate: Wed Jul 2 11:51:45 2025 -0700
chore: refactor react-syntax-highlither to handle dark themes
It appears `react-syntax-highlither` has been used directly without wrappers in the past, making it hard to style / theme it properly as it's used in the app.
In this PR:
- write a simple wrapper for `react-syntax-highlither` that's theme-aware
- refactor all usage of `react-syntax-highlither` in the main app to use this new component
- basic styling that switches based on whether the theme is dark or not (doesn't use the intricate brand colors for now)
- basic unit tests and storybook for the new wrapper
---
superset-frontend/package-lock.json | 4 +-
superset-frontend/package.json | 2 -
.../packages/superset-ui-core/package.json | 2 +
.../CodeSyntaxHighlighter/index.test.tsx | 164 ++++++++++++
.../src/components/CodeSyntaxHighlighter/index.tsx | 148 +++++++++++
.../src/types/react-syntax-highlighter.d.ts | 0
.../src/SqlLab/components/HighlightedSql/index.tsx | 277 ++++++++++++---------
.../src/SqlLab/components/ShowSQL/index.tsx | 18 +-
.../src/explore/components/controls/ViewQuery.tsx | 31 +--
.../src/features/home/SavedQueries.tsx | 57 +++--
.../src/features/queries/SyntaxHighlighterCopy.tsx | 95 ++++---
.../src/pages/QueryHistoryList/index.tsx | 47 +++-
12 files changed, 636 insertions(+), 209 deletions(-)
diff --git a/superset-frontend/package-lock.json b/superset-frontend/package-lock.json
index af757fd6ee..18677bc596 100644
--- a/superset-frontend/package-lock.json
+++ b/superset-frontend/package-lock.json
@@ -118,7 +118,6 @@
"react-search-input": "^0.11.3",
"react-sortable-hoc": "^2.0.0",
"react-split": "^2.0.9",
- "react-syntax-highlighter": "^15.4.5",
"react-table": "^7.8.0",
"react-transition-group": "^4.4.5",
"react-virtualized-auto-sizer": "^1.0.25",
@@ -196,7 +195,6 @@
"@types/react-redux": "^7.1.10",
"@types/react-resizable": "^3.0.8",
"@types/react-router-dom": "^5.3.3",
- "@types/react-syntax-highlighter": "^15.5.13",
"@types/react-transition-group": "^4.4.12",
"@types/react-ultimate-pagination": "^1.2.4",
"@types/react-virtualized-auto-sizer": "^1.0.4",
@@ -53903,6 +53901,7 @@
"react-js-cron": "^5.2.0",
"react-markdown": "^8.0.7",
"react-resize-detector": "^7.1.2",
+ "react-syntax-highlighter": "^15.4.5",
"react-ultimate-pagination": "^1.3.2",
"regenerator-runtime": "^0.14.1",
"rehype-raw": "^7.0.0",
@@ -53925,6 +53924,7 @@
"@types/math-expression-evaluator": "^1.3.3",
"@types/node": "^22.10.3",
"@types/prop-types": "^15.7.2",
+ "@types/react-syntax-highlighter": "^15.5.13",
"@types/react-table": "^7.7.20",
"@types/rison": "0.1.0",
"@types/seedrandom": "^3.0.8",
diff --git a/superset-frontend/package.json b/superset-frontend/package.json
index bf3a7571c6..5562db96c8 100644
--- a/superset-frontend/package.json
+++ b/superset-frontend/package.json
@@ -186,7 +186,6 @@
"react-search-input": "^0.11.3",
"react-sortable-hoc": "^2.0.0",
"react-split": "^2.0.9",
- "react-syntax-highlighter": "^15.4.5",
"react-table": "^7.8.0",
"react-transition-group": "^4.4.5",
"react-virtualized-auto-sizer": "^1.0.25",
@@ -264,7 +263,6 @@
"@types/react-redux": "^7.1.10",
"@types/react-resizable": "^3.0.8",
"@types/react-router-dom": "^5.3.3",
- "@types/react-syntax-highlighter": "^15.5.13",
"@types/react-transition-group": "^4.4.12",
"@types/react-ultimate-pagination": "^1.2.4",
"@types/react-virtualized-auto-sizer": "^1.0.4",
diff --git a/superset-frontend/packages/superset-ui-core/package.json b/superset-frontend/packages/superset-ui-core/package.json
index cb504c8a3d..6a8684fe43 100644
--- a/superset-frontend/packages/superset-ui-core/package.json
+++ b/superset-frontend/packages/superset-ui-core/package.json
@@ -51,6 +51,7 @@
"react-js-cron": "^5.2.0",
"react-draggable": "^4.4.6",
"react-resize-detector": "^7.1.2",
+ "react-syntax-highlighter": "^15.4.5",
"react-ultimate-pagination": "^1.3.2",
"react-error-boundary": "^5.0.0",
"react-markdown": "^8.0.7",
@@ -72,6 +73,7 @@
"@types/d3-time": "^3.0.4",
"@types/d3-time-format": "^4.0.3",
"@types/react-table": "^7.7.20",
+ "@types/react-syntax-highlighter": "^15.5.13",
"@types/jquery": "^3.5.8",
"@types/lodash": "^4.17.16",
"@types/math-expression-evaluator": "^1.3.3",
diff --git a/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.test.tsx b/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.test.tsx
new file mode 100644
index 0000000000..deb295fed6
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.test.tsx
@@ -0,0 +1,164 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen } from '../../spec';
+import CodeSyntaxHighlighter from './index';
+
+// Simple mock that just returns the content
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/light',
+ () =>
+ function MockSyntaxHighlighter({ children, ...props }: any) {
+ return (
+ <pre data-testid="syntax-highlighter" data-language={props.language}>
+ {children}
+ </pre>
+ );
+ },
+);
+
+// Mock the language modules
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/languages/hljs/sql',
+ () => 'sql-mock',
+);
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/languages/hljs/json',
+ () => 'json-mock',
+);
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars',
+ () => 'html-mock',
+);
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown',
+ () => 'md-mock',
+);
+
+// Mock the styles
+jest.mock('react-syntax-highlighter/dist/cjs/styles/hljs/github', () => ({}));
+jest.mock(
+ 'react-syntax-highlighter/dist/cjs/styles/hljs/atom-one-dark',
+ () => ({}),
+);
+
+describe('CodeSyntaxHighlighter', () => {
+ it('renders code content', () => {
+ render(<CodeSyntaxHighlighter>SELECT * FROM users;</CodeSyntaxHighlighter>);
+
+ expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
+ });
+
+ it('renders with default SQL language', () => {
+ render(<CodeSyntaxHighlighter>SELECT * FROM users;</CodeSyntaxHighlighter>);
+
+ // Should show content (the important thing is content is visible)
+ expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
+ });
+
+ it('renders with specified language', () => {
+ render(
+ <CodeSyntaxHighlighter language="json">
+ {`{ "key": "value" }`}
+ </CodeSyntaxHighlighter>,
+ );
+
+ // Should show content regardless of which element renders it
+ expect(screen.getByText('{ "key": "value" }')).toBeInTheDocument();
+ });
+
+ it('supports all expected languages', () => {
+ const languages = ['sql', 'json', 'htmlbars', 'markdown'] as const;
+
+ languages.forEach(language => {
+ const { unmount } = render(
+ <CodeSyntaxHighlighter language={language}>
+ Test content for {language}
+ </CodeSyntaxHighlighter>,
+ );
+
+ // Should render the content (either in fallback or syntax highlighter)
+ expect(
+ screen.getByText(`Test content for ${language}`),
+ ).toBeInTheDocument();
+
+ unmount();
+ });
+ });
+
+ it('renders fallback pre element initially', () => {
+ render(
+ <CodeSyntaxHighlighter language="sql">
+ SELECT COUNT(*) FROM table;
+ </CodeSyntaxHighlighter>,
+ );
+
+ // Should render the content in some form
+ expect(screen.getByText('SELECT COUNT(*) FROM table;')).toBeInTheDocument();
+ });
+
+ it('handles empty content', () => {
+ render(<CodeSyntaxHighlighter language="sql" />);
+
+ // Should render without throwing an error - the exact element doesn't matter
+ // as long as the component doesn't crash
+ expect(document.body).toBeInTheDocument();
+ });
+
+ it('handles special characters', () => {
+ const specialContent = "SELECT * FROM `users` WHERE name = 'O\\'Brien';";
+
+ render(
+ <CodeSyntaxHighlighter language="sql">
+ {specialContent}
+ </CodeSyntaxHighlighter>,
+ );
+
+ expect(screen.getByText(specialContent)).toBeInTheDocument();
+ });
+
+ it('accepts custom styles', () => {
+ render(
+ <CodeSyntaxHighlighter language="sql" customStyle={{ fontSize: '16px' }}>
+ SELECT * FROM users;
+ </CodeSyntaxHighlighter>,
+ );
+
+ expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
+ });
+
+ it('accepts showLineNumbers prop', () => {
+ render(
+ <CodeSyntaxHighlighter language="sql" showLineNumbers>
+ SELECT * FROM users;
+ </CodeSyntaxHighlighter>,
+ );
+
+ expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
+ });
+
+ it('accepts wrapLines prop', () => {
+ render(
+ <CodeSyntaxHighlighter language="sql" wrapLines={false}>
+ SELECT * FROM users;
+ </CodeSyntaxHighlighter>,
+ );
+
+ expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
+ });
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.tsx b/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.tsx
new file mode 100644
index 0000000000..89d2e0d699
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-core/src/components/CodeSyntaxHighlighter/index.tsx
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useState } from 'react';
+import SyntaxHighlighterBase from 'react-syntax-highlighter/dist/cjs/light';
+import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
+import atomOneDark from 'react-syntax-highlighter/dist/cjs/styles/hljs/atom-one-dark';
+import { themeObject } from '@superset-ui/core';
+
+export type SupportedLanguage = 'sql' | 'htmlbars' | 'markdown' | 'json';
+
+export interface CodeSyntaxHighlighterProps {
+ children: string;
+ language?: SupportedLanguage;
+ customStyle?: React.CSSProperties;
+ showLineNumbers?: boolean;
+ wrapLines?: boolean;
+ style?: any; // Override theme style if needed
+}
+
+// Track which languages have been registered to avoid duplicate registrations
+const registeredLanguages = new Set<SupportedLanguage>();
+
+// Language import functions - these will be called lazily
+const languageImporters = {
+ sql: () => import('react-syntax-highlighter/dist/cjs/languages/hljs/sql'),
+ htmlbars: () =>
+ import('react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars'),
+ markdown: () =>
+ import('react-syntax-highlighter/dist/cjs/languages/hljs/markdown'),
+ json: () => import('react-syntax-highlighter/dist/cjs/languages/hljs/json'),
+};
+
+/**
+ * Lazily register a language for syntax highlighting
+ */
+const registerLanguage = async (language: SupportedLanguage): Promise<void> => {
+ if (registeredLanguages.has(language)) {
+ return; // Already registered
+ }
+
+ try {
+ const languageModule = await languageImporters[language]();
+ SyntaxHighlighterBase.registerLanguage(language, languageModule.default);
+ registeredLanguages.add(language);
+ } catch (error) {
+ console.warn(`Failed to load language ${language}:`, error);
+ }
+};
+
+/**
+ * A themed syntax highlighter component that automatically adapts to Superset's current theme.
+ * Supports light/dark mode switching and provides consistent styling across the application.
+ * Languages are loaded lazily to improve initial page load performance.
+ */
+export const CodeSyntaxHighlighter: React.FC<CodeSyntaxHighlighterProps> = ({
+ children,
+ language = 'sql',
+ customStyle = {},
+ showLineNumbers = false,
+ wrapLines = true,
+ style: overrideStyle,
+}) => {
+ const [isLanguageReady, setIsLanguageReady] = useState(
+ registeredLanguages.has(language),
+ );
+
+ useEffect(() => {
+ const loadLanguage = async () => {
+ if (!registeredLanguages.has(language)) {
+ await registerLanguage(language);
+ setIsLanguageReady(true);
+ }
+ };
+
+ loadLanguage();
+ }, [language]);
+
+ const isDark = themeObject.isThemeDark();
+ const themeStyle = overrideStyle || (isDark ? atomOneDark : github);
+
+ const defaultCustomStyle: React.CSSProperties = {
+ background: themeObject.theme.colorBgElevated,
+ padding: themeObject.theme.sizeUnit * 4,
+ border: 0,
+ borderRadius: themeObject.theme.borderRadius,
+ ...customStyle,
+ };
+
+ // Show a simple pre-formatted text while language is loading
+ if (!isLanguageReady) {
+ return (
+ <pre
+ style={{
+ ...defaultCustomStyle,
+ fontFamily: 'monospace',
+ whiteSpace: 'pre-wrap',
+ margin: 0,
+ }}
+ >
+ {children}
+ </pre>
+ );
+ }
+
+ return (
+ <SyntaxHighlighterBase
+ language={language}
+ style={themeStyle}
+ customStyle={defaultCustomStyle}
+ showLineNumbers={showLineNumbers}
+ wrapLines={wrapLines}
+ >
+ {children}
+ </SyntaxHighlighterBase>
+ );
+};
+
+/**
+ * Utility function to preload specific languages if needed
+ * This can be called strategically in components that know they'll need certain languages
+ */
+export const preloadLanguages = async (
+ languages: SupportedLanguage[],
+): Promise<void> => {
+ const promises = languages
+ .filter(lang => !registeredLanguages.has(lang))
+ .map(registerLanguage);
+
+ await Promise.all(promises);
+};
+
+export default CodeSyntaxHighlighter;
diff --git a/superset-frontend/src/types/react-syntax-highlighter.d.ts b/superset-frontend/packages/superset-ui-core/src/types/react-syntax-highlighter.d.ts
similarity index 100%
rename from superset-frontend/src/types/react-syntax-highlighter.d.ts
rename to superset-frontend/packages/superset-ui-core/src/types/react-syntax-highlighter.d.ts
diff --git a/superset-frontend/src/SqlLab/components/HighlightedSql/index.tsx b/superset-frontend/src/SqlLab/components/HighlightedSql/index.tsx
index 2733b4ae81..2f3ce9a0fb 100644
--- a/superset-frontend/src/SqlLab/components/HighlightedSql/index.tsx
+++ b/superset-frontend/src/SqlLab/components/HighlightedSql/index.tsx
@@ -16,139 +16,176 @@
* specific language governing permissions and limitations
* under the License.
*/
-import SyntaxHighlighterBase from 'react-syntax-highlighter/dist/cjs/light';
-import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
-import atomOneDark from 'react-syntax-highlighter/dist/cjs/styles/hljs/atom-one-dark';
-import { t, themeObject } from '@superset-ui/core';
-import { ModalTrigger } from '@superset-ui/core/components';
+import {
+ FC,
+ KeyboardEvent,
+ MouseEvent,
+ useCallback,
+ useEffect,
+ useState,
+} from 'react';
+import rison from 'rison';
+import { styled, SupersetClient, t } from '@superset-ui/core';
+import { Icons, Switch, Button, Skeleton } from '@superset-ui/core/components';
+import { CopyToClipboard } from 'src/components';
+import { CopyButton } from 'src/explore/components/DataTableControl';
+import CodeSyntaxHighlighter, {
+ SupportedLanguage,
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
+import { useHistory } from 'react-router-dom';
-SyntaxHighlighterBase.registerLanguage('sql', sql);
+const CopyButtonViewQuery = styled(CopyButton)`
+ ${({ theme }) => `
+ && {
+ margin: 0 0 ${theme.sizeUnit}px;
+ }
+ `}
+`;
-const ThemedSyntaxHighlighter = ({
- children,
- style,
-}: {
- children: string;
- style: any;
-}) => (
- <SyntaxHighlighterBase
- language="sql"
- style={style}
- customStyle={{
- background: themeObject.theme.colorBgElevated,
- padding: themeObject.theme.sizeUnit * 4,
- border: 0,
- }}
- >
- {children}
- </SyntaxHighlighterBase>
-);
-
-export interface HighlightedSqlProps {
+export interface ViewQueryProps {
sql: string;
- rawSql?: string;
- maxWidth?: number;
- maxLines?: number;
- shrink?: any;
+ datasource: string;
+ language?: SupportedLanguage;
}
-interface HighlightedSqlModalTypes {
- rawSql?: string;
- sql: string;
- syntaxTheme: any;
-}
+const StyledSyntaxContainer = styled.div`
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+`;
-interface TriggerNodeProps {
- shrink: boolean;
- sql: string;
- maxLines: number;
- maxWidth: number;
- syntaxTheme: any;
-}
+const StyledHeaderMenuContainer = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ margin-top: ${({ theme }) => -theme.sizeUnit * 4}px;
+ align-items: flex-end;
+`;
+
+const StyledHeaderActionContainer = styled.div`
+ display: flex;
+ flex-direction: row;
+ column-gap: ${({ theme }) => theme.sizeUnit * 2}px;
+`;
-const shrinkSql = (sql: string, maxLines: number, maxWidth: number) => {
- const ssql = sql || '';
- let lines = ssql.split('\n');
- if (lines.length >= maxLines) {
- lines = lines.slice(0, maxLines);
- lines.push('{...}');
- }
- return lines
- .map(line =>
- line.length > maxWidth ? `${line.slice(0, maxWidth)}{...}` : line,
- )
- .join('\n');
+const StyledCodeSyntaxHighlighter = styled(CodeSyntaxHighlighter)`
+ flex: 1;
+`;
+
+const StyledLabel = styled.label`
+ font-size: ${({ theme }) => theme.fontSize}px;
+`;
+
+const DATASET_BACKEND_QUERY = {
+ keys: ['none'],
+ columns: ['database.backend'],
};
-function TriggerNode({
- shrink,
- sql,
- maxLines,
- maxWidth,
- syntaxTheme,
-}: TriggerNodeProps) {
- return (
- <ThemedSyntaxHighlighter style={syntaxTheme}>
- {shrink ? shrinkSql(sql, maxLines, maxWidth) : sql}
- </ThemedSyntaxHighlighter>
- );
-}
+const ViewQuery: FC<ViewQueryProps> = props => {
+ const { sql, language = 'sql', datasource } = props;
+ const datasetId = datasource.split('__')[0];
+ const [formattedSQL, setFormattedSQL] = useState<string>();
+ const [showFormatSQL, setShowFormatSQL] = useState(true);
+ const history = useHistory();
+ const currentSQL = (showFormatSQL ? formattedSQL : sql) ?? sql;
-function HighlightSqlModal({
- rawSql,
- sql,
- syntaxTheme,
-}: HighlightedSqlModalTypes) {
- return (
- <div>
- <h4>{t('Source SQL')}</h4>
- <ThemedSyntaxHighlighter style={syntaxTheme}>
- {sql}
- </ThemedSyntaxHighlighter>
- {rawSql && rawSql !== sql && (
- <div>
- <h4>{t('Executed SQL')}</h4>
- <ThemedSyntaxHighlighter style={syntaxTheme}>
- {rawSql}
- </ThemedSyntaxHighlighter>
- </div>
- )}
- </div>
+ // Preload the language when component mounts to ensure smooth experience
+ useEffect(() => {
+ preloadLanguages([language]);
+ }, [language]);
+
+ const formatCurrentQuery = useCallback(() => {
+ if (formattedSQL) {
+ setShowFormatSQL(val => !val);
+ } else {
+ const queryParams = rison.encode(DATASET_BACKEND_QUERY);
+ SupersetClient.get({
+ endpoint: `/api/v1/dataset/${datasetId}?q=${queryParams}`,
+ })
+ .then(({ json }) =>
+ SupersetClient.post({
+ endpoint: `/api/v1/sqllab/format_sql/`,
+ body: JSON.stringify({
+ sql,
+ engine: json.result.database.backend,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ )
+ .then(({ json }) => {
+ setFormattedSQL(json.result);
+ setShowFormatSQL(true);
+ })
+ .catch(() => {
+ setShowFormatSQL(true);
+ });
+ }
+ }, [sql, datasetId, formattedSQL]);
+
+ const navToSQLLab = useCallback(
+ (domEvent: KeyboardEvent<HTMLElement> | MouseEvent<HTMLElement>) => {
+ const requestedQuery = {
+ datasourceKey: datasource,
+ sql: currentSQL,
+ };
+ if (domEvent.metaKey || domEvent.ctrlKey) {
+ domEvent.preventDefault();
+ window.open(
+ `/sqllab?datasourceKey=${datasource}&sql=${currentSQL}`,
+ '_blank',
+ );
+ } else {
+ history.push('/sqllab', { state: { requestedQuery } });
+ }
+ },
+ [history, datasource, currentSQL],
);
-}
-function HighlightedSql({
- sql,
- rawSql,
- maxWidth = 50,
- maxLines = 5,
- shrink = false,
-}: HighlightedSqlProps) {
- const isDark = themeObject.isThemeDark();
- const syntaxTheme = isDark ? atomOneDark : github;
+ useEffect(() => {
+ formatCurrentQuery();
+ }, [sql]);
return (
- <ModalTrigger
- modalTitle={t('SQL')}
- modalBody={
- <HighlightSqlModal
- rawSql={rawSql}
- sql={sql}
- syntaxTheme={syntaxTheme}
- />
- }
- triggerNode={
- <TriggerNode
- shrink={shrink}
- sql={sql}
- maxLines={maxLines}
- maxWidth={maxWidth}
- syntaxTheme={syntaxTheme}
- />
- }
- />
+ <StyledSyntaxContainer key={sql}>
+ <StyledHeaderMenuContainer>
+ <StyledHeaderActionContainer>
+ <CopyToClipboard
+ text={currentSQL}
+ shouldShowText={false}
+ copyNode={
+ <CopyButtonViewQuery
+ buttonSize="small"
+ icon={<Icons.CopyOutlined />}
+ >
+ {t('Copy')}
+ </CopyButtonViewQuery>
+ }
+ />
+ <Button onClick={navToSQLLab}>{t('View in SQL Lab')}</Button>
+ </StyledHeaderActionContainer>
+ <StyledHeaderActionContainer>
+ <Switch
+ id="formatSwitch"
+ checked={!showFormatSQL}
+ onChange={formatCurrentQuery}
+ />
+ <StyledLabel htmlFor="formatSwitch">
+ {t('Show original SQL')}
+ </StyledLabel>
+ </StyledHeaderActionContainer>
+ </StyledHeaderMenuContainer>
+ {!formattedSQL && <Skeleton active />}
+ {formattedSQL && (
+ <StyledCodeSyntaxHighlighter
+ language={language}
+ customStyle={{ flex: 1 }}
+ >
+ {currentSQL}
+ </StyledCodeSyntaxHighlighter>
+ )}
+ </StyledSyntaxContainer>
);
-}
+};
-export default HighlightedSql;
+export default ViewQuery;
diff --git a/superset-frontend/src/SqlLab/components/ShowSQL/index.tsx b/superset-frontend/src/SqlLab/components/ShowSQL/index.tsx
index a9739faace..267f735c50 100644
--- a/superset-frontend/src/SqlLab/components/ShowSQL/index.tsx
+++ b/superset-frontend/src/SqlLab/components/ShowSQL/index.tsx
@@ -16,13 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
-import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
+import { useEffect } from 'react';
import { IconTooltip, ModalTrigger } from '@superset-ui/core/components';
import { Icons } from '@superset-ui/core/components/Icons';
-
-SyntaxHighlighter.registerLanguage('sql', sql);
+import CodeSyntaxHighlighter, {
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
interface ShowSQLProps {
sql: string;
@@ -37,6 +36,11 @@ export default function ShowSQL({
sql: sqlString,
triggerNode,
}: ShowSQLProps) {
+ // Preload SQL language since this component will definitely use it when modal opens
+ useEffect(() => {
+ preloadLanguages(['sql']);
+ }, []);
+
return (
<ModalTrigger
modalTitle={title}
@@ -49,9 +53,9 @@ export default function ShowSQL({
}
modalBody={
<div>
- <SyntaxHighlighter language="sql" style={github}>
+ <CodeSyntaxHighlighter language="sql">
{sqlString}
- </SyntaxHighlighter>
+ </CodeSyntaxHighlighter>
</div>
}
/>
diff --git a/superset-frontend/src/explore/components/controls/ViewQuery.tsx b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
index da5e7d0454..dca607e846 100644
--- a/superset-frontend/src/explore/components/controls/ViewQuery.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
@@ -26,15 +26,13 @@ import {
} from 'react';
import rison from 'rison';
import { styled, SupersetClient, t } from '@superset-ui/core';
-import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import { Icons, Switch, Button, Skeleton } from '@superset-ui/core/components';
import { CopyToClipboard } from 'src/components';
import { CopyButton } from 'src/explore/components/DataTableControl';
-import markdownSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown';
-import htmlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars';
-import sqlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import jsonSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/json';
+import CodeSyntaxHighlighter, {
+ SupportedLanguage,
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
import { useHistory } from 'react-router-dom';
const CopyButtonViewQuery = styled(CopyButton)`
@@ -45,15 +43,10 @@ const CopyButtonViewQuery = styled(CopyButton)`
`}
`;
-SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
-SyntaxHighlighter.registerLanguage('html', htmlSyntax);
-SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
-SyntaxHighlighter.registerLanguage('json', jsonSyntax);
-
export interface ViewQueryProps {
sql: string;
datasource: string;
- language?: string;
+ language?: SupportedLanguage;
}
const StyledSyntaxContainer = styled.div`
@@ -76,7 +69,7 @@ const StyledHeaderActionContainer = styled.div`
column-gap: ${({ theme }) => theme.sizeUnit * 2}px;
`;
-const StyledSyntaxHighlighter = styled(SyntaxHighlighter)`
+const StyledThemedSyntaxHighlighter = styled(CodeSyntaxHighlighter)`
flex: 1;
`;
@@ -97,6 +90,11 @@ const ViewQuery: FC<ViewQueryProps> = props => {
const history = useHistory();
const currentSQL = (showFormatSQL ? formattedSQL : sql) ?? sql;
+ // Preload the language when component mounts to ensure smooth experience
+ useEffect(() => {
+ preloadLanguages([language]);
+ }, [language]);
+
const formatCurrentQuery = useCallback(() => {
if (formattedSQL) {
setShowFormatSQL(val => !val);
@@ -179,9 +177,12 @@ const ViewQuery: FC<ViewQueryProps> = props => {
</StyledHeaderMenuContainer>
{!formattedSQL && <Skeleton active />}
{formattedSQL && (
- <StyledSyntaxHighlighter language={language} style={github}>
+ <StyledThemedSyntaxHighlighter
+ language={language}
+ customStyle={{ flex: 1 }}
+ >
{currentSQL}
- </StyledSyntaxHighlighter>
+ </StyledThemedSyntaxHighlighter>
)}
</StyledSyntaxContainer>
);
diff --git a/superset-frontend/src/features/home/SavedQueries.tsx b/superset-frontend/src/features/home/SavedQueries.tsx
index 8051d5891f..fc805f3699 100644
--- a/superset-frontend/src/features/home/SavedQueries.tsx
+++ b/superset-frontend/src/features/home/SavedQueries.tsx
@@ -16,12 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useCallback, useState } from 'react';
+import { useCallback, useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { styled, SupersetClient, t, useTheme, css } from '@superset-ui/core';
-import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
-import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
+import CodeSyntaxHighlighter, {
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
import { LoadingCards } from 'src/pages/Home';
import { TableTab } from 'src/views/CRUD/types';
import withToasts from 'src/components/MessageToasts/withToasts';
@@ -49,8 +49,6 @@ import SubMenu from './SubMenu';
import EmptyState from './EmptyState';
import { WelcomeTable } from './types';
-SyntaxHighlighter.registerLanguage('sql', sql);
-
interface Query {
id?: number;
sql_tables?: Array<any>;
@@ -110,13 +108,20 @@ const QueryData = styled.div`
`;
const QueryContainer = styled.div`
- pre {
+ /* Custom styles for the syntax highlighter in cards */
+ & > div {
height: ${({ theme }) => theme.sizeUnit * 40}px;
border: none !important;
- background-color: ${({ theme }) =>
- theme.colors.grayscale.light5} !important;
- overflow: hidden;
- padding: ${({ theme }) => theme.sizeUnit * 4}px !important;
+ overflow: hidden !important;
+
+ pre {
+ height: 100%;
+ margin: 0;
+ border: none;
+ overflow: hidden;
+ word-break: break-all;
+ white-space: pre-wrap;
+ }
}
`;
@@ -151,6 +156,13 @@ export const SavedQueries = ({
const theme = useTheme();
+ // Preload SQL language since we'll likely show SQL snippets
+ useEffect(() => {
+ if (showThumbnails && featureFlag) {
+ preloadLanguages(['sql']);
+ }
+ }, [showThumbnails, featureFlag]);
+
const handleQueryDelete = ({ id, label }: Query) => {
SupersetClient.delete({
endpoint: `/api/v1/saved_query/${id}`,
@@ -315,24 +327,21 @@ export const SavedQueries = ({
cover={
q?.sql?.length && showThumbnails && featureFlag ? (
<QueryContainer>
- <SyntaxHighlighter
+ <CodeSyntaxHighlighter
language="sql"
- lineProps={{
- style: {
- color: theme.colors.grayscale.dark2,
- wordBreak: 'break-all',
- whiteSpace: 'pre-wrap',
- },
- }}
- style={github}
+ showLineNumbers={false}
wrapLines
- lineNumberStyle={{
- display: 'none',
+ customStyle={{
+ height: theme.sizeUnit * 40,
+ border: 'none',
+ overflow: 'hidden',
+ color: theme.colors.grayscale.dark2,
+ wordBreak: 'break-all',
+ whiteSpace: 'pre-wrap',
}}
- showLineNumbers={false}
>
{shortenSQL(q.sql, 25)}
- </SyntaxHighlighter>
+ </CodeSyntaxHighlighter>
</QueryContainer>
) : showThumbnails && !q?.sql?.length ? (
false
diff --git a/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx b/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
index d6e5bee15c..f29abbc621 100644
--- a/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
+++ b/superset-frontend/src/features/queries/SyntaxHighlighterCopy.tsx
@@ -16,58 +16,79 @@
* specific language governing permissions and limitations
* under the License.
*/
+import { useEffect } from 'react';
import { styled, t } from '@superset-ui/core';
-import { SyntaxHighlighterProps } from 'react-syntax-highlighter';
-import sqlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import htmlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars';
-import markdownSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown';
-import jsonSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/json';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
-import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
+import CodeSyntaxHighlighter, {
+ SupportedLanguage,
+ ThemedCodeSyntaxHighlighterProps,
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
import { Icons } from '@superset-ui/core/components/Icons';
import { ToastProps } from 'src/components/MessageToasts/withToasts';
import copyTextToClipboard from 'src/utils/copy';
-SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
-SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
-SyntaxHighlighter.registerLanguage('html', htmlSyntax);
-SyntaxHighlighter.registerLanguage('json', jsonSyntax);
-
const SyntaxHighlighterWrapper = styled.div`
+ position: relative;
margin-top: -24px;
&:hover {
- svg {
+ .copy-button {
visibility: visible;
}
}
- svg {
- position: relative;
+ .copy-button {
+ position: absolute;
top: 40px;
- left: 512px;
+ right: 16px;
+ z-index: 10;
visibility: hidden;
margin: -4px;
+ padding: 4px;
+ background: ${({ theme }) => theme.colors.grayscale.light4};
+ border-radius: ${({ theme }) => theme.borderRadius}px;
color: ${({ theme }) => theme.colors.grayscale.base};
+ cursor: pointer;
+ transition: all 0.2s ease;
+
+ &:hover {
+ background: ${({ theme }) => theme.colors.grayscale.light2};
+ color: ${({ theme }) => theme.colors.grayscale.dark1};
+ }
+
+ &:focus {
+ visibility: visible;
+ outline: 2px solid ${({ theme }) => theme.colors.primary.base};
+ outline-offset: 2px;
+ }
}
`;
+interface SyntaxHighlighterCopyProps
+ extends Omit<ThemedCodeSyntaxHighlighterProps, 'children'> {
+ children: string;
+ addDangerToast?: ToastProps['addDangerToast'];
+ addSuccessToast?: ToastProps['addSuccessToast'];
+ language: SupportedLanguage;
+}
+
export default function SyntaxHighlighterCopy({
addDangerToast,
addSuccessToast,
children,
+ language,
...syntaxHighlighterProps
-}: SyntaxHighlighterProps & {
- children: string;
- addDangerToast?: ToastProps['addDangerToast'];
- addSuccessToast?: ToastProps['addSuccessToast'];
- language: 'sql' | 'markdown' | 'html' | 'json';
-}) {
+}: SyntaxHighlighterCopyProps) {
+ // Preload the language when component mounts
+ useEffect(() => {
+ preloadLanguages([language]);
+ }, [language]);
+
function copyToClipboard(textToCopy: string) {
copyTextToClipboard(() => Promise.resolve(textToCopy))
.then(() => {
if (addSuccessToast) {
- addSuccessToast(t('SQL Copied!'));
+ addSuccessToast(t('Code Copied!'));
}
})
.catch(() => {
@@ -76,20 +97,34 @@ export default function SyntaxHighlighterCopy({
}
});
}
+
+ const handleCopyClick = (e: React.MouseEvent<HTMLElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.blur();
+ copyToClipboard(children);
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLElement>) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ copyToClipboard(children);
+ }
+ };
+
return (
<SyntaxHighlighterWrapper>
<Icons.CopyOutlined
+ className="copy-button"
tabIndex={0}
role="button"
- onClick={(e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.currentTarget.blur();
- copyToClipboard(children);
- }}
+ aria-label={t('Copy code to clipboard')}
+ onClick={handleCopyClick}
+ onKeyDown={handleKeyDown}
/>
- <SyntaxHighlighter style={github} {...syntaxHighlighterProps}>
+ <CodeSyntaxHighlighter language={language} {...syntaxHighlighterProps}>
{children}
- </SyntaxHighlighter>
+ </CodeSyntaxHighlighter>
</SyntaxHighlighterWrapper>
);
}
diff --git a/superset-frontend/src/pages/QueryHistoryList/index.tsx b/superset-frontend/src/pages/QueryHistoryList/index.tsx
index 012fee6f30..7f37e6dedc 100644
--- a/superset-frontend/src/pages/QueryHistoryList/index.tsx
+++ b/superset-frontend/src/pages/QueryHistoryList/index.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useMemo, useState, useCallback, ReactElement } from 'react';
+import { useMemo, useState, useCallback, ReactElement, useEffect } from 'react';
import { Link, useHistory } from 'react-router-dom';
import {
css,
@@ -43,9 +43,9 @@ import {
type ListViewProps,
type ListViewFilters,
} from 'src/components';
-import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
-import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
-import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
+import CodeSyntaxHighlighter, {
+ preloadLanguages,
+} from '@superset-ui/core/components/CodeSyntaxHighlighter';
import { DATETIME_WITH_TIME_ZONE, TIME_WITH_MS } from 'src/constants';
import { QueryObject, QueryObjectColumns } from 'src/views/CRUD/types';
@@ -64,12 +64,23 @@ const TopAlignedListView = styled(ListView)<ListViewProps<QueryObject>>`
}
`;
-SyntaxHighlighter.registerLanguage('sql', sql);
-const StyledSyntaxHighlighter = styled(SyntaxHighlighter)`
+const StyledCodeSyntaxHighlighter = styled(CodeSyntaxHighlighter)`
height: ${({ theme }) => theme.sizeUnit * 26}px;
overflow: hidden !important; /* needed to override inline styles */
text-overflow: ellipsis;
white-space: nowrap;
+
+ /* Ensure the syntax highlighter content respects the container constraints */
+ & > div {
+ height: 100%;
+ overflow: hidden;
+ }
+
+ pre {
+ height: 100% !important;
+ overflow: hidden !important;
+ margin: 0 !important;
+ }
`;
interface QueryListProps {
@@ -112,6 +123,11 @@ function QueryList({ addDangerToast }: QueryListProps) {
const theme = useTheme();
const history = useHistory();
+ // Preload SQL language since this component will definitely display SQL
+ useEffect(() => {
+ preloadLanguages(['sql']);
+ }, []);
+
const handleQueryPreview = useCallback(
(id: number) => {
SupersetClient.get({
@@ -350,10 +366,23 @@ function QueryList({ addDangerToast }: QueryListProps) {
role="button"
data-test={`open-sql-preview-${id}`}
onClick={() => setQueryCurrentlyPreviewing(original)}
+ onKeyDown={e => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ setQueryCurrentlyPreviewing(original);
+ }
+ }}
+ style={{ cursor: 'pointer' }}
>
- <StyledSyntaxHighlighter language="sql" style={github}>
+ <StyledCodeSyntaxHighlighter
+ language="sql"
+ customStyle={{
+ cursor: 'pointer',
+ userSelect: 'none',
+ }}
+ >
{shortenSQL(original.sql, SQL_PREVIEW_MAX_LINES)}
- </StyledSyntaxHighlighter>
+ </StyledCodeSyntaxHighlighter>
</div>
),
id: QueryObjectColumns.Sql,
@@ -375,7 +404,7 @@ function QueryList({ addDangerToast }: QueryListProps) {
),
},
],
- [],
+ [theme], // Add theme to dependencies since it's used in the columns
);
const filters: ListViewFilters = useMemo(