UNPKG

qlik-script-editor

Version:

A React component library for Qlik Sense script editing with syntax highlighting, autocomplete, and theme support

413 lines (324 loc) • 10.5 kB
# Qlik Script Editor A modern React component library for Qlik Sense script editing with syntax highlighting, autocomplete, and theme support. ## Features - šŸŽÆ **Qlik-specific Editor**: Tailored for Qlik Sense script development - šŸŽØ **Syntax Highlighting**: Color-coded Qlik keywords, functions, and variables - šŸ”® **Smart Autocomplete**: IntelliSense for Qlik functions, keywords, and variables - šŸŒ™ **Theme Support**: Light/dark themes with system preference detection - šŸ“ **Script Validation**: Basic syntax validation and error detection - ⚔ **Single File Bundle**: Optimized 12KB bundle (4KB gzipped) - šŸ“Š **TypeScript**: Full type safety and excellent developer experience - šŸŽŖ **Live Demo**: Try it out in the [example project](./example) ## Installation ```bash npm install qlik-script-editor # or yarn add qlik-script-editor # or pnpm add qlik-script-editor ``` ## Quick Start ```tsx import React, { useState } from 'react' import { QlikScriptEditor, ThemeProvider } from 'qlik-script-editor' import 'qlik-script-editor/lib/style.css' function App() { const [script, setScript] = useState(` LOAD CustomerID, CustomerName, Country, Region FROM data/customers.csv; `.trim()) const variables = ['vDataPath', 'vCurrentYear', 'vMaxDate'] return ( <ThemeProvider defaultTheme="system"> <div style={{ height: '400px', width: '100%' }}> <QlikScriptEditor initialScript={script} onChange={setScript} variables={variables} height="100%" placeholder="Enter your Qlik script here..." /> </div> </ThemeProvider> ) } export default App ``` ## šŸ“¦ Bundle Size This package is optimized for production with a **single file bundle**: - **ESM Bundle**: 12KB (4.2KB gzipped) - **CommonJS Bundle**: 8KB (3.7KB gzipped) - **TypeScript Definitions**: 10KB (single file) - **CSS Styles**: 8KB (2.2KB gzipped) No code splitting or chunk loading - everything you need in one optimized file! ## šŸŽŖ Example Project Check out the complete working example in the [`/example`](./example) directory: ```bash cd example npm install npm start ``` The example includes: - Multiple editor instances - Theme switching - Script validation - Export functionality - Real-time script statistics ## Components ### QlikScriptEditor The main editor component for Qlik script development. **Props:** - `initialScript?: string` - Initial script content - `onChange?: (script: string) => void` - Called when script changes - `variables?: string[]` - Available variables for autocomplete - `theme?: 'light' | 'dark'` - Editor theme (overrides provider) - `height?: string` - Editor height (default: '400px') - `width?: string` - Editor width (default: '100%') - `readOnly?: boolean` - Make editor read-only - `placeholder?: string` - Placeholder text ### ThemeProvider Provides theme context for the editor and manages theme switching. **Props:** - `defaultTheme?: 'light' | 'dark' | 'system'` - Default theme (default: 'system') - `storageKey?: string` - localStorage key for theme persistence - `children: React.ReactNode` - Child components ## Hooks ### useQlikScript Hook for managing Qlik script state with validation and utilities. ```tsx import { useQlikScript } from 'qlik-script-editor' function MyComponent() { const { script, setScript, errors, hasErrors, formatScript, getScriptStats } = useQlikScript({ initialScript: 'LOAD * FROM data.csv;', variables: ['vPath', 'vYear'], enableValidation: true }) const stats = getScriptStats() console.log('Script statistics:', stats) return ( <div> <button onClick={formatScript}>Format Script</button> <p>Lines: {stats.lines}, Errors: {errors.length}</p> </div> ) } ``` ### useTheme Hook for accessing and controlling theme state. ```tsx import { useTheme } from 'qlik-script-editor' function ThemeToggle() { const { theme, actualTheme, setTheme } = useTheme() return ( <button onClick={() => setTheme(actualTheme === 'dark' ? 'light' : 'dark')}> Current theme: {actualTheme} </button> ) } ``` ## Advanced Usage ### Custom Variables and Functions ```tsx import { QlikScriptEditor } from 'qlik-script-editor' function AdvancedEditor() { const customVariables = [ 'vStartDate', 'vEndDate', 'vDataSource', 'vApplicationName' ] return ( <QlikScriptEditor initialScript="LET vToday = Today();" variables={customVariables} onChange={(script) => { // Auto-save or validate script console.log('Script changed:', script) }} /> ) } ``` ### Validation and Error Handling ```tsx import { useQlikScript, QlikScriptEditor } from 'qlik-script-editor' function ValidatedEditor() { const { script, setScript, errors, hasErrors } = useQlikScript({ enableValidation: true, variables: ['vPath', 'vYear'] }) return ( <div> <QlikScriptEditor initialScript={script} onChange={setScript} className={hasErrors ? 'editor-with-errors' : ''} /> {errors.length > 0 && ( <div className="error-panel"> <h3>Script Issues:</h3> {errors.map((error, index) => ( <div key={index} className={`error-${error.type}`}> Line {error.line}: {error.message} </div> ))} </div> )} </div> ) } ``` ### Theme Customization ```tsx import { ThemeProvider } from 'qlik-script-editor' function CustomThemeApp() { return ( <ThemeProvider defaultTheme="dark" storageKey="myapp-theme" > <div className="custom-app"> {/* Your app components */} </div> </ThemeProvider> ) } ``` ## Qlik Language Support The editor includes comprehensive support for Qlik script language features: ### Keywords - **Load Operations**: `LOAD`, `SELECT`, `FROM`, `WHERE`, `GROUP BY` - **Joins**: `LEFT JOIN`, `RIGHT JOIN`, `INNER JOIN`, `OUTER JOIN` - **Control Flow**: `IF`, `THEN`, `ELSE`, `FOR`, `WHILE`, `SWITCH` - **Data Operations**: `CONCATENATE`, `MAPPING`, `QUALIFY`, `DROP`, `STORE` ### Functions - **Aggregation**: `Sum`, `Count`, `Avg`, `Min`, `Max` - **Date/Time**: `Date`, `Today`, `Now`, `Year`, `Month`, `Day` - **String**: `Len`, `Left`, `Right`, `Mid`, `Trim`, `Upper`, `Lower` - **Conditional**: `If`, `Alt`, `Match`, `ApplyMap` ### Features - **Variable Detection**: Recognizes `$(variableName)` syntax - **Function Signatures**: Shows parameter hints for functions - **Syntax Validation**: Highlights common syntax errors - **Code Formatting**: Auto-indentation and structure formatting ## Styling The component uses CSS custom properties for theming. You can customize the appearance: ```css .qlik-script-editor-theme--light { --editor-background: #ffffff; --editor-text: #374151; --editor-keyword: #7c3aed; --editor-string: #059669; --editor-function: #dc2626; } .qlik-script-editor-theme--dark { --editor-background: #1e293b; --editor-text: #e2e8f0; --editor-keyword: #a78bfa; --editor-string: #34d399; --editor-function: #fb7185; } ``` ## Performance & Bundle ### Single File Bundle This package uses **single file bundling** for optimal performance: - No code splitting or lazy loading required - Minimal HTTP requests - Better browser caching - Smaller overall bundle size ### Bundle Analysis ``` qlik-script-editor/lib/ ā”œā”€ā”€ index.js # 12KB (4.2KB gzipped) - ESM bundle ā”œā”€ā”€ index.cjs # 8KB (3.7KB gzipped) - CommonJS ā”œā”€ā”€ index.d.ts # 10KB - All TypeScript definitions └── style.css # 8KB (2.2KB gzipped) - All styles ``` ### Tree Shaking Support Import only what you need: ```tsx // Import specific components (recommended) import { QlikScriptEditor } from 'qlik-script-editor' // Import everything (if needed) import * as QlikEditor from 'qlik-script-editor' ``` ## Browser Support - āœ… Chrome 80+ - āœ… Firefox 75+ - āœ… Safari 13+ - āœ… Edge 80+ ## Troubleshooting ### CSS Import Issues If you encounter issues importing the CSS file, try one of these approaches: **Method 1: Direct path (recommended)** ```tsx import 'qlik-script-editor/lib/style.css' ``` **Method 2: Styles export** ```tsx import 'qlik-script-editor/styles' ``` **Method 3: Manual import in your CSS/SCSS** ```css @import '~qlik-script-editor/lib/style.css'; ``` **Method 4: For Webpack/Vite projects with path issues** ```tsx import QlikStyles from 'qlik-script-editor/lib/style.css?inline' // Then inject the styles manually if needed ``` ### Common Bundle Issues **Tree Shaking**: Make sure your bundler supports ES modules: ```json { "type": "module" } ``` **TypeScript**: Ensure you have the correct TypeScript configuration: ```json { "compilerOptions": { "moduleResolution": "bundler", "allowImportingTsExtensions": true } } ``` ## TypeScript This package is written in TypeScript and includes complete type definitions. All components, hooks, and utilities are fully typed for the best development experience. ```tsx import type { QlikScriptEditorProps, QlikVariable, QlikScriptError, ThemeContextType } from 'qlik-script-editor' ``` ## Contributing Contributions are welcome! Please feel free to submit issues and pull requests. 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## License MIT License - see [LICENSE](LICENSE) file for details. --- **Perfect for Qlik developers who want a modern, feature-rich script editor in their React applications.** ### Built With - āš›ļø **React 18** - Modern React with hooks - šŸ“˜ **TypeScript 5** - Full type safety - ⚔ **Vite 5** - Fast build tooling - šŸŽØ **CSS Custom Properties** - Theme system - šŸ”§ **ESLint** - Code quality - šŸ“¦ **Single Bundle** - Optimized delivery