repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
PhilStainer/philstainer.io
components/CustomLink.tsx
<gh_stars>0 import Link from 'next/link' type Props = { href: string } export const CustomLink = (props: Props): JSX.Element => { const href = props.href const isInternalLink = href.startsWith('/') || href.startsWith('#') if (isInternalLink) { return ( <Link href={href}> <a {...props} /> </Link> ) } return <a target="_blank" rel="noopener noreferrer" {...props} /> }
PhilStainer/philstainer.io
pages/_app.tsx
import '@/styles/globals.css' import {ThemeProvider} from 'next-themes' import {AppProps} from 'next/app' const MyApp = ({Component, pageProps}: AppProps): JSX.Element => { return ( <ThemeProvider attribute="class" disableTransitionOnChange> <Component {...pageProps} /> </ThemeProvider> ) } export default MyApp
PhilStainer/philstainer.io
__tests__/pages/index.test.tsx
jest.mock('next/router', () => ({useRouter: () => ({asPath: ''})})) import {Home} from '@/pages/index' import {render, screen} from '@/__tests__/testUtils' test('should render latest posts', () => { const posts = [ { title: 'blog title 1', summary: 'blog summary 1', publishedAt: '2021-01-01', image: '', slug: 'blog-1', readingTime: { text: '1 min read', }, }, { title: 'blog title 2', summary: 'blog summary 2', publishedAt: '2021-01-02', image: '', slug: 'blog-2', readingTime: { text: '2 min read', }, }, ] render(<Home posts={posts} />) const title = screen.getByRole('heading', {name: /latest posts/i}) const foundPosts = screen.getAllByRole('link', {name: /blog title/i}) expect(title).toBeInTheDocument() expect(foundPosts).toHaveLength(2) }) test('should not render latest posts', () => { render(<Home posts={[]} />) const title = screen.queryByRole('heading', {name: /latest posts/i}) const foundPosts = screen.queryAllByRole('link', {name: /blog title/i}) expect(foundPosts).toHaveLength(0) expect(title).not.toBeInTheDocument() })
PhilStainer/philstainer.io
__tests__/components/Project.test.tsx
import {Project} from '@/components/Project' import {render, screen} from '@/__tests__/testUtils' const config = { title: 'philstainer.io', description: 'My personal site and blog.', href: 'https://philstainer.io', source: 'https://github.com/PhilStainer/philstainer.io', tags: ['next.js', 'tailwind'], } test('should render project', () => { render( <Project title={config.title} description={config.description} href={config.href} source={config.source} tags={config.tags} /> ) const title = screen.getByText(/philstainer\.io/i) const tags = screen.getAllByTestId('tag') const description = screen.getByText(/my personal site and blog\./i) const hrefLink = screen.getByRole('link', {name: /view site/i}) const sourceLink = screen.getByRole('link', {name: /source code/i}) expect(title).toBeInTheDocument() expect(tags).toHaveLength(config.tags.length) expect(description).toBeInTheDocument() expect(hrefLink).toBeInTheDocument() expect(sourceLink).toBeInTheDocument() }) test('should not render source link', () => { render( <Project title={config.title} description={config.description} href={config.href} /> ) const sourceLink = screen.queryByRole('link', {name: /source code/i}) expect(sourceLink).not.toBeInTheDocument() }) test('should not render tags', () => { render( <Project title={config.title} description={config.description} href={config.href} /> ) const tags = screen.queryAllByTestId('tag') expect(tags).toHaveLength(0) })
PhilStainer/philstainer.io
lib/mdx.ts
<filename>lib/mdx.ts<gh_stars>0 import fs from 'fs' import path from 'path' import matter from 'gray-matter' import readingTime from 'reading-time' import {serialize} from 'next-mdx-remote/serialize' import mdxPrism from 'mdx-prism' import {BlogPost} from 'types/BlogPost' import {Post} from 'types/Post' export const root = process.cwd() export const basePath = path.join(root, 'data') export const getFiles = async (dir: string): Promise<string[]> => fs.readdirSync(path.join(basePath, dir)) export const getFileBySlug = async ( dir: string, slug?: string ): Promise<BlogPost> => { const source = slug ? fs.readFileSync(path.join(root, 'data', dir, `${slug}.mdx`), 'utf8') : fs.readFileSync(path.join(root, 'data', `${dir}.mdx`), 'utf8') const { data: {title, publishedAt, summary, image}, content, } = matter(source) const mdxSource = await serialize(content, { mdxOptions: { remarkPlugins: [ require('remark-slug'), require('remark-autolink-headings'), require('remark-code-titles'), ], rehypePlugins: [mdxPrism], }, }) return { mdxSource, frontMatter: { wordCount: content.split(/\s+/gu).length, readingTime: readingTime(content), slug, title, publishedAt, summary, image, }, } } export const getFilesMatter = async (dir: string): Promise<Post[]> => { const files = await getFiles(dir) return files.reduce((posts: Post[], slug: string): Post[] => { const source = fs.readFileSync(path.join(basePath, dir, slug), 'utf-8') const { data: {title, publishedAt, summary, image}, content, } = matter(source) return [ { title, publishedAt, summary, image, slug: slug.replace('.mdx', ''), readingTime: readingTime(content), }, ...posts, ] }, []) }
PhilStainer/philstainer.io
__tests__/components/Layout.test.tsx
<filename>__tests__/components/Layout.test.tsx<gh_stars>0 jest.mock('next/router', () => ({useRouter: () => ({asPath: ''})})) import {Layout} from '@/components/Layout' import {render, screen, within} from '@/__tests__/testUtils' test('should render nav', () => { render(<Layout>Test</Layout>) const navigation = screen.getByRole('navigation') const home = within(navigation).getByRole('link', {name: /home/i}) const blog = within(navigation).getByRole('link', {name: /blog/i}) expect(home).toBeInTheDocument() expect(blog).toBeInTheDocument() }) test('should render children', () => { render(<Layout>Test</Layout>) const children = screen.getByText(/test/i) expect(children).toBeInTheDocument() }) test('should render footer', () => { render(<Layout>Test</Layout>) const name = screen.getByText(/© 2021 <NAME>/i) const twitter = screen.getByRole('link', {name: /my twitter/i}) const github = screen.getByRole('link', {name: /my github/i}) expect(name).toBeInTheDocument() expect(twitter).toBeInTheDocument() expect(github).toBeInTheDocument() })
PhilStainer/philstainer.io
types/Post.ts
export type Post = { title: string publishedAt: string summary: string image: string slug?: string wordCount?: number readingTime: any }
PhilStainer/philstainer.io
components/BlogLayout.tsx
<gh_stars>0 import {Layout} from '@/components/Layout' import format from 'date-fns/format' import parseISO from 'date-fns/parseISO' type Props = { children: JSX.Element frontMatter: any } type GenerateUrl = { slug: string } const editUrl = (slug: GenerateUrl): string => `https://github.com/PhilStainer/philstainer.io/edit/main/data/posts/${slug}.mdx` const discussUrl = (slug: GenerateUrl): string => `https://mobile.twitter.com/search?q=${encodeURIComponent( `https://philStainer.io/blog/${slug}` )}` export const BlogLayout = ({children, frontMatter}: Props): JSX.Element => { return ( <Layout title={`${frontMatter.title} - <NAME>`} description={frontMatter.summary} image={`https://philstainer.io${frontMatter.image}`} date={new Date(frontMatter.publishedAt).toISOString()} type="article" > <article className="flex flex-col justify-center items-start w-full max-w-3xl mx-auto"> <h1 className="font-bold text-3xl md:text-5xl mb-5 text-gray-900 dark:text-gray-100"> {frontMatter.title} </h1> <p className="text-sm font-light text-gray-500 dark:text-gray-400 mb-5"> {format(parseISO(frontMatter.publishedAt), 'MMMM dd, yyyy')} -{' '} {frontMatter.readingTime.text} </p> <div className="prose dark:prose-dark max-w-none w-full"> {children} </div> <div className="w-full flex justify-center text-sm text-gray-600 dark:text-gray-300 mt-10 space-x-1"> <a href={discussUrl(frontMatter.slug)} target="_blank" rel="noopener noreferrer" > {'Discuss on Twitter'} </a> <span>•</span> <a href={editUrl(frontMatter.slug)} target="_blank" rel="noopener noreferrer" > {'Edit on GitHub'} </a> </div> </article> </Layout> ) }
PhilStainer/philstainer.io
components/Nav.tsx
import Link from 'next/link' import {ThemeButton} from './ThemeButton' export const pages = [ {name: 'Home', href: '/'}, {name: 'Blog', href: '/blog'}, ] export const Nav = (): JSX.Element => { return ( <nav className="sticky top-0 z-10 flex items-center justify-between md:justify-end w-full max-w-5xl p-6 mx-auto my-0 bg-white bg-opacity-95 dark:bg-gray-900 dark:bg-opacity-95 select-none md:my-2"> <ThemeButton /> <div className="space-x-2"> {pages.map(({name, href}) => ( <Link key={name} href={href}> <a className="p-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors rounded sm:p-3 focus:outline-none focus:ring-2 focus:ring-gray-800 dark:focus:ring-gray-200"> {name} </a> </Link> ))} </div> </nav> ) }
PhilStainer/philstainer.io
components/Pre.tsx
import {useEffect, useRef, useState} from 'react' import classNames from 'classnames' import {copyToClipboard} from '@/utils/copyToClipboard' type Props = { children: JSX.Element className: string } export const Pre = ({children, className, ...props}: Props): JSX.Element => { const preRef = useRef<HTMLPreElement>(null) const [copied, setCopied] = useState(false) useEffect(() => { const timer = setTimeout(() => setCopied(false), 2000) return () => clearTimeout(timer) }, [copied]) const onClick = async () => { if (preRef.current?.innerText) { copyToClipboard(preRef.current.innerText) setCopied(true) } } return ( <div className="relative group"> <pre {...props} ref={preRef} className={classNames(className, 'focus:outline-none')} > <div className="absolute flex items-center space-x-2 top-0 right-0 m-2"> <span className={classNames('hidden fade-in text-xs text-green-400', { 'group-hover:flex': copied, })} > Copied! </span> <button type="button" aria-label="Copy to Clipboard" onClick={onClick} disabled={copied} className={classNames( 'hidden transition bg-transparent border rounded-md p-2 focus:outline-none group-hover:flex fade-in', { 'border-green-400': copied, 'hover:border-gray-500 dark:border-gray-700 dark:hover:border-gray-400 focus:ring-4 focus:ring-gray-200 focus:ring-opacity-50': !copied, } )} > <svg xmlns="http://www.w3.org/2000/svg" className={classNames('h-4 w-4 pointer-events-none', { 'text-gray-500 dark:text-gray-400': !copied, 'text-green-400': copied, })} fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" className={classNames({block: !copied, hidden: copied})} /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" className={classNames({block: copied, hidden: !copied})} /> </svg> </button> </div> {children} </pre> </div> ) }
PhilStainer/philstainer.io
components/Layout.tsx
<filename>components/Layout.tsx import Head from 'next/head' import {useRouter} from 'next/router' import {ReactNode} from 'react' import {Nav} from '@/components/Nav' import {Footer} from '@/components/Footer' type Props = { children: ReactNode title?: string description?: string image?: string date?: string type?: string } export const Layout = ({children, ...customMeta}: Props): JSX.Element => { const router = useRouter() const meta: any = { title: '<NAME> – Curious Developer and creator.', description: `Full-stack developer and JavaScript enthusiast.`, image: 'https://philstainer.io/static/images/banner.png', type: 'website', ...customMeta, } return ( <div className="bg-white dark:bg-gray-900"> <Head> <title>{meta.title}</title> <meta name="robots" content="follow, index" /> <meta content={meta.description} name="description" /> <meta property="og:url" content={`https://philstainer.io${router.asPath}`} /> <link rel="canonical" href={`https://philstainer.io${router.asPath}`} /> <meta property="og:type" content={meta.type} /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:description" content={meta.description} /> <meta property="og:title" content={meta.title} /> <meta property="og:image" content={meta.image} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@PhilStainer" /> <meta name="twitter:title" content={meta.title} /> <meta name="twitter:description" content={meta.description} /> <meta name="twitter:image" content={meta.image} /> {meta.date && ( <meta property="article:published_time" content={meta.date} /> )} </Head> <Nav /> <main className="flex flex-col justify-center bg-white dark:bg-gray-900 px-6 mt-10 md:mt-20"> {children} <Footer /> </main> </div> ) }
PhilStainer/philstainer.io
__tests__/components/Themebutton.test.tsx
<reponame>PhilStainer/philstainer.io<filename>__tests__/components/Themebutton.test.tsx import {ThemeButton} from '@/components/ThemeButton' import {fireEvent, render, screen} from '@/__tests__/testUtils' import {useTheme} from 'next-themes' jest.mock('next-themes', () => ({ useTheme: jest.fn(() => ({theme: jest.fn(), setTheme: jest.fn()})), })) const useThemeMocked = (useTheme as unknown) as jest.Mock test('should render button with alt', () => { render(<ThemeButton />) const themeButton = screen.getByRole('button', { name: /toggle theme/i, }) expect(themeButton).toBeInTheDocument() }) test('should call setTheme onClick', () => { const setThemeMock = jest.fn() useThemeMocked.mockImplementation(() => ({ theme: jest.fn(), setTheme: setThemeMock, })) render(<ThemeButton />) const themeButton = screen.getByRole('button', { name: /toggle theme/i, }) expect(setThemeMock).toHaveBeenCalledTimes(0) fireEvent.click(themeButton) expect(setThemeMock).toHaveBeenCalledTimes(1) fireEvent.click(themeButton) expect(setThemeMock).toHaveBeenCalledTimes(2) })
PhilStainer/philstainer.io
components/BlogPost.tsx
import Link from 'next/link' import format from 'date-fns/format' import parseISO from 'date-fns/parseISO' import {Post} from 'types/Post' export const BlogPost = ({ title, summary, publishedAt, slug, readingTime, }: Post): JSX.Element => { return ( <Link href={`/blog/${slug}`}> <a className="flex w-full mb-6 md:mb-8"> <div className="space-y-1"> <h4 className="text-xl md:text-2xl tracking-tight text-gray-900 dark:text-gray-100"> <span>{title}</span> </h4> <p className="text-gray-500 dark:text-gray-400"> {format(parseISO(publishedAt), 'MMMM dd, yyyy')} -{' '} {readingTime.text} </p> <p className="text-gray-600 dark:text-gray-300">{summary}</p> </div> </a> </Link> ) }
PhilStainer/philstainer.io
__tests__/pages/blog.test.tsx
<reponame>PhilStainer/philstainer.io<filename>__tests__/pages/blog.test.tsx<gh_stars>0 jest.mock('next/router', () => ({useRouter: () => ({asPath: ''})})) import {render, screen} from '@/__tests__/testUtils' import {Blog} from '@/pages/blog' test('should render blog page', () => { render(<Blog posts={[]} />) const header = screen.getByRole('heading', {name: /blog/i}) const message = screen.getByText(/no posts found\./i) expect(header).toBeInTheDocument() expect(message).toBeInTheDocument() }) test('should sort and render posts', () => { const posts = [ { title: 'blog 1', summary: 'blog summary 1', publishedAt: '2021-01-01', image: '', slug: 'blog-1', readingTime: { text: '1 min read', }, }, { title: 'blog 2', summary: 'blog summary 2', publishedAt: '2021-01-02', image: '', slug: 'blog-2', readingTime: { text: '2 min read', }, }, ] render(<Blog posts={[...posts]} />) const links = screen.getAllByRole('link', {name: /blog summary/i}) expect(links).toHaveLength(2) expect(links[0]).toHaveAttribute('href', `/blog/${posts[1].slug}`) })
PhilStainer/philstainer.io
__tests__/components/BlogPost.test.tsx
import format from 'date-fns/format' import parseISO from 'date-fns/parseISO' import {BlogPost} from '@/components/BlogPost' import {render, screen} from '@/__tests__/testUtils' test('should render blog post', () => { const post = { title: 'blog title', summary: 'blog summary', publishedAt: '2021-01-01', image: '', slug: 'my-blog-name', readingTime: { text: '1 min read', }, } render(<BlogPost {...post} />) const title = screen.getByRole('heading', {name: post.title}) const summary = screen.getByText(post.summary) const formattedDate = format(parseISO(post.publishedAt), 'MMMM dd, yyyy') const details = screen.getByText( `${formattedDate} - ${post.readingTime.text}` ) const link = screen.getByRole('link') expect(title).toBeInTheDocument() expect(summary).toBeInTheDocument() expect(details).toBeInTheDocument() expect(link).toBeInTheDocument() expect(link).toHaveAttribute('href', `/blog/${post.slug}`) })
jenkins-sigaut/ag-grid
community-modules/core/src/ts/widgets/agList.ts
<filename>community-modules/core/src/ts/widgets/agList.ts import { AgAbstractField } from "./agAbstractField"; import { Component } from "./component"; import { PostConstruct } from "../context/context"; import { escapeString } from "../utils/string"; import { addCssClass, removeCssClass } from "../utils/dom"; import { findIndex } from "../utils/array"; import { KeyCode } from '../constants/keyCode'; import { setAriaSelected } from '../utils/aria'; export interface ListOption { value: string; text?: string; } export class AgList extends Component { public static EVENT_ITEM_SELECTED = 'selectedItem'; private static ACTIVE_CLASS = 'ag-active-item'; private options: ListOption[] = []; private itemEls: HTMLElement[] = []; private highlightedEl: HTMLElement; private value: string | null; private displayValue: string | null; constructor(private readonly cssIdentifier = 'default') { super(/* html */`<div class="ag-list ag-${cssIdentifier}-list" role="listbox"></div>`); } @PostConstruct private init(): void { this.addManagedListener(this.getGui(), 'keydown', this.handleKeyDown.bind(this)); } private handleKeyDown(e: KeyboardEvent): void { const key = e.keyCode; switch (key) { case KeyCode.ENTER: if (!this.highlightedEl) { this.setValue(this.getValue()); } else { const pos = this.itemEls.indexOf(this.highlightedEl); this.setValueByIndex(pos); } break; case KeyCode.DOWN: case KeyCode.UP: const isDown = key === KeyCode.DOWN; let itemToHighlight: HTMLElement; e.preventDefault(); if (!this.highlightedEl) { itemToHighlight = this.itemEls[isDown ? 0 : this.itemEls.length - 1]; } else { const currentIdx = this.itemEls.indexOf(this.highlightedEl); let nextPos = currentIdx + (isDown ? 1 : -1); nextPos = Math.min(Math.max(nextPos, 0), this.itemEls.length - 1); itemToHighlight = this.itemEls[nextPos]; } this.highlightItem(itemToHighlight); break; } } public addOptions(listOptions: ListOption[]): this { listOptions.forEach(listOption => this.addOption(listOption)); return this; } public addOption(listOption: ListOption): this { const { value, text } = listOption; const sanitisedText = escapeString(text || value); this.options.push({ value, text: sanitisedText }); this.renderOption(value, sanitisedText); return this; } private renderOption(value: string, text: string): void { const itemEl = document.createElement('div'); itemEl.setAttribute('role', 'option'); addCssClass(itemEl, 'ag-list-item'); addCssClass(itemEl, `ag-${this.cssIdentifier}-list-item`); itemEl.innerHTML = `<span>${text}</span>`; itemEl.tabIndex = -1; this.itemEls.push(itemEl); this.addManagedListener(itemEl, 'mouseover', () => this.highlightItem(itemEl)); this.addManagedListener(itemEl, 'mouseleave', () => this.clearHighlighted()); this.addManagedListener(itemEl, 'click', () => this.setValue(value)); this.getGui().appendChild(itemEl); } public setValue(value?: string, silent?: boolean): this { if (this.value === value) { this.fireItemSelected(); return this; } if (value == null) { this.reset(); return this; } const idx = findIndex(this.options, option => option.value === value); if (idx !== -1) { const option = this.options[idx]; this.value = option.value; this.displayValue = option.text != null ? option.text : option.value; this.highlightItem(this.itemEls[idx]); if (!silent) { this.fireChangeEvent(); } } return this; } public setValueByIndex(idx: number): this { return this.setValue(this.options[idx].value); } public getValue(): string | null { return this.value; } public getDisplayValue(): string | null { return this.displayValue; } public refreshHighlighted(): void { this.clearHighlighted(); const idx = findIndex(this.options, option => option.value === this.value); if (idx !== -1) { this.highlightItem(this.itemEls[idx]); } } private reset(): void { this.value = null; this.displayValue = null; this.clearHighlighted(); this.fireChangeEvent(); } private highlightItem(el: HTMLElement): void { if (!el.offsetParent) { return; } this.clearHighlighted(); this.highlightedEl = el; addCssClass(this.highlightedEl, AgList.ACTIVE_CLASS); setAriaSelected(this.highlightedEl, true); this.highlightedEl.focus(); } private clearHighlighted(): void { if (!this.highlightedEl || !this.highlightedEl.offsetParent) { return; } removeCssClass(this.highlightedEl, AgList.ACTIVE_CLASS); setAriaSelected(this.highlightedEl, false); this.highlightedEl = null; } private fireChangeEvent(): void { this.dispatchEvent({ type: AgAbstractField.EVENT_CHANGED }); this.fireItemSelected(); } private fireItemSelected(): void { this.dispatchEvent({ type: AgList.EVENT_ITEM_SELECTED }); } }
jenkins-sigaut/ag-grid
enterprise-modules/menu/src/menu/menuList.ts
<gh_stars>0 import { ManagedFocusComponent, MenuItemDef, _, KeyCode, } from "@ag-grid-community/core"; import { MenuItemComponent, MenuItemSelectedEvent, MenuItemActivatedEvent } from "./menuItemComponent"; export class MenuList extends ManagedFocusComponent { private menuItems: MenuItemComponent[] = []; private activeMenuItem: MenuItemComponent | null; constructor(private readonly level = 1) { super(/* html */`<div class="ag-menu-list" role="tree"></div>`, true); } protected onTabKeyDown(e: KeyboardEvent) { const parent = this.getParentComponent(); const isManaged = parent && parent instanceof ManagedFocusComponent; if (!isManaged) { e.preventDefault(); } if (e.shiftKey) { this.closeIfIsChild(e); } } protected handleKeyDown(e: KeyboardEvent): void { switch (e.keyCode) { case KeyCode.UP: case KeyCode.RIGHT: case KeyCode.DOWN: case KeyCode.LEFT: e.preventDefault(); this.handleNavKey(e.keyCode); break; case KeyCode.ESCAPE: const topMenu = this.findTopMenu(); if (topMenu) { this.focusController.focusInto(topMenu.getGui()); } break; } } public clearActiveItem(): void { if (this.activeMenuItem) { this.activeMenuItem.deactivate(); this.activeMenuItem = null; } } public addMenuItems(menuItems?: (MenuItemDef | string)[]): void { if (menuItems == null) { return; } menuItems.forEach(menuItemOrString => { if (menuItemOrString === 'separator') { this.addSeparator(); } else if (typeof menuItemOrString === 'string') { console.warn(`ag-Grid: unrecognised menu item ${menuItemOrString}`); } else { this.addItem(menuItemOrString); } }); } public addItem(menuItemDef: MenuItemDef): void { const menuItem = this.createManagedBean(new MenuItemComponent({ ...menuItemDef, isAnotherSubMenuOpen: () => _.some(this.menuItems, m => m.isSubMenuOpen()) })); menuItem.setParentComponent(this); _.setAriaLevel(menuItem.getGui(), this.level); this.menuItems.push(menuItem); this.appendChild(menuItem.getGui()); this.addManagedListener(menuItem, MenuItemComponent.EVENT_MENU_ITEM_SELECTED, (event: MenuItemSelectedEvent) => { this.dispatchEvent(event); }); this.addManagedListener(menuItem, MenuItemComponent.EVENT_MENU_ITEM_ACTIVATED, (event: MenuItemActivatedEvent) => { if (this.activeMenuItem && this.activeMenuItem !== event.menuItem) { this.activeMenuItem.deactivate(); } this.activeMenuItem = event.menuItem; }); } public activateFirstItem(): void { const item = this.menuItems.filter(item => !item.isDisabled())[0]; if (!item) { return; } item.activate(); } private addSeparator() { const separatorHtml = /* html */` <div class="ag-menu-separator" aria-hidden="true"> <div class="ag-menu-separator-part"></div> <div class="ag-menu-separator-part"></div> <div class="ag-menu-separator-part"></div> <div class="ag-menu-separator-part"></div> </div>`; this.appendChild(_.loadTemplate(separatorHtml)); } private findTopMenu(): MenuList | undefined { let parent = this.getParentComponent(); if (!parent && this instanceof MenuList) { return this; } while (true) { const nextParent = parent && parent.getParentComponent && parent.getParentComponent(); if (!nextParent || (!(nextParent instanceof MenuList || nextParent instanceof MenuItemComponent))) { break; } parent = nextParent; } return parent instanceof MenuList ? parent : undefined; } private handleNavKey(key: number): void { switch (key) { case KeyCode.UP: case KeyCode.DOWN: const nextItem = this.findNextItem(key === KeyCode.UP); if (nextItem && nextItem !== this.activeMenuItem) { nextItem.activate(); } return; } const left = this.gridOptionsWrapper.isEnableRtl() ? KeyCode.RIGHT : KeyCode.LEFT; if (key === left) { this.closeIfIsChild(); } else { this.openChild(); } } private closeIfIsChild(e?: KeyboardEvent): void { const parentItem = this.getParentComponent(); if (parentItem && parentItem instanceof MenuItemComponent) { if (e) { e.preventDefault(); } parentItem.closeSubMenu(); parentItem.getGui().focus(); } } private openChild(): void { if (this.activeMenuItem) { this.activeMenuItem.openSubMenu(true); } } private findNextItem(up?: boolean): MenuItemComponent | undefined { const items = this.menuItems.filter(item => !item.isDisabled()); if (!items.length) { return; } if (!this.activeMenuItem) { return up ? _.last(items) : items[0]; } if (up) { items.reverse(); } let nextItem: MenuItemComponent; let foundCurrent = false; for (let i = 0; i < items.length; i++) { const item = items[i]; if (!foundCurrent) { if (item === this.activeMenuItem) { foundCurrent = true; } continue; } nextItem = item; break; } return nextItem || this.activeMenuItem; } protected destroy(): void { this.clearActiveItem(); super.destroy(); } }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/headerRendering/headerGroup/headerGroupComp.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { Component } from "../../widgets/component"; import { IComponent } from "../../interfaces/iComponent"; import { ColumnGroup } from "../../entities/columnGroup"; import { ColumnApi } from "../../columnController/columnApi"; import { GridApi } from "../../gridApi"; export interface IHeaderGroupParams { columnGroup: ColumnGroup; displayName: string; setExpanded: (expanded: boolean) => void; api: GridApi; columnApi: ColumnApi; context: any; } export interface IHeaderGroup { } export interface IHeaderGroupComp extends IHeaderGroup, IComponent<IHeaderGroupParams> { } export declare class HeaderGroupComp extends Component implements IHeaderGroupComp { private columnController; static TEMPLATE: string; private params; private eOpenIcon; private eCloseIcon; constructor(); destroy(): void; init(params: IHeaderGroupParams): void; private setupExpandIcons; private addTouchAndClickListeners; private updateIconVisibility; private addInIcon; private addGroupExpandIcon; private setupLabel; }
jenkins-sigaut/ag-grid
enterprise-modules/charts/src/charts/chartComp/chartTranslator.ts
<filename>enterprise-modules/charts/src/charts/chartComp/chartTranslator.ts import { Bean, BeanStub } from "@ag-grid-community/core"; @Bean("chartTranslator") export class ChartTranslator extends BeanStub { private static DEFAULT_TRANSLATIONS: { [name: string]: string; } = { pivotChartTitle: 'Pivot Chart', rangeChartTitle: 'Range Chart', settings: 'Settings', data: 'Data', format: 'Format', categories: 'Categories', defaultCategory: '(None)', series: 'Series', xyValues: 'X Y Values', paired: 'Paired Mode', axis: 'Axis', navigator: 'Navigator', color: 'Color', thickness: 'Thickness', xType: 'X Type', automatic: 'Automatic', category: 'Category', number: 'Number', time: 'Time', xRotation: 'X Rotation', yRotation: 'Y Rotation', ticks: 'Ticks', width: 'Width', height: 'Height', length: 'Length', padding: 'Padding', spacing: 'Spacing', chart: 'Chart', title: 'Title', titlePlaceholder: 'Chart title - double click to edit', background: 'Background', font: 'Font', top: 'Top', right: 'Right', bottom: 'Bottom', left: 'Left', labels: 'Labels', size: 'Size', shape: 'Shape', minSize: 'Minimum Size', maxSize: 'Maximum Size', legend: 'Legend', position: 'Position', markerSize: 'Marker Size', markerStroke: 'Marker Stroke', markerPadding: 'Marker Padding', itemSpacing: 'Item Spacing', itemPaddingX: 'Item Padding X', itemPaddingY: 'Item Padding Y', layoutHorizontalSpacing: 'Horizontal Spacing', layoutVerticalSpacing: 'Vertical Spacing', strokeWidth: 'Stroke Width', offset: 'Offset', offsets: 'Offsets', tooltips: 'Tooltips', callout: 'Callout', markers: 'Markers', shadow: 'Shadow', blur: 'Blur', xOffset: 'X Offset', yOffset: 'Y Offset', lineWidth: 'Line Width', normal: 'Normal', bold: 'Bold', italic: 'Italic', boldItalic: 'Bold Italic', predefined: 'Predefined', fillOpacity: 'Fill Opacity', strokeOpacity: 'Line Opacity', histogramBinCount: 'Bin count', columnGroup: 'Column', barGroup: 'Bar', pieGroup: 'Pie', lineGroup: 'Line', scatterGroup: 'X Y (Scatter)', areaGroup: 'Area', histogramGroup: 'Histogram', groupedColumnTooltip: 'Grouped', stackedColumnTooltip: 'Stacked', normalizedColumnTooltip: '100% Stacked', groupedBarTooltip: 'Grouped', stackedBarTooltip: 'Stacked', normalizedBarTooltip: '100% Stacked', pieTooltip: 'Pie', doughnutTooltip: 'Doughnut', lineTooltip: 'Line', groupedAreaTooltip: 'Area', stackedAreaTooltip: 'Stacked', normalizedAreaTooltip: '100% Stacked', scatterTooltip: 'Scatter', bubbleTooltip: 'Bubble', histogramTooltip: 'Histogram', noDataToChart: 'No data available to be charted.', pivotChartRequiresPivotMode: 'Pivot Chart requires Pivot Mode enabled.', }; public translate(toTranslate: string): string { const translate = this.gridOptionsWrapper.getLocaleTextFunc(); const defaultTranslation = ChartTranslator.DEFAULT_TRANSLATIONS[toTranslate]; return translate(toTranslate, defaultTranslation); } }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/rendering/row/rowDragComp.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { Component } from "../../widgets/component"; import { RowNode } from "../../entities/rowNode"; import { DragItem } from "../../dragAndDrop/dragAndDropService"; import { Beans } from "../beans"; import { Column } from "../../entities/column"; export interface IRowDragItem extends DragItem { defaultTextValue: string; } export declare class RowDragComp extends Component { private readonly rowNode; private readonly column; private readonly cellValueFn; private readonly beans; constructor(rowNode: RowNode, column: Column, cellValueFn: () => string, beans: Beans); private postConstruct; private getSelectedCount; private checkCompatibility; private addDragSource; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/widgets/agSelect.d.ts
<reponame>jenkins-sigaut/ag-grid // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { AgPickerField } from "./agPickerField"; import { ListOption, AgList } from "./agList"; import { IAgLabel } from './agAbstractLabel'; export declare class AgSelect extends AgPickerField<HTMLSelectElement, string> { protected listComponent: AgList; private hideList; private popupService; constructor(config?: IAgLabel); init(): void; showPicker(): AgList; addOptions(options: ListOption[]): this; addOption(option: ListOption): this; setValue(value: string, silent?: boolean, fromPicker?: boolean): this; protected destroy(): void; }
jenkins-sigaut/ag-grid
community-modules/react/lib/keyGenerator.d.ts
<reponame>jenkins-sigaut/ag-grid // @ag-grid-community/react v25.0.0 export default function generateNewKey(): string;
jenkins-sigaut/ag-grid
enterprise-modules/set-filter/src/setFilter/setValueModel.ts
import { IClientSideRowModel, ColDef, Column, Constants, IRowModel, ISetFilterParams, AgPromise, SetFilterValues, SetFilterValuesFunc, SetFilterValuesFuncParams, TextFilter, TextFormatter, ValueFormatterService, IEventEmitter, _, EventService, RowNode } from '@ag-grid-community/core'; import { ISetFilterLocaleText } from './localeText'; import { ClientSideValuesExtractor } from '../clientSideValueExtractor'; export enum SetFilterModelValuesType { PROVIDED_LIST, PROVIDED_CALLBACK, TAKEN_FROM_GRID_VALUES } export class SetValueModel implements IEventEmitter { public static EVENT_AVAILABLE_VALUES_CHANGED = 'availableValuesChanged'; private readonly localEventService = new EventService(); private readonly formatter: TextFormatter; private readonly clientSideValuesExtractor: ClientSideValuesExtractor; private valuesType: SetFilterModelValuesType; private miniFilterText: string = null; // The lookup for a set is much faster than the lookup for an array, especially when the length of the array is // thousands of records long, so where lookups are important we use a set. /** Values provided to the filter for use. */ private providedValues: SetFilterValues = null; /** Values can be loaded asynchronously, so wait on this promise if you need to ensure values have been loaded. */ private allValuesPromise: AgPromise<(string | null)[]>; /** All possible values for the filter, sorted if required. */ private allValues: string[] = []; /** Remaining values when filters from other columns have been applied. */ private availableValues = new Set<string>(); /** All values that are currently displayed, after the mini-filter has been applied. */ private displayedValues: string[] = []; /** Values that have been selected for this filter. */ private selectedValues = new Set<string>(); constructor( rowModel: IRowModel, valueGetter: (node: RowNode) => any, private readonly filterParams: ISetFilterParams, private readonly colDef: ColDef, private readonly column: Column, private readonly doesRowPassOtherFilters: (node: RowNode) => boolean, private readonly suppressSorting: boolean, private readonly setIsLoading: (loading: boolean) => void, private readonly valueFormatterService: ValueFormatterService, private readonly translate: (key: keyof ISetFilterLocaleText) => string, ) { if (rowModel.getType() === Constants.ROW_MODEL_TYPE_CLIENT_SIDE) { this.clientSideValuesExtractor = new ClientSideValuesExtractor( rowModel as IClientSideRowModel, colDef, valueGetter ); } this.formatter = this.filterParams.textFormatter || TextFilter.DEFAULT_FORMATTER; const { values } = this.filterParams; if (values == null) { this.valuesType = SetFilterModelValuesType.TAKEN_FROM_GRID_VALUES; } else { this.valuesType = Array.isArray(values) ? SetFilterModelValuesType.PROVIDED_LIST : SetFilterModelValuesType.PROVIDED_CALLBACK; this.providedValues = values; } this.updateAllValues().then(values => this.resetSelectionState(values)); } public addEventListener(eventType: string, listener: Function, async?: boolean): void { this.localEventService.addEventListener(eventType, listener, async); } public removeEventListener(eventType: string, listener: Function, async?: boolean): void { this.localEventService.removeEventListener(eventType, listener, async); } /** * Re-fetches the values used in the filter from the value source. * If keepSelection is false, the filter selection will be reset to everything selected, * otherwise the current selection will be preserved. */ public refreshValues(keepSelection = true): AgPromise<void> { const currentModel = this.getModel(); this.updateAllValues(); // ensure model is updated for new values return this.setModel(keepSelection ? currentModel : null); } /** * Overrides the current values being used for the set filter. * If keepSelection is false, the filter selection will be reset to everything selected, * otherwise the current selection will be preserved. */ public overrideValues(valuesToUse: (string | null)[], keepSelection = true): AgPromise<void> { return new AgPromise<void>(resolve => { // wait for any existing values to be populated before overriding this.allValuesPromise.then(() => { this.valuesType = SetFilterModelValuesType.PROVIDED_LIST; this.providedValues = valuesToUse; this.refreshValues(keepSelection).then(() => resolve()); }); }); } public refreshAfterAnyFilterChanged(): AgPromise<void> { return this.showAvailableOnly() ? this.allValuesPromise.then(values => this.updateAvailableValues(values || [])) : AgPromise.resolve(); } private updateAllValues(): AgPromise<(string | null)[]> { this.allValuesPromise = new AgPromise<(string | null)[]>(resolve => { switch (this.valuesType) { case SetFilterModelValuesType.TAKEN_FROM_GRID_VALUES: case SetFilterModelValuesType.PROVIDED_LIST: { const values = this.valuesType === SetFilterModelValuesType.TAKEN_FROM_GRID_VALUES ? this.getValuesFromRows(false) : _.toStrings(this.providedValues as any[]); const sortedValues = this.sortValues(values); this.allValues = sortedValues; resolve(sortedValues); break; } case SetFilterModelValuesType.PROVIDED_CALLBACK: { this.setIsLoading(true); const callback = this.providedValues as SetFilterValuesFunc; const params: SetFilterValuesFuncParams = { success: values => { const processedValues = _.toStrings(values); this.setIsLoading(false); const sortedValues = this.sortValues(processedValues); this.allValues = sortedValues; resolve(sortedValues); }, colDef: this.colDef }; window.setTimeout(() => callback(params), 0); break; } default: throw new Error('Unrecognised valuesType'); } }); this.allValuesPromise.then(values => this.updateAvailableValues(values)); return this.allValuesPromise; } public setValuesType(value: SetFilterModelValuesType) { this.valuesType = value; } public getValuesType(): SetFilterModelValuesType { return this.valuesType; } public isValueAvailable(value: string): boolean { return this.availableValues.has(value); } private showAvailableOnly(): boolean { return this.valuesType === SetFilterModelValuesType.TAKEN_FROM_GRID_VALUES && !this.filterParams.suppressRemoveEntries; } private updateAvailableValues(allValues: string[]): void { const availableValues = this.showAvailableOnly() ? this.sortValues(this.getValuesFromRows(true)) : allValues; this.availableValues = _.convertToSet(availableValues); this.localEventService.dispatchEvent({ type: SetValueModel.EVENT_AVAILABLE_VALUES_CHANGED }); this.updateDisplayedValues(); } private sortValues(values: string[]): string[] { if (this.suppressSorting) { return values; } const comparator = this.filterParams.comparator || this.colDef.comparator as (a: any, b: any) => number || _.defaultComparator; if (!this.filterParams.excelMode || values.indexOf(null) < 0) { return values.sort(comparator); } // ensure the blank value always appears last return _.filter(values, v => v != null).sort(comparator).concat(null); } private getValuesFromRows(removeUnavailableValues = false): string[] { if (!this.clientSideValuesExtractor) { console.error('ag-Grid: Set Filter cannot initialise because you are using a row model that does not contain all rows in the browser. Either use a different filter type, or configure Set Filter such that you provide it with values'); return []; } const predicate = (node: RowNode) => (!removeUnavailableValues || this.doesRowPassOtherFilters(node)); return this.clientSideValuesExtractor.extractUniqueValues(predicate); } /** Sets mini filter value. Returns true if it changed from last value, otherwise false. */ public setMiniFilter(value?: string): boolean { value = _.makeNull(value); if (this.miniFilterText === value) { //do nothing if filter has not changed return false; } this.miniFilterText = value; this.updateDisplayedValues(); return true; } public getMiniFilter(): string { return this.miniFilterText; } private updateDisplayedValues(): void { // if no filter, just display all available values if (this.miniFilterText == null) { this.displayedValues = _.values(this.availableValues); return; } // if filter present, we filter down the list this.displayedValues = []; // to allow for case insensitive searches, upper-case both filter text and value const formattedFilterText = this.formatter(this.miniFilterText).toUpperCase(); const matchesFilter = (valueToCheck: string): boolean => valueToCheck != null && valueToCheck.toUpperCase().indexOf(formattedFilterText) >= 0; this.availableValues.forEach(value => { if (value == null) { if (this.filterParams.excelMode && matchesFilter(this.translate('blanks'))) { this.displayedValues.push(value); } } else { const textFormatterValue = this.formatter(value); // TODO: should this be applying the text formatter *after* the value formatter? const valueFormatterValue = this.valueFormatterService.formatValue( this.column, null, null, textFormatterValue, this.filterParams.valueFormatter, false); if (matchesFilter(textFormatterValue) || matchesFilter(valueFormatterValue)) { this.displayedValues.push(value); } } }); } public getDisplayedValueCount(): number { return this.displayedValues.length; } public getDisplayedValue(index: any): string { return this.displayedValues[index]; } public hasSelections(): boolean { return this.filterParams.defaultToNothingSelected ? this.selectedValues.size > 0 : this.allValues.length !== this.selectedValues.size; } public getUniqueValueCount(): number { return this.allValues.length; } public getUniqueValue(index: any): string | null { return this.allValues[index]; } public getValues(): string[] { return this.allValues.slice(); } public selectAllMatchingMiniFilter(clearExistingSelection = false): void { if (this.miniFilterText == null) { // ensure everything is selected this.selectedValues = _.convertToSet(this.allValues); } else { // ensure everything that matches the mini filter is selected if (clearExistingSelection) { this.selectedValues.clear(); } _.forEach(this.displayedValues, value => this.selectedValues.add(value)); } } public deselectAllMatchingMiniFilter(): void { if (this.miniFilterText == null) { // ensure everything is deselected this.selectedValues.clear(); } else { // ensure everything that matches the mini filter is deselected _.forEach(this.displayedValues, value => this.selectedValues.delete(value)); } } public selectValue(value: string): void { this.selectedValues.add(value); } public deselectValue(value: string): void { if (this.filterParams.excelMode && this.isEverythingVisibleSelected()) { // ensure we're starting from the correct "everything selected" state this.resetSelectionState(this.displayedValues); } this.selectedValues.delete(value); } public isValueSelected(value: string): boolean { return this.selectedValues.has(value); } public isEverythingVisibleSelected(): boolean { return _.filter(this.displayedValues, it => this.isValueSelected(it)).length === this.displayedValues.length; } public isNothingVisibleSelected(): boolean { return _.filter(this.displayedValues, it => this.isValueSelected(it)).length === 0; } public getModel(): string[] | null { return this.hasSelections() ? _.values(this.selectedValues) : null; } public setModel(model: (string | null)[] | null): AgPromise<void> { return this.allValuesPromise.then(values => { if (model == null) { this.resetSelectionState(values); } else { // select all values from the model that exist in the filter this.selectedValues.clear(); const allValues = _.convertToSet(values); _.forEach(model, value => { if (allValues.has(value)) { this.selectedValues.add(value); } }); } }); } private resetSelectionState(values: string[]): void { if (this.filterParams.defaultToNothingSelected) { this.selectedValues.clear(); } else { this.selectedValues = _.convertToSet(values); } } }
jenkins-sigaut/ag-grid
charts-packages/ag-charts-community/dist/es6/chart/chart.d.ts
import { Scene } from "../scene/scene"; import { Series, SeriesNodeDatum } from "./series/series"; import { Padding } from "../util/padding"; import { Shape } from "../scene/shape/shape"; import { Node } from "../scene/node"; import { Rect } from "../scene/shape/rect"; import { Legend } from "./legend"; import { BBox } from "../scene/bbox"; import { Caption } from "../caption"; import { Observable, SourceEvent } from "../util/observable"; import { ChartAxis } from "./chartAxis"; export interface ChartClickEvent extends SourceEvent<Chart> { event: MouseEvent; } export interface TooltipMeta { pageX: number; pageY: number; } export interface TooltipRendererResult { content?: string; title?: string; color?: string; backgroundColor?: string; } export declare function toTooltipHtml(input: string | TooltipRendererResult, defaults?: TooltipRendererResult): string; export declare class ChartTooltip extends Observable { chart: Chart; element: HTMLDivElement; private observer?; enabled: boolean; class: string; delay: number; /** * If `true`, the tooltip will be shown for the marker closest to the mouse cursor. * Only has effect on series with markers. */ tracking: boolean; isVisible(): boolean; updateClass(visible?: boolean, constrained?: boolean): void; private showTimeout; /** * Shows tooltip at the given event's coordinates. * If the `html` parameter is missing, moves the existing tooltip to the new position. */ show(meta: TooltipMeta, html?: string, instantly?: boolean): void; toggle(visible?: boolean): void; constructor(chart: Chart); destroy(): void; } export declare abstract class Chart extends Observable { readonly id: string; readonly scene: Scene; readonly background: Rect; readonly legend: Legend; protected legendAutoPadding: Padding; protected captionAutoPadding: number; static readonly defaultTooltipClass = "ag-chart-tooltip"; private _container; container: HTMLElement | undefined | null; private _data; data: any[]; width: number; height: number; protected _autoSize: boolean; autoSize: boolean; readonly tooltip: ChartTooltip; private _tooltipClass; /** * @deprecated Please use {@link tooltip.class} instead. */ tooltipClass: string; /** * @deprecated Please use {@link tooltip.tracking} instead. */ tooltipTracking: boolean; download(fileName?: string): void; padding: Padding; title?: Caption; subtitle?: Caption; private static tooltipDocuments; protected constructor(document?: Document); destroy(): void; private onLayoutChange; private onLegendPositionChange; private onCaptionChange; protected _element: HTMLElement; readonly element: HTMLElement; abstract readonly seriesRoot: Node; protected _axes: ChartAxis[]; axes: ChartAxis[]; protected attachAxis(axis: ChartAxis): void; protected detachAxis(axis: ChartAxis): void; protected _series: Series[]; series: Series[]; private scheduleLayout; private scheduleData; addSeries(series: Series, before?: Series): boolean; protected initSeries(series: Series): void; protected freeSeries(series: Series): void; addSeriesAfter(series: Series, after?: Series): boolean; removeSeries(series: Series): boolean; removeAllSeries(): void; protected assignSeriesToAxes(): void; protected assignAxesToSeries(force?: boolean): void; private findMatchingAxis; protected _axesChanged: boolean; protected axesChanged: boolean; protected _seriesChanged: boolean; protected seriesChanged: boolean; protected layoutCallbackId: number; /** * Only `true` while we are waiting for the layout to start. * This will be `false` if the layout has already started and is ongoing. */ layoutPending: boolean; private readonly _performLayout; private dataCallbackId; dataPending: boolean; processData(): void; private updateLegend; abstract performLayout(): void; protected positionCaptions(): void; protected positionLegend(): void; protected setupDomListeners(chartElement: HTMLCanvasElement): void; protected cleanupDomListeners(chartElement: HTMLCanvasElement): void; protected seriesRect?: BBox; private pickSeriesNode; lastPick?: { datum: SeriesNodeDatum; node?: Shape; event?: MouseEvent; }; private pickClosestSeriesNodeDatum; private _onMouseDown; private _onMouseUp; private _onMouseMove; private _onMouseOut; private _onClick; protected onMouseMove(event: MouseEvent): void; protected handleTooltip(event: MouseEvent): void; protected onMouseDown(event: MouseEvent): void; protected onMouseUp(event: MouseEvent): void; protected onMouseOut(event: MouseEvent): void; protected onClick(event: MouseEvent): void; private checkSeriesNodeClick; private onSeriesNodeClick; private checkLegendClick; private onSeriesDatumPick; highlightedDatum?: SeriesNodeDatum; highlightDatum(datum: SeriesNodeDatum): void; dehighlightDatum(): void; }
jenkins-sigaut/ag-grid
enterprise-modules/set-filter/src/setFilter/setFloatingFilter.ts
import { Autowired, Component, IFloatingFilter, RefSelector, ValueFormatterService, IFloatingFilterParams, AgInputTextField, _, ColumnController, ISetFilterParams } from '@ag-grid-community/core'; import { SetFilterModel } from './setFilterModel'; import { SetFilter } from './setFilter'; import { SetValueModel } from './setValueModel'; import { DEFAULT_LOCALE_TEXT } from './localeText'; export class SetFloatingFilterComp extends Component implements IFloatingFilter { @RefSelector('eFloatingFilterText') private readonly eFloatingFilterText: AgInputTextField; @Autowired('valueFormatterService') private readonly valueFormatterService: ValueFormatterService; @Autowired('columnController') private readonly columnController: ColumnController; private params: IFloatingFilterParams; private lastKnownModel: SetFilterModel; private availableValuesListenerAdded = false; constructor() { super(/* html */` <div class="ag-floating-filter-input" role="presentation"> <ag-input-text-field ref="eFloatingFilterText"></ag-input-text-field> </div>` ); } // this is a user component, and IComponent has "public destroy()" as part of the interface. // so we need to override destroy() just to make the method public. public destroy(): void { super.destroy(); } public init(params: IFloatingFilterParams): void { const displayName = this.columnController.getDisplayNameForColumn(params.column, 'header', true); const translate = this.gridOptionsWrapper.getLocaleTextFunc(); this.eFloatingFilterText .setDisabled(true) .setInputAriaLabel(`${displayName} ${translate('ariaFilterInput', 'Filter Input')}`) .addGuiEventListener('click', () => params.showParentFilter()); this.params = params; } public onParentModelChanged(parentModel: SetFilterModel): void { this.lastKnownModel = parentModel; this.updateFloatingFilterText(); } private addAvailableValuesListener(): void { this.params.parentFilterInstance((setFilter: SetFilter) => { const setValueModel = setFilter.getValueModel(); // unlike other filters, what we show in the floating filter can be different, even // if another filter changes. this is due to how set filter restricts its values based // on selections in other filters, e.g. if you filter Language to English, then the set filter // on Country will only show English speaking countries. Thus the list of items to show // in the floating filter can change. this.addManagedListener( setValueModel, SetValueModel.EVENT_AVAILABLE_VALUES_CHANGED, () => this.updateFloatingFilterText()); }); this.availableValuesListenerAdded = true; } private updateFloatingFilterText(): void { if (!this.lastKnownModel) { this.eFloatingFilterText.setValue(''); return; } if (!this.availableValuesListenerAdded) { this.addAvailableValuesListener(); } // also supporting old filter model for backwards compatibility const values = this.lastKnownModel instanceof Array ? this.lastKnownModel as string[] : this.lastKnownModel.values; if (!values) { this.eFloatingFilterText.setValue(''); return; } this.params.parentFilterInstance((setFilter: SetFilter) => { const valueModel = setFilter.getValueModel(); const availableValues = _.filter(values, v => valueModel.isValueAvailable(v)); const localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc(); // format all the values, if a formatter is provided const formattedValues = _.map(availableValues, value => { const { column, filterParams } = this.params; const formattedValue = this.valueFormatterService.formatValue( column, null, null, value, (filterParams as ISetFilterParams).valueFormatter, false); const valueToRender = formattedValue != null ? formattedValue : value; return valueToRender == null ? localeTextFunc('blanks', DEFAULT_LOCALE_TEXT['blanks']) : valueToRender; }); const arrayToDisplay = formattedValues.length > 10 ? formattedValues.slice(0, 10).concat('...') : formattedValues; const valuesString = `(${formattedValues.length}) ${arrayToDisplay.join(',')}`; this.eFloatingFilterText.setValue(valuesString); }); } }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/filter/provided/providedFilter.test.ts
import { ProvidedFilter, IProvidedFilterParams } from './providedFilter'; import { ProvidedFilterModel, IDoesFilterPassParams } from '../../interfaces/iFilter'; import { Constants } from '../../constants/constants'; import { IRowModel } from '../../interfaces/iRowModel'; import { GridOptionsWrapper } from '../../gridOptionsWrapper'; import { mock } from '../../test-utils/mock'; import { AgPromise } from '../../utils'; class TestFilter extends ProvidedFilter { private uiModel: ProvidedFilterModel; private modelHasChanged = false; constructor(params: IProvidedFilterParams, rowModelType: string = Constants.ROW_MODEL_TYPE_CLIENT_SIDE) { super('textFilter'); const eGui = mock<HTMLElement>('appendChild'); this.setGui(eGui); const gridOptionsWrapper = mock<GridOptionsWrapper>('getLocaleTextFunc'); gridOptionsWrapper.getLocaleTextFunc.mockReturnValue((_: string, defaultValue: string) => defaultValue); (this as any).gridOptionsWrapper = gridOptionsWrapper; const rowModel = mock<IRowModel>('getType'); rowModel.getType.mockReturnValue(rowModelType); (this as any).rowModel = rowModel; this.setParams(params); } public doesFilterPass(params: IDoesFilterPassParams): boolean { throw new Error('Method not implemented.'); } protected updateUiVisibility(): void { throw new Error('Method not implemented.'); } protected createBodyTemplate(): string { throw new Error('Method not implemented.'); } protected getCssIdentifier(): string { throw new Error('Method not implemented.'); } protected resetUiToDefaults(silent?: boolean): AgPromise<void> { throw new Error('Method not implemented.'); } protected setModelIntoUi(model: ProvidedFilterModel): AgPromise<void> { throw new Error('Method not implemented.'); } protected areModelsEqual(a: ProvidedFilterModel, b: ProvidedFilterModel): boolean { return !this.modelHasChanged; } protected getFilterType(): string { return 'test'; } public getModelFromUi(): ProvidedFilterModel { return this.uiModel; } public setModelHasChanged(hasChanged: boolean): void { this.modelHasChanged = hasChanged; } public apply(afterFloatingFilter = false, afterDataChange = false): void { this.onBtApply(afterFloatingFilter, afterDataChange); } } describe('filterChangedCallback', () => { it('calls filterChangedCallback when filter has changed', () => { const params = mock<IProvidedFilterParams>('filterChangedCallback'); const filter = new TestFilter(params); filter.setModelHasChanged(true); filter.apply(); expect(params.filterChangedCallback).toHaveBeenCalledTimes(1); }); it('does not call filterChangedCallback when filter has not changed', () => { const params = mock<IProvidedFilterParams>('filterChangedCallback'); const filter = new TestFilter(params); filter.apply(); expect(params.filterChangedCallback).not.toHaveBeenCalled(); }); }); describe('closeOnApply', () => { it('closes popup if closeOnApply is true and apply button is present', () => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); params.buttons = ['apply']; params.closeOnApply = true; const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.setModelHasChanged(true); filter.apply(); expect(hidePopup).toHaveBeenCalledTimes(1); }); it('closes popup if closeOnApply is true even if model did not change', () => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); params.buttons = ['apply']; params.closeOnApply = true; const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.apply(); expect(hidePopup).toHaveBeenCalledTimes(1); }); it('does not close popup if apply button is not present', () => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); params.closeOnApply = true; const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.setModelHasChanged(true); filter.apply(); expect(hidePopup).toHaveBeenCalledTimes(0); }); it('does not close popup if from change came from floating filter', () => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); params.buttons = ['apply']; params.closeOnApply = true; const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.setModelHasChanged(true); filter.apply(true); expect(hidePopup).toHaveBeenCalledTimes(0); }); it('does not close popup if from change came from data', () => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); params.buttons = ['apply']; params.closeOnApply = true; const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.setModelHasChanged(true); filter.apply(false, true); expect(hidePopup).toHaveBeenCalledTimes(0); }); it.each([undefined, false])('does not close popup if closeOnApply is %s', value => { const hidePopup = jest.fn(); const params = mock<IProvidedFilterParams>('filterChangedCallback'); // mocking library does not set property correctly for falsy values, so we have to do this instead Object.defineProperty(params, 'closeOnApply', { get: () => value, set: () => { } }); const filter = new TestFilter(params); filter.afterGuiAttached({ container: 'columnMenu', hidePopup }); filter.setModelHasChanged(true); filter.apply(); expect(hidePopup).not.toHaveBeenCalled(); }); });
jenkins-sigaut/ag-grid
grid-packages/ag-grid-react/lib/keyGenerator.d.ts
// ag-grid-react v25.0.0 export default function generateNewKey(): string;
jenkins-sigaut/ag-grid
grid-packages/ag-grid-community/dist/lib/rendering/row/detailRowCompCache.d.ts
import { ICellRendererComp } from "../cellRenderers/iCellRenderer"; import { RowNode } from "../../entities/rowNode"; import { BeanStub } from "../../context/beanStub"; /** * For Master Detail, it is required to keep components between expanding & collapsing parents. * For example a user expands row A (and shows a detail grid for this row), then when row A * is closed, we want to keep the detail grid, so next time row A is expanded the detail grid * is showed with it's context intact, eg if user sorted in the detail grid, that sort should * still be applied after the detail grid is shown for the second time. */ export declare class DetailRowCompCache extends BeanStub { private cacheItems; private maxCacheSize; private active; private postConstruct; addOrDestroy(rowNode: RowNode, pinned: string, comp: ICellRendererComp): void; private getCacheItem; private stampCacheItem; private destroyFullWidthRow; private purgeCache; get(rowNode: RowNode, pinned: string): ICellRendererComp; protected destroy(): void; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/filter/filterLocaleText.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> export interface IFilterLocaleText { applyFilter: string; clearFilter: string; resetFilter: string; cancelFilter: string; filterOoo: string; empty: string; equals: string; notEqual: string; lessThan: string; greaterThan: string; inRange: string; inRangeStart: string; inRangeEnd: string; lessThanOrEqual: string; greaterThanOrEqual: string; contains: string; notContains: string; startsWith: string; endsWith: string; andCondition: string; orCondition: string; dateFormatOoo: string; } export interface IFilterTitleLocaleText { textFilter: string; numberFilter: string; dateFilter: string; setFilter: string; } export declare const DEFAULT_FILTER_LOCALE_TEXT: IFilterLocaleText & IFilterTitleLocaleText;
jenkins-sigaut/ag-grid
community-modules/client-side-row-model/dist/es6/clientSideRowModel/sortService.d.ts
<filename>community-modules/client-side-row-model/dist/es6/clientSideRowModel/sortService.d.ts import { ChangedPath, Column, RowNode, BeanStub } from "@ag-grid-community/core"; export interface SortOption { inverter: number; column: Column; } export interface SortedRowNode { currentPos: number; rowNode: RowNode; } export declare class SortService extends BeanStub { private sortController; private columnController; private rowNodeSorter; private postSortFunc; init(): void; sort(sortOptions: SortOption[], sortActive: boolean, deltaSort: boolean, dirtyLeafNodes: { [nodeId: string]: boolean; }, changedPath: ChangedPath, noAggregations: boolean): void; private doFullSort; private mapNodeToSortedNode; private doDeltaSort; private mergeSortedArrays; private compareRowNodes; private getValue; private updateChildIndexes; private updateGroupDataForHiddenOpenParents; private pullDownGroupDataForHideOpenParents; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/focusController.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { BeanStub } from "./context/beanStub"; import { Column } from "./entities/column"; import { CellPosition } from "./entities/cellPosition"; import { RowNode } from "./entities/rowNode"; import { AbstractHeaderWrapper } from "./headerRendering/header/abstractHeaderWrapper"; import { HeaderPosition } from "./headerRendering/header/headerPosition"; import { ColumnGroup } from "./entities/columnGroup"; import { GridCore } from "./gridCore"; export declare class FocusController extends BeanStub { private readonly columnController; private readonly headerNavigationService; private readonly columnApi; private readonly gridApi; private readonly rowRenderer; private readonly rowPositionUtils; private readonly rangeController; private gridCore; private focusedCellPosition; private focusedHeaderPosition; private static keyboardModeActive; private static instancesMonitored; /** * Adds a gridCore to the list of the gridCores monitoring Keyboard Mode * in a specific HTMLDocument. * * @param doc {Document} - The Document containing the gridCore. * @param gridCore {GridCore} - The GridCore to be monitored. */ private static addKeyboardModeEvents; /** * Removes a gridCore from the list of the gridCores monitoring Keyboard Mode * in a specific HTMLDocument. * * @param doc {Document} - The Document containing the gridCore. * @param gridCore {GridCore} - The GridCore to be removed. */ private static removeKeyboardModeEvents; /** * This method will be called by `keydown` and `mousedown` events on all Documents monitoring * KeyboardMode. It will then fire a KEYBOARD_FOCUS, MOUSE_FOCUS on each gridCore present in * the Document allowing each gridCore to maintain a state for KeyboardMode. * * @param event {KeyboardEvent | MouseEvent | TouchEvent} - The event triggered. */ private static toggleKeyboardMode; private init; registerGridCore(gridCore: GridCore): void; unregisterGridCore(gridCore: GridCore): void; onColumnEverythingChanged(): void; isKeyboardMode(): boolean; getFocusCellToUseAfterRefresh(): CellPosition | null; private getGridCellForDomElement; clearFocusedCell(): void; getFocusedCell(): CellPosition; setFocusedCell(rowIndex: number, colKey: string | Column, floating: string | undefined, forceBrowserFocus?: boolean): void; isCellFocused(cellPosition: CellPosition): boolean; isRowNodeFocused(rowNode: RowNode): boolean; isHeaderWrapperFocused(headerWrapper: AbstractHeaderWrapper): boolean; clearFocusedHeader(): void; getFocusedHeader(): HeaderPosition; setFocusedHeader(headerRowIndex: number, column: ColumnGroup | Column): void; focusHeaderPosition(headerPosition: HeaderPosition, direction?: 'Before' | 'After', fromTab?: boolean, allowUserOverride?: boolean, event?: KeyboardEvent): boolean; isAnyCellFocused(): boolean; isRowFocused(rowIndex: number, floating: string): boolean; findFocusableElements(rootNode: HTMLElement, exclude?: string, onlyUnmanaged?: boolean): HTMLElement[]; focusInto(rootNode: HTMLElement, up?: boolean, onlyUnmanaged?: boolean): boolean; findNextFocusableElement(rootNode: HTMLElement, onlyManaged?: boolean, backwards?: boolean): HTMLElement; isFocusUnderManagedComponent(rootNode: HTMLElement): boolean; findTabbableParent(node: HTMLElement, limit?: number): HTMLElement; private onCellFocused; focusGridView(column?: Column, backwards?: boolean): boolean; focusNextGridCoreContainer(backwards: boolean): boolean; }
jenkins-sigaut/ag-grid
enterprise-modules/server-side-row-model/dist/es6/serverSideRowModel/blocks/partialStoreBlock.d.ts
import { LoadSuccessParams, NumberSequence, RowBounds, RowNode, RowNodeBlock, ServerSideStoreParams } from "@ag-grid-community/core"; import { SSRMParams } from "../serverSideRowModel"; import { PartialStore } from "../stores/partialStore"; export declare class PartialStoreBlock extends RowNodeBlock { private rowRenderer; private columnController; private valueService; private columnApi; private gridApi; private cacheUtils; private blockUtils; private nodeManager; private rowNodeBlockLoader; private logger; private readonly ssrmParams; private readonly storeParams; private readonly startRow; private readonly level; private readonly groupLevel; private readonly leafGroup; private readonly parentStore; private readonly parentRowNode; private defaultRowHeight; private usingTreeData; private usingMasterDetail; private lastAccessed; private allNodesMap; rowNodes: RowNode[]; private displayIndexStart; private displayIndexEnd; private blockTopPx; private blockHeightPx; private groupField; private rowGroupColumn; private nodeIdPrefix; constructor(blockNumber: number, parentRowNode: RowNode, ssrmParams: SSRMParams, storeParams: ServerSideStoreParams, parentStore: PartialStore); protected postConstruct(): void; isDisplayIndexInBlock(displayIndex: number): boolean; isBlockBefore(displayIndex: number): boolean; getDisplayIndexStart(): number | undefined; getDisplayIndexEnd(): number | undefined; getBlockHeightPx(): number; getBlockTopPx(): number; isGroupLevel(): boolean | undefined; getGroupField(): string; private prefixId; getBlockStateJson(): { id: string; state: any; }; isAnyNodeOpen(): boolean; private forEachNode; forEachNodeDeep(callback: (rowNode: RowNode, index: number) => void, sequence?: NumberSequence): void; forEachNodeShallow(callback: (rowNode: RowNode) => void, sequence?: NumberSequence): void; getLastAccessed(): number; getRowUsingLocalIndex(rowIndex: number): RowNode; private touchLastAccessed; protected processServerFail(): void; retryLoads(): void; protected processServerResult(params: LoadSuccessParams): void; setData(rows?: any[], failedLoad?: boolean): void; removeDuplicateNode(id: string): void; refresh(): void; private destroyRowNodes; private setBeans; getRowUsingDisplayIndex(displayRowIndex: number): RowNode | null; protected loadFromDatasource(): void; isPixelInRange(pixel: number): boolean; getRowBounds(index: number): RowBounds | undefined; getRowIndexAtPixel(pixel: number): number | undefined; clearDisplayIndexes(): void; setDisplayIndexes(displayIndexSeq: NumberSequence, nextRowTop: { value: number; }): void; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/interfaces/iFiltersToolPanel.d.ts
<gh_stars>0 // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { ColDef } from "../entities/colDef"; export interface IFiltersToolPanel { setFilterLayout(colDefs: ColDef[]): void; expandFilterGroups(groupIds?: string[]): void; collapseFilterGroups(groupIds?: string[]): void; expandFilters(colIds?: string[]): void; collapseFilters(colIds?: string[]): void; syncLayoutWithGrid(): void; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/rowNodes/rowNodeSorter.d.ts
<reponame>jenkins-sigaut/ag-grid // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { Column } from "../entities/column"; import { RowNode } from "../entities/rowNode"; export interface SortOption { sort: string; column: Column; } export interface SortedRowNode { currentPos: number; rowNode: RowNode; } export declare class RowNodeSorter { private gridOptionsWrapper; private valueService; doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[]; compareRowNodes(sortOptions: SortOption[], sortedNodeA: SortedRowNode, sortedNodeB: SortedRowNode): number; private getValue; }
jenkins-sigaut/ag-grid
enterprise-modules/multi-filter/dist/es6/multiFilter/multiFilter.d.ts
<filename>enterprise-modules/multi-filter/dist/es6/multiFilter/multiFilter.d.ts import { AgPromise, ProvidedFilterModel, IDoesFilterPassParams, IAfterGuiAttachedParams, IFilterComp, IFilterDef, IFilterParams, ManagedFocusComponent } from '@ag-grid-community/core'; export interface IMultiFilterDef extends IFilterDef { display?: 'inline' | 'accordion' | 'subMenu'; title?: string; } export interface IMultiFilterParams extends IFilterParams { filters?: IMultiFilterDef[]; } export interface IMultiFilterModel { filterType: string; filterModels: any[]; } export declare class MultiFilter extends ManagedFocusComponent implements IFilterComp { private readonly filterManager; private readonly userComponentFactory; private params; private filterDefs; private filters; private guiDestroyFuncs; private column; private filterChangedCallback; private lastOpenedInContainer?; private activeFilterIndices; private lastActivatedMenuItem; constructor(); static getFilterDefs(params: IMultiFilterParams): IMultiFilterDef[]; init(params: IMultiFilterParams): AgPromise<void>; private refreshGui; private getFilterTitle; private destroyChildren; private insertFilterMenu; private insertFilterGroup; isFilterActive(): boolean; getLastActiveFilterIndex(): number | null; doesFilterPass(params: IDoesFilterPassParams, filterToSkip?: IFilterComp): boolean; private getFilterType; getModelFromUi(): IMultiFilterModel | null; getModel(): ProvidedFilterModel | null; setModel(model: IMultiFilterModel | null): AgPromise<void>; getChildFilterInstance(index: number): IFilterComp; afterGuiAttached(params?: IAfterGuiAttachedParams): void; onAnyFilterChanged(): void; onNewRowsLoaded(): void; destroy(): void; private executeFunctionIfExists; private createFilter; private filterChanged; protected onFocusIn(e: FocusEvent): void; }
jenkins-sigaut/ag-grid
community-modules/client-side-row-model/dist/es6/clientSideRowModel/immutableService.d.ts
<filename>community-modules/client-side-row-model/dist/es6/clientSideRowModel/immutableService.d.ts<gh_stars>0 import { IImmutableService, RowDataTransaction, BeanStub } from "@ag-grid-community/core"; export declare class ImmutableService extends BeanStub implements IImmutableService { private rowModel; private clientSideRowModel; private postConstruct; createTransactionForRowData(data: any[]): ([RowDataTransaction, { [id: string]: number; }]) | undefined; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/interfaces/serverSideTransaction.d.ts
<filename>community-modules/core/dist/es6/interfaces/serverSideTransaction.d.ts // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { RowNode } from "../entities/rowNode"; export interface ServerSideTransaction { route?: string[]; addIndex?: number; add?: any[]; remove?: any[]; update?: any[]; } export interface ServerSideTransactionResult { status: ServerSideTransactionResultStatus; add?: RowNode[]; remove?: RowNode[]; update?: RowNode[]; } export declare enum ServerSideTransactionResultStatus { StoreNotFound = "StoreNotFound", StoreLoading = "StoreLoading", StoreWaitingToLoad = "StoreWaitingToLoad", StoreLoadingFailed = "StoreLoadingFailed", StoreWrongType = "StoreWrongType", Applied = "Applied", Cancelled = "Cancelled" }
jenkins-sigaut/ag-grid
enterprise-modules/column-tool-panel/dist/es6/columnToolPanel/toolPanelColumnComp.d.ts
<reponame>jenkins-sigaut/ag-grid import { Column, Component, ITooltipParams } from "@ag-grid-community/core"; export declare class ToolPanelColumnComp extends Component { private readonly column; private readonly columnDept; private readonly allowDragging; private readonly groupsExist; private readonly focusWrapper; private static TEMPLATE; private columnController; private dragAndDropService; private modelItemUtils; private eLabel; private cbSelect; private eDragHandle; private displayName; private processingColumnStateChange; constructor(column: Column, columnDept: number, allowDragging: boolean, groupsExist: boolean, focusWrapper: HTMLElement); init(): void; private setupTooltip; getTooltipParams(): ITooltipParams; protected handleKeyDown(e: KeyboardEvent): void; private onLabelClicked; private onCheckboxChanged; private onChangeCommon; private refreshAriaLabel; private setupDragging; private createDragItem; private onColumnStateChanged; getDisplayName(): string | null; onSelectAllChanged(value: boolean): void; isSelected(): boolean; isSelectable(): boolean; isExpandable(): boolean; setExpanded(value: boolean): void; }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/filter/provided/providedFilter.ts
import { ProvidedFilterModel, IDoesFilterPassParams, IFilterComp, IFilterParams } from '../../interfaces/iFilter'; import { Autowired, PostConstruct } from '../../context/context'; import { IRowModel } from '../../interfaces/iRowModel'; import { Constants } from '../../constants/constants'; import { IAfterGuiAttachedParams } from '../../interfaces/iAfterGuiAttachedParams'; import { loadTemplate, addCssClass, setDisabled } from '../../utils/dom'; import { debounce } from '../../utils/function'; import { AgPromise } from '../../utils/promise'; import { PopupEventParams } from '../../widgets/popupService'; import { IFilterLocaleText, IFilterTitleLocaleText, DEFAULT_FILTER_LOCALE_TEXT } from '../filterLocaleText'; import { ManagedFocusComponent } from '../../widgets/managedFocusComponent'; import { convertToSet } from '../../utils/set'; type FilterButtonType = 'apply' | 'clear' | 'reset' | 'cancel'; export interface IProvidedFilterParams extends IFilterParams { /** @deprecated */ clearButton?: boolean; /** @deprecated */ resetButton?: boolean; /** @deprecated */ applyButton?: boolean; buttons?: FilterButtonType[]; closeOnApply?: boolean; /** @deprecated */ newRowsAction?: string; debounceMs?: number; } /** * Contains common logic to all provided filters (apply button, clear button, etc). * All the filters that come with ag-Grid extend this class. User filters do not * extend this class. */ export abstract class ProvidedFilter extends ManagedFocusComponent implements IFilterComp { private newRowsActionKeep: boolean; // each level in the hierarchy will save params with the appropriate type for that level. private providedFilterParams: IProvidedFilterParams; private applyActive = false; private hidePopup: (params: PopupEventParams) => void = null; // a debounce of the onBtApply method private onBtApplyDebounce: () => void; // after the user hits 'apply' the model gets copied to here. this is then the model that we use for // all filtering. so if user changes UI but doesn't hit apply, then the UI will be out of sync with this model. // this is what we want, as the UI should only become the 'active' filter once it's applied. when apply is // inactive, this model will be in sync (following the debounce ms). if the UI is not a valid filter // (eg the value is missing so nothing to filter on, or for set filter all checkboxes are checked so filter // not active) then this appliedModel will be null/undefined. private appliedModel: ProvidedFilterModel | null = null; @Autowired('rowModel') protected readonly rowModel: IRowModel; constructor(private readonly filterNameKey: keyof IFilterTitleLocaleText) { super(); } public abstract doesFilterPass(params: IDoesFilterPassParams): boolean; protected abstract updateUiVisibility(): void; protected abstract createBodyTemplate(): string; protected abstract getCssIdentifier(): string; protected abstract resetUiToDefaults(silent?: boolean): AgPromise<void>; protected abstract setModelIntoUi(model: ProvidedFilterModel): AgPromise<void>; protected abstract areModelsEqual(a: ProvidedFilterModel, b: ProvidedFilterModel): boolean; /** Used to get the filter type for filter models. */ protected abstract getFilterType(): string; public abstract getModelFromUi(): ProvidedFilterModel | null; public getFilterTitle(): string { return this.translate(this.filterNameKey); } /** @deprecated */ public onFilterChanged(): void { console.warn(`ag-Grid: you should not call onFilterChanged() directly on the filter, please call gridApi.onFilterChanged() instead. onFilterChanged is not part of the exposed filter interface (it was a method that existed on an old version of the filters that was not intended for public use.`); this.providedFilterParams.filterChangedCallback(); } public isFilterActive(): boolean { // filter is active if we have a valid applied model return !!this.appliedModel; } @PostConstruct protected postConstruct(): void { this.resetTemplate(); // do this first to create the DOM super.postConstruct(); } protected resetTemplate(paramsMap?: any) { const templateString = /* html */` <div class="ag-filter-wrapper"> <div class="ag-filter-body-wrapper ag-${this.getCssIdentifier()}-body-wrapper"> ${this.createBodyTemplate()} </div> </div>`; this.setTemplate(templateString, paramsMap); } public init(params: IProvidedFilterParams): void { this.setParams(params); this.resetUiToDefaults(true).then(() => { this.updateUiVisibility(); this.setupOnBtApplyDebounce(); }); } protected setParams(params: IProvidedFilterParams): void { ProvidedFilter.checkForDeprecatedParams(params); this.providedFilterParams = params; if (params.newRowsAction === 'keep') { this.newRowsActionKeep = true; } else if (params.newRowsAction === 'clear') { this.newRowsActionKeep = false; } else { // the default for SSRM and IRM is 'keep', for CSRM and VRM the default is 'clear' const modelsForKeep = [Constants.ROW_MODEL_TYPE_SERVER_SIDE, Constants.ROW_MODEL_TYPE_INFINITE]; this.newRowsActionKeep = modelsForKeep.indexOf(this.rowModel.getType()) >= 0; } this.applyActive = ProvidedFilter.isUseApplyButton(params); this.createButtonPanel(); } private createButtonPanel(): void { const { buttons } = this.providedFilterParams; if (!buttons || buttons.length < 1) { return; } const eButtonsPanel = document.createElement('div'); addCssClass(eButtonsPanel, 'ag-filter-apply-panel'); const addButton = (type: FilterButtonType): void => { let text; let clickListener: (e?: Event) => void; switch (type) { case 'apply': text = this.translate('applyFilter'); clickListener = (e) => this.onBtApply(false, false, e); break; case 'clear': text = this.translate('clearFilter'); clickListener = () => this.onBtClear(); break; case 'reset': text = this.translate('resetFilter'); clickListener = () => this.onBtReset(); break; case 'cancel': text = this.translate('cancelFilter'); clickListener = (e) => { this.onBtCancel(e); }; break; default: console.warn('Unknown button type specified'); return; } const button = loadTemplate(/* html */ `<button type="button" ref="${type}FilterButton" class="ag-standard-button ag-filter-apply-panel-button" >${text} </button>` ); eButtonsPanel.appendChild(button); this.addManagedListener(button, 'click', clickListener); }; convertToSet(buttons).forEach(type => addButton(type)); this.getGui().appendChild(eButtonsPanel); } private static checkForDeprecatedParams(params: IProvidedFilterParams): void { const buttons = params.buttons || []; if (buttons.length > 0) { return; } const { applyButton, resetButton, clearButton } = params; if (clearButton) { console.warn('ag-Grid: as of ag-Grid v23.2, filterParams.clearButton is deprecated. Please use filterParams.buttons instead'); buttons.push('clear'); } if (resetButton) { console.warn('ag-Grid: as of ag-Grid v23.2, filterParams.resetButton is deprecated. Please use filterParams.buttons instead'); buttons.push('reset'); } if (applyButton) { console.warn('ag-Grid: as of ag-Grid v23.2, filterParams.applyButton is deprecated. Please use filterParams.buttons instead'); buttons.push('apply'); } if ((params as any).apply) { console.warn('ag-Grid: as of ag-Grid v21, filterParams.apply is deprecated. Please use filterParams.buttons instead'); buttons.push('apply'); } params.buttons = buttons; } // subclasses can override this to provide alternative debounce defaults protected getDefaultDebounceMs(): number { return 0; } private setupOnBtApplyDebounce(): void { const debounceMs = ProvidedFilter.getDebounceMs(this.providedFilterParams, this.getDefaultDebounceMs()); this.onBtApplyDebounce = debounce(this.onBtApply.bind(this), debounceMs); } public getModel(): ProvidedFilterModel { return this.appliedModel; } public setModel(model: ProvidedFilterModel): AgPromise<void> { const promise = model ? this.setModelIntoUi(model) : this.resetUiToDefaults(); return promise.then(() => { this.updateUiVisibility(); // we set the model from the GUI, rather than the provided model, // so the model is consistent, e.g. handling of null/undefined will be the same, // or if model is case insensitive, then casing is removed. this.applyModel(); }); } private onBtCancel(e: Event): void { this.setModelIntoUi(this.getModel()).then(() => { this.onUiChanged(false, 'prevent'); if (this.providedFilterParams.closeOnApply) { this.close(e); } }); } private onBtClear(): void { this.resetUiToDefaults().then(() => this.onUiChanged()); } private onBtReset(): void { this.onBtClear(); this.onBtApply(); } /** * Applies changes made in the UI to the filter, and returns true if the model has changed. */ public applyModel(): boolean { const newModel = this.getModelFromUi(); if (!this.isModelValid(newModel)) { return false; } const previousModel = this.appliedModel; this.appliedModel = newModel; // models can be same if user pasted same content into text field, or maybe just changed the case // and it's a case insensitive filter return !this.areModelsEqual(previousModel, newModel); } protected isModelValid(model: ProvidedFilterModel): boolean { return true; } protected onBtApply(afterFloatingFilter = false, afterDataChange = false, e?: Event): void { if (this.applyModel()) { // the floating filter uses 'afterFloatingFilter' info, so it doesn't refresh after filter changed if change // came from floating filter this.providedFilterParams.filterChangedCallback({ afterFloatingFilter, afterDataChange }); } const { closeOnApply } = this.providedFilterParams; // only close if an apply button is visible, otherwise we'd be closing every time a change was made! if (closeOnApply && this.applyActive && !afterFloatingFilter && !afterDataChange) { this.close(e); } } public onNewRowsLoaded(): void { if (!this.newRowsActionKeep) { this.resetUiToDefaults().then(() => this.appliedModel = null); } } public close(e?: Event): void { if (!this.hidePopup) { return; } const keyboardEvent = e as KeyboardEvent; const key = keyboardEvent && keyboardEvent.key; let params: PopupEventParams; if (key === 'Enter' || key === 'Space') { params = { keyboardEvent }; } this.hidePopup(params); this.hidePopup = null; } // called by set filter protected isNewRowsActionKeep(): boolean { return this.newRowsActionKeep; } /** * By default, if the change came from a floating filter it will be applied immediately, otherwise if there is no * apply button it will be applied after a debounce, otherwise it will not be applied at all. This behaviour can * be adjusted by using the apply parameter. */ protected onUiChanged(fromFloatingFilter = false, apply?: 'immediately' | 'debounce' | 'prevent'): void { this.updateUiVisibility(); this.providedFilterParams.filterModifiedCallback(); if (this.applyActive) { const isValid = this.isModelValid(this.getModelFromUi()); setDisabled(this.getRefElement('applyFilterButton'), !isValid); } if ((fromFloatingFilter && !apply) || apply === 'immediately') { this.onBtApply(fromFloatingFilter); } else if ((!this.applyActive && !apply) || apply === 'debounce') { this.onBtApplyDebounce(); } } public afterGuiAttached(params?: IAfterGuiAttachedParams): void { if (params == null) { return; } this.hidePopup = params.hidePopup; } // static, as used by floating filter also public static getDebounceMs(params: IProvidedFilterParams, debounceDefault: number): number { if (ProvidedFilter.isUseApplyButton(params)) { if (params.debounceMs != null) { console.warn('ag-Grid: debounceMs is ignored when apply button is present'); } return 0; } return params.debounceMs != null ? params.debounceMs : debounceDefault; } // static, as used by floating filter also public static isUseApplyButton(params: IProvidedFilterParams): boolean { ProvidedFilter.checkForDeprecatedParams(params); return params.buttons && params.buttons.indexOf('apply') >= 0; } public destroy(): void { this.hidePopup = null; super.destroy(); } protected translate(key: keyof IFilterLocaleText | keyof IFilterTitleLocaleText): string { const translate = this.gridOptionsWrapper.getLocaleTextFunc(); return translate(key, DEFAULT_FILTER_LOCALE_TEXT[key]); } }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/filter/provided/number/numberFilter.ts
<reponame>jenkins-sigaut/ag-grid<filename>community-modules/core/src/ts/filter/provided/number/numberFilter.ts import { RefSelector } from '../../../widgets/componentAnnotations'; import { AgPromise } from '../../../utils'; import { SimpleFilter, ConditionPosition, ISimpleFilterModel } from '../simpleFilter'; import { ScalarFilter, Comparator, IScalarFilterParams } from '../scalarFilter'; import { IAfterGuiAttachedParams } from '../../../interfaces/iAfterGuiAttachedParams'; import { makeNull } from '../../../utils/generic'; import { setDisplayed } from '../../../utils/dom'; import { AgInputTextField } from '../../../widgets/agInputTextField'; import { isBrowserChrome, isBrowserEdge } from '../../../utils/browser'; export interface NumberFilterModel extends ISimpleFilterModel { filter?: number; filterTo?: number; } export interface INumberFilterParams extends IScalarFilterParams { allowedCharPattern?: string; numberParser?: (text: string) => number; } export class NumberFilter extends ScalarFilter<NumberFilterModel, number> { public static DEFAULT_FILTER_OPTIONS = [ ScalarFilter.EQUALS, ScalarFilter.NOT_EQUAL, ScalarFilter.LESS_THAN, ScalarFilter.LESS_THAN_OR_EQUAL, ScalarFilter.GREATER_THAN, ScalarFilter.GREATER_THAN_OR_EQUAL, ScalarFilter.IN_RANGE ]; @RefSelector('eValueFrom1') private readonly eValueFrom1: AgInputTextField; @RefSelector('eValueTo1') private readonly eValueTo1: AgInputTextField; @RefSelector('eValueFrom2') private readonly eValueFrom2: AgInputTextField; @RefSelector('eValueTo2') private readonly eValueTo2: AgInputTextField; private numberFilterParams: INumberFilterParams; constructor() { super('numberFilter'); } protected mapRangeFromModel(filterModel: NumberFilterModel): { from: number, to: number; } { return { from: filterModel.filter, to: filterModel.filterTo }; } protected getDefaultDebounceMs(): number { return 500; } protected resetUiToDefaults(silent?: boolean): AgPromise<void> { return super.resetUiToDefaults(silent).then(() => { const fields = [this.eValueFrom1, this.eValueFrom2, this.eValueTo1, this.eValueTo2]; fields.forEach(field => field.setValue(null, silent)); this.resetPlaceholder(); }); } protected setConditionIntoUi(model: NumberFilterModel, position: ConditionPosition): void { const positionOne = position === ConditionPosition.One; const eValueFrom = positionOne ? this.eValueFrom1 : this.eValueFrom2; const eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2; eValueFrom.setValue(model ? ('' + model.filter) : null); eValueTo.setValue(model ? ('' + model.filterTo) : null); } protected setValueFromFloatingFilter(value: string): void { this.eValueFrom1.setValue(value); this.eValueTo1.setValue(null); this.eValueFrom2.setValue(null); this.eValueTo2.setValue(null); } protected comparator(): Comparator<number> { return (left: number, right: number): number => { if (left === right) { return 0; } return left < right ? 1 : -1; }; } protected setParams(params: INumberFilterParams): void { this.numberFilterParams = params; const allowedCharPattern = this.getAllowedCharPattern(); if (allowedCharPattern) { const config = { allowedCharPattern }; this.resetTemplate({ eValueFrom1: config, eValueTo1: config, eValueFrom2: config, eValueTo2: config, }); } super.setParams(params); this.addValueChangedListeners(); } private addValueChangedListeners(): void { const listener = () => this.onUiChanged(); this.eValueFrom1.onValueChange(listener); this.eValueTo1.onValueChange(listener); this.eValueFrom2.onValueChange(listener); this.eValueTo2.onValueChange(listener); } private resetPlaceholder(): void { const globalTranslate = this.gridOptionsWrapper.getLocaleTextFunc(); const isRange1 = this.showValueTo(this.getCondition1Type()); const isRange2 = this.showValueTo(this.getCondition2Type()); this.eValueFrom1.setInputPlaceholder(this.translate(isRange1 ? 'inRangeStart' : 'filterOoo')); this.eValueFrom1.setInputAriaLabel( isRange1 ? globalTranslate('ariaFilterFromValue', 'Filter from value') : globalTranslate('ariaFilterValue', 'Filter Value') ); this.eValueTo1.setInputPlaceholder(this.translate('inRangeEnd')); this.eValueTo1.setInputAriaLabel(globalTranslate('ariaFilterToValue', 'Filter to Value')); this.eValueFrom2.setInputPlaceholder(this.translate(isRange2 ? 'inRangeStart' : 'filterOoo')); this.eValueFrom2.setInputAriaLabel( isRange2 ? globalTranslate('ariaFilterFromValue', 'Filter from value') : globalTranslate('ariaFilterValue', 'Filter Value') ); this.eValueTo2.setInputPlaceholder(this.translate('inRangeEnd')); this.eValueTo2.setInputAriaLabel(globalTranslate('ariaFilterToValue', 'Filter to Value')); } public afterGuiAttached(params?: IAfterGuiAttachedParams): void { super.afterGuiAttached(params); this.resetPlaceholder(); if (!params || !params.suppressFocus) { this.eValueFrom1.getInputElement().focus(); } } protected getDefaultFilterOptions(): string[] { return NumberFilter.DEFAULT_FILTER_OPTIONS; } protected createValueTemplate(position: ConditionPosition): string { const pos = position === ConditionPosition.One ? '1' : '2'; const allowedCharPattern = this.getAllowedCharPattern(); const agElementTag = allowedCharPattern ? 'ag-input-text-field' : 'ag-input-number-field'; return /* html */` <div class="ag-filter-body" ref="eCondition${pos}Body" role="presentation"> <${agElementTag} class="ag-filter-from ag-filter-filter" ref="eValueFrom${pos}"></${agElementTag}> <${agElementTag} class="ag-filter-to ag-filter-filter" ref="eValueTo${pos}"></${agElementTag}> </div>`; } protected isConditionUiComplete(position: ConditionPosition): boolean { const positionOne = position === ConditionPosition.One; const option = positionOne ? this.getCondition1Type() : this.getCondition2Type(); if (option === SimpleFilter.EMPTY) { return false; } if (this.doesFilterHaveHiddenInput(option)) { return true; } const eValue = positionOne ? this.eValueFrom1 : this.eValueFrom2; const eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2; const value = this.stringToFloat(eValue.getValue()); return value != null && (!this.showValueTo(option) || this.stringToFloat(eValueTo.getValue()) != null); } protected areSimpleModelsEqual(aSimple: NumberFilterModel, bSimple: NumberFilterModel): boolean { return aSimple.filter === bSimple.filter && aSimple.filterTo === bSimple.filterTo && aSimple.type === bSimple.type; } protected getFilterType(): string { return 'number'; } private stringToFloat(value: string | number): number { if (typeof value === 'number') { return value; } let filterText = makeNull(value); if (filterText != null && filterText.trim() === '') { filterText = null; } if (this.numberFilterParams.numberParser) { return this.numberFilterParams.numberParser(filterText); } return filterText == null || filterText.trim() === '-' ? null : parseFloat(filterText); } protected createCondition(position: ConditionPosition): NumberFilterModel { const positionOne = position === ConditionPosition.One; const type = positionOne ? this.getCondition1Type() : this.getCondition2Type(); const eValue = positionOne ? this.eValueFrom1 : this.eValueFrom2; const value = this.stringToFloat(eValue.getValue()); const model: NumberFilterModel = { filterType: this.getFilterType(), type }; if (!this.doesFilterHaveHiddenInput(type)) { model.filter = value; if (this.showValueTo(type)) { const eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2; const valueTo = this.stringToFloat(eValueTo.getValue()); model.filterTo = valueTo; } } return model; } protected updateUiVisibility(): void { super.updateUiVisibility(); this.resetPlaceholder(); const condition1Type = this.getCondition1Type(); const condition2Type = this.getCondition2Type(); setDisplayed(this.eValueFrom1.getGui(), this.showValueFrom(condition1Type)); setDisplayed(this.eValueTo1.getGui(), this.showValueTo(condition1Type)); setDisplayed(this.eValueFrom2.getGui(), this.showValueFrom(condition2Type)); setDisplayed(this.eValueTo2.getGui(), this.showValueTo(condition2Type)); } private getAllowedCharPattern(): string | null { const { allowedCharPattern } = this.numberFilterParams || {}; if (allowedCharPattern) { return allowedCharPattern; } if (!isBrowserChrome() && !isBrowserEdge()) { // only Chrome and Edge support the HTML5 number field, so for other browsers we provide an equivalent // constraint instead return '\\d\\-\\.'; } return null; } }
jenkins-sigaut/ag-grid
charts-packages/ag-charts-community/src/main.ts
export * from "./caption"; export * from "./chart/axis/numberAxis"; export * from "./chart/axis/categoryAxis"; export * from "./chart/axis/groupedCategoryAxis"; export * from "./chart/axis/timeAxis"; export * from "./chart/cartesianChart"; export * from "./chart/chart"; export * from "./chart/chartAxis"; export * from "./chart/groupedCategoryChart"; export * from "./chart/polarChart"; export * from "./chart/marker/marker"; export * from "./chart/legend"; export * from "./chart/series/cartesian/areaSeries"; export * from "./chart/series/cartesian/barSeries"; export * from "./chart/series/cartesian/lineSeries"; export * from "./chart/series/cartesian/scatterSeries"; export * from "./chart/series/cartesian/histogramSeries"; export * from "./chart/series/polar/pieSeries"; export * from "./scale/bandScale"; export * from "./scale/linearScale"; export * from "./scene/clipRect"; export * from "./scene/dropShadow"; export * from "./scene/group"; export * from "./scene/scene"; export * from "./scene/shape/arc"; export * from "./scene/shape/line"; export * from "./scene/shape/path"; export * from "./scene/shape/rect"; export * from "./scene/shape/sector"; export * from "./scene/shape/shape"; export * from "./util/angle"; export * from "./util/array"; export * from "./util/padding"; import { millisecond } from "./util/time/millisecond"; import { second } from "./util/time/second"; import { minute } from "./util/time/minute"; import { hour } from "./util/time/hour"; import { day } from "./util/time/day"; import { sunday, monday, tuesday, wednesday, thursday, friday, saturday } from "./util/time/week"; import { month } from "./util/time/month"; import { year } from "./util/time/year"; import { utcMinute } from "./util/time/utcMinute"; import { utcHour } from "./util/time/utcHour"; import { utcDay } from "./util/time/utcDay"; import { utcMonth } from "./util/time/utcMonth"; import { utcYear } from "./util/time/utcYear"; export const time = { millisecond, second, minute, hour, day, sunday, monday, tuesday, wednesday, thursday, friday, saturday, month, year, utcMinute, utcHour, utcDay, utcMonth, utcYear }; export * from "./chart/agChartOptions"; export * from "./chart/agChart"; export * from "./chart/themes/chartTheme";
jenkins-sigaut/ag-grid
enterprise-modules/charts/src/gridChartsModule.ts
import { Module, ModuleNames } from "@ag-grid-community/core"; import { EnterpriseCoreModule } from "@ag-grid-enterprise/core"; import { ChartService } from "./charts/chartService"; import { ChartTranslator } from "./charts/chartComp/chartTranslator"; import { ChartCrossFilter } from "./charts/chartComp/chartCrossFilter"; import { RangeSelectionModule } from "@ag-grid-enterprise/range-selection"; export const GridChartsModule: Module = { moduleName: ModuleNames.GridChartsModule, beans: [ ChartService, ChartTranslator, ChartCrossFilter ], dependantModules: [ RangeSelectionModule, EnterpriseCoreModule ] };
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/headerRendering/standardMenu.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { BeanStub } from "../context/beanStub"; import { IMenuFactory } from '../interfaces/iMenuFactory'; import { Column } from '../entities/column'; import { GridPanel } from "../gridPanel/gridPanel"; export declare class StandardMenuFactory extends BeanStub implements IMenuFactory { private filterManager; private popupService; private focusController; private hidePopup; private tabListener; private gridPanel; registerGridComp(gridPanel: GridPanel): void; hideActiveMenu(): void; showMenuAfterMouseEvent(column: Column, mouseEvent: MouseEvent | Touch): void; showMenuAfterButtonClick(column: Column, eventSource: HTMLElement): void; showPopup(column: Column, positionCallback: (eMenu: HTMLElement) => void, eventSource: HTMLElement): void; private trapFocusWithin; isMenuEnabled(column: Column): boolean; }
jenkins-sigaut/ag-grid
enterprise-modules/excel-export/src/excelExport/files/ooxml/styles/stylesheet.ts
import { ExcelOOXMLTemplate, ExcelStyle, ExcelInterior, ExcelBorders, ExcelFont, _ } from '@ag-grid-community/core'; import numberFormatsFactory from './numberFormats'; import fontsFactory from './fonts'; import fillsFactory from './fills'; import bordersFactory from './borders'; import cellStylesXfsFactory from './cellStyleXfs'; import cellXfsFactory from './cellXfs'; import cellStylesFactory from './cellStyles'; import { NumberFormat, numberFormatMap } from './numberFormat'; import { getFamilyId, Font } from './font'; import { Fill } from './fill'; import { convertLegacyBorder, BorderSet, Border } from './border'; import { Xf } from './xf'; import { CellStyle } from './cellStyle'; let stylesMap: StylesMap; let registeredNumberFmts: NumberFormat[]; let registeredFonts: Font[]; let registeredFills: Fill[]; let registeredBorders: BorderSet[]; let registeredCellStyleXfs: Xf[]; let registeredCellXfs: Xf[]; let registeredCellStyles: CellStyle[]; interface StylesMap { [key: string]: number; } interface ColorMap { [key: string]: string; } type BorderProperty = string | undefined; const resetStylesheetValues = (): void => { stylesMap = { base: 0 }; registeredNumberFmts = []; registeredFonts = [{ name: 'Calibri', size: 14, colorTheme: '1', family: 2, scheme: 'minor' }]; registeredFills = [{ patternType: 'none', }, { patternType: 'gray125' }]; registeredBorders = [{ left: undefined, right: undefined, top: undefined, bottom: undefined, diagonal: undefined }]; registeredCellStyleXfs = [{ borderId: 0, fillId: 0, fontId: 0, numFmtId: 0 }]; registeredCellXfs = [{ borderId: 0, fillId: 0, fontId: 0, numFmtId: 0, xfId: 0 }]; registeredCellStyles = [{ builtinId: 0, name: 'normal', xfId: 0 }]; }; const convertLegacyPattern = (name: string): string => { const colorMap: ColorMap = { None: 'none', Solid: 'solid', Gray50: 'mediumGray', Gray75: 'darkGray', Gray25: 'lightGray', HorzStripe: 'darkHorizontal', VertStripe: 'darkVertical', ReverseDiagStripe: 'darkDown', DiagStripe: 'darkUp', DiagCross: 'darkGrid', ThickDiagCross: 'darkTrellis', ThinHorzStripe: 'lightHorizontal', ThinVertStripe: 'lightVertical', ThinReverseDiagStripe: 'lightDown', ThinDiagStripe: 'lightUp', ThinHorzCross: 'lightGrid', ThinDiagCross: 'lightTrellis', Gray125: 'gray125', Gray0625: 'gray0625' }; if (!name) { return 'none'; } return colorMap[name] || name; }; export const convertLegacyColor = (color: string): string => { if (color == undefined) { return color; } if (color.charAt(0) === '#') { color = color.substr(1); } return color.length === 6 ? '00' + color : color; }; const registerFill = (fill: ExcelInterior): number => { const convertedPattern = convertLegacyPattern(fill.pattern); const convertedFillColor = convertLegacyColor(fill.color); const convertedPatternColor = convertLegacyColor(fill.patternColor); let pos = _.findIndex(registeredFills, currentFill => { const { patternType, fgRgb, bgRgb } = currentFill; if ( patternType != convertedPattern || fgRgb != convertedFillColor || bgRgb != convertedPatternColor ) { return false; } return true; }); if (pos === -1) { pos = registeredFills.length; registeredFills.push({ patternType: convertedPattern, fgRgb: convertedFillColor, bgRgb: convertedPatternColor }); } return pos; }; const registerNumberFmt = (format: string): number => { format = _.utf8_encode(format); if (numberFormatMap[format]) { return numberFormatMap[format]; } let pos = _.findIndex(registeredNumberFmts, currentFormat => currentFormat.formatCode === format); if (pos === -1) { pos = registeredNumberFmts.length + 164; registeredNumberFmts.push({ formatCode: format, numFmtId: pos }); } else { pos = registeredNumberFmts[pos].numFmtId; } return pos; }; const registerBorders = (borders: ExcelBorders): number => { const { borderBottom, borderTop, borderLeft, borderRight } = borders; let bottomStyle: BorderProperty; let topStyle: BorderProperty; let leftStyle: BorderProperty; let rightStyle: BorderProperty; let bottomColor: BorderProperty; let topColor: BorderProperty; let leftColor: BorderProperty; let rightColor: BorderProperty; if (borderLeft) { leftStyle = convertLegacyBorder(borderLeft.lineStyle, borderLeft.weight); leftColor = convertLegacyColor(borderLeft.color); } if (borderRight) { rightStyle = convertLegacyBorder(borderRight.lineStyle, borderRight.weight); rightColor = convertLegacyColor(borderRight.color); } if (borderBottom) { bottomStyle = convertLegacyBorder(borderBottom.lineStyle, borderBottom.weight); bottomColor = convertLegacyColor(borderBottom.color); } if (borderTop) { topStyle = convertLegacyBorder(borderTop.lineStyle, borderTop.weight); topColor = convertLegacyColor(borderTop.color); } let pos = _.findIndex(registeredBorders, currentBorder => { const { left, right, top, bottom } = currentBorder; if (!left && (leftStyle || leftColor)) { return false; } if (!right && (rightStyle || rightColor)) { return false; } if (!top && (topStyle || topColor)) { return false; } if (!bottom && (bottomStyle || bottomColor)) { return false; } const { style: clS, color: clC } = left || {} as Border; const { style: crS, color: crC } = right || {} as Border; const { style: ctS, color: ctC } = top || {} as Border; const { style: cbS, color: cbC } = bottom || {} as Border; if (clS != leftStyle || clC != leftColor) { return false; } if (crS != rightStyle || crC != rightColor) { return false; } if (ctS != topStyle || ctC != topColor) { return false; } if (cbS != bottomStyle || cbC != bottomColor) { return false; } return true; }); if (pos === -1) { pos = registeredBorders.length; registeredBorders.push({ left: { style: leftStyle, color: leftColor }, right: { style: rightStyle, color: rightColor }, top: { style: topStyle, color: topColor }, bottom: { style: bottomStyle, color: bottomColor }, diagonal: { style: undefined, color: undefined } }); } return pos; }; const registerFont = (font: ExcelFont): number => { const { fontName: name, color, size, bold, italic, outline, shadow, strikeThrough, underline, family } = font; const utf8Name = name ? _.utf8_encode(name) : name; const convertedColor = convertLegacyColor(color); const familyId = getFamilyId(family); let pos = _.findIndex(registeredFonts, (currentFont) => { if ( currentFont.name != utf8Name || currentFont.color != convertedColor || currentFont.size != size || currentFont.bold != bold || currentFont.italic != italic || currentFont.outline != outline || currentFont.shadow != shadow || currentFont.strike != strikeThrough || currentFont.underline != underline || currentFont.family != familyId ) { return false; } return true; }); if (pos === -1) { pos = registeredFonts.length; registeredFonts.push({ name: utf8Name, color: convertedColor, size, bold, italic, outline, shadow, strike: strikeThrough, underline, family: familyId }); } return pos; }; const registerStyle = (config: ExcelStyle): void => { const { id, alignment, borders, font, interior, numberFormat, protection } = config; let currentFill = 0; let currentBorder = 0; let currentFont = 0; let currentNumberFmt = 0; if (!id || stylesMap[id] != undefined) { return; } if (interior) { currentFill = registerFill(interior); } if (borders) { currentBorder = registerBorders(borders); } if (font) { currentFont = registerFont(font); } if (numberFormat) { currentNumberFmt = registerNumberFmt(numberFormat.format); } stylesMap[id] = registeredCellXfs.length; registeredCellXfs.push({ alignment, borderId: currentBorder || 0, fillId: currentFill || 0, fontId: currentFont || 0, numFmtId: currentNumberFmt || 0, protection, xfId: 0 }); }; const stylesheetFactory: ExcelOOXMLTemplate = { getTemplate() { const numberFormats = numberFormatsFactory.getTemplate(registeredNumberFmts); const fonts = fontsFactory.getTemplate(registeredFonts); const fills = fillsFactory.getTemplate(registeredFills); const borders = bordersFactory.getTemplate(registeredBorders); const cellStylesXfs = cellStylesXfsFactory.getTemplate(registeredCellStyleXfs); const cellXfs = cellXfsFactory.getTemplate(registeredCellXfs); const cellStyles = cellStylesFactory.getTemplate(registeredCellStyles); resetStylesheetValues(); return { name: 'styleSheet', properties: { rawMap: { xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main' } }, children: [ numberFormats, fonts, fills, borders, cellStylesXfs, cellXfs, cellStyles, { name: 'tableStyles', properties: { rawMap: { count: 0, defaultPivotStyle: 'PivotStyleLight16', defaultTableStyle: 'TableStyleMedium2' } } } ] }; } }; export const getStyleId = (name: string): number => { return stylesMap[name] || 0; }; export const registerStyles = (styles: ExcelStyle[]): void => { resetStylesheetValues(); styles.forEach(registerStyle); }; export default stylesheetFactory;
jenkins-sigaut/ag-grid
community-modules/core/src/ts/dragAndDrop/dragAndDropService.ts
import { BeanStub } from "../context/beanStub"; import { PostConstruct, Bean, Autowired, PreDestroy } from "../context/context"; import { Column } from "../entities/column"; import { ColumnApi } from "../columnController/columnApi"; import { GridApi } from "../gridApi"; import { DragService, DragListenerParams } from "./dragService"; import { Environment } from "../environment"; import { RowDropZoneParams } from "../gridPanel/rowDragFeature"; import { RowNode } from "../entities/rowNode"; import { escapeString } from "../utils/string"; import { createIcon } from "../utils/icon"; import { removeFromArray } from "../utils/array"; import { find } from "../utils/generic"; import { getBodyHeight, getBodyWidth } from "../utils/browser"; import { loadTemplate, addCssClass, clearElement, addOrRemoveCssClass } from "../utils/dom"; import { isFunction } from "../utils/function"; export interface DragItem { /** * When dragging a row, this contains the row node being dragged * When dragging multiple rows, this contains the row that started the drag. */ rowNode?: RowNode; /** When dragging multiple rows, this contains all rows being dragged */ rowNodes?: RowNode[]; /** When dragging columns, this contains the columns being dragged */ columns?: Column[]; /** When dragging columns, this contains the visible state of the columns */ visibleState?: { [key: string]: boolean }; } export enum DragSourceType { ToolPanel, HeaderCell, RowDrag, ChartPanel } export interface DragSource { /** * The type of the drag source, used by the drop target to know where the * drag originated from. */ type: DragSourceType; /** * Element which, when dragged, will kick off the DnD process */ eElement: HTMLElement; /** * If eElement is dragged, then the dragItem is the object that gets passed around. */ getDragItem: () => DragItem; /** * This name appears in the ghost icon when dragging. */ dragItemName: string | (() => string) | null; /** * Icon to show when not over a drop zone */ defaultIconName?: string; /** * The drop target associated with this dragSource. When dragging starts, this * target does not get an onDragEnter event. */ dragSourceDropTarget?: DropTarget; /** * The drag source DOM Data Key, this is useful to detect if the origin grid is the same * as the target grid. */ dragSourceDomDataKey?: string; /** * After how many pixels of dragging should the drag operation start. Default is 4. */ dragStartPixels?: number; /** * Callback for drag started */ onDragStarted?: () => void; /** * Callback for drag stopped */ onDragStopped?: () => void; } export interface DropTarget { /** The main container that will get the drop. */ getContainer(): HTMLElement; /** If any secondary containers. For example when moving columns in ag-Grid, we listen for drops * in the header as well as the body (main rows and pinned rows) of the grid. */ getSecondaryContainers?(): HTMLElement[]; /** Icon to show when drag is over */ getIconName?(): string; isInterestedIn(type: DragSourceType): boolean; /** Callback for when drag enters */ onDragEnter?(params: DraggingEvent): void; /** Callback for when drag leaves */ onDragLeave?(params: DraggingEvent): void; /** Callback for when dragging */ onDragging?(params: DraggingEvent): void; /** Callback for when drag stops */ onDragStop?(params: DraggingEvent): void; external?: boolean; } export enum VerticalDirection { Up, Down } export enum HorizontalDirection { Left, Right } export interface DraggingEvent { event: MouseEvent; x: number; y: number; vDirection: VerticalDirection; hDirection: HorizontalDirection; dragSource: DragSource; dragItem: DragItem; fromNudge: boolean; api: GridApi; columnApi: ColumnApi; dropZoneTarget: HTMLElement; } @Bean('dragAndDropService') export class DragAndDropService extends BeanStub { @Autowired('dragService') private dragService: DragService; @Autowired('environment') private environment: Environment; @Autowired('columnApi') private columnApi: ColumnApi; @Autowired('gridApi') private gridApi: GridApi; public static ICON_PINNED = 'pinned'; public static ICON_MOVE = 'move'; public static ICON_LEFT = 'left'; public static ICON_RIGHT = 'right'; public static ICON_GROUP = 'group'; public static ICON_AGGREGATE = 'aggregate'; public static ICON_PIVOT = 'pivot'; public static ICON_NOT_ALLOWED = 'notAllowed'; public static ICON_HIDE = 'hide'; public static GHOST_TEMPLATE = `<div class="ag-dnd-ghost ag-unselectable"> <span class="ag-dnd-ghost-icon ag-shake-left-to-right"></span> <div class="ag-dnd-ghost-label"></div> </div>`; private dragSourceAndParamsList: { params: DragListenerParams, dragSource: DragSource }[] = []; private dragItem: DragItem; private eventLastTime: MouseEvent; private dragSource: DragSource; private dragging: boolean; private eGhost: HTMLElement; private eGhostParent: HTMLElement; private eGhostIcon: HTMLElement; private dropTargets: DropTarget[] = []; private lastDropTarget: DropTarget; private ePinnedIcon: HTMLElement; private eHideIcon: HTMLElement; private eMoveIcon: HTMLElement; private eLeftIcon: HTMLElement; private eRightIcon: HTMLElement; private eGroupIcon: HTMLElement; private eAggregateIcon: HTMLElement; private ePivotIcon: HTMLElement; private eDropNotAllowedIcon: HTMLElement; @PostConstruct private init(): void { this.ePinnedIcon = createIcon('columnMovePin', this.gridOptionsWrapper, null); this.eHideIcon = createIcon('columnMoveHide', this.gridOptionsWrapper, null); this.eMoveIcon = createIcon('columnMoveMove', this.gridOptionsWrapper, null); this.eLeftIcon = createIcon('columnMoveLeft', this.gridOptionsWrapper, null); this.eRightIcon = createIcon('columnMoveRight', this.gridOptionsWrapper, null); this.eGroupIcon = createIcon('columnMoveGroup', this.gridOptionsWrapper, null); this.eAggregateIcon = createIcon('columnMoveValue', this.gridOptionsWrapper, null); this.ePivotIcon = createIcon('columnMovePivot', this.gridOptionsWrapper, null); this.eDropNotAllowedIcon = createIcon('dropNotAllowed', this.gridOptionsWrapper, null); } public addDragSource(dragSource: DragSource, allowTouch = false): void { const params: DragListenerParams = { eElement: dragSource.eElement, dragStartPixels: dragSource.dragStartPixels, onDragStart: this.onDragStart.bind(this, dragSource), onDragStop: this.onDragStop.bind(this), onDragging: this.onDragging.bind(this) }; this.dragSourceAndParamsList.push({ params: params, dragSource: dragSource }); this.dragService.addDragSource(params, allowTouch); } public removeDragSource(dragSource: DragSource): void { const sourceAndParams = find(this.dragSourceAndParamsList, item => item.dragSource === dragSource); if (sourceAndParams) { this.dragService.removeDragSource(sourceAndParams.params); removeFromArray(this.dragSourceAndParamsList, sourceAndParams); } } @PreDestroy private clearDragSourceParamsList(): void { this.dragSourceAndParamsList.forEach(sourceAndParams => this.dragService.removeDragSource(sourceAndParams.params)); this.dragSourceAndParamsList.length = 0; } public nudge(): void { if (this.dragging) { this.onDragging(this.eventLastTime, true); } } private onDragStart(dragSource: DragSource, mouseEvent: MouseEvent): void { this.dragging = true; this.dragSource = dragSource; this.eventLastTime = mouseEvent; this.dragItem = this.dragSource.getDragItem(); this.lastDropTarget = this.dragSource.dragSourceDropTarget; if (this.dragSource.onDragStarted) { this.dragSource.onDragStarted(); } this.createGhost(); } private onDragStop(mouseEvent: MouseEvent): void { this.eventLastTime = null; this.dragging = false; if (this.dragSource.onDragStopped) { this.dragSource.onDragStopped(); } if (this.lastDropTarget && this.lastDropTarget.onDragStop) { const draggingEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, null, null, false); this.lastDropTarget.onDragStop(draggingEvent); } this.lastDropTarget = null; this.dragItem = null; this.removeGhost(); } private onDragging(mouseEvent: MouseEvent, fromNudge: boolean): void { const hDirection = this.getHorizontalDirection(mouseEvent); const vDirection = this.getVerticalDirection(mouseEvent); this.eventLastTime = mouseEvent; this.positionGhost(mouseEvent); // check if mouseEvent intersects with any of the drop targets const validDropTargets = this.dropTargets.filter(dropTarget => this.isMouseOnDropTarget(mouseEvent, dropTarget)); const len = validDropTargets.length; if (len === 0) { return; } const dropTarget: DropTarget = len === 1 ? validDropTargets[0] // the current mouse position could intersect with more than 1 element // if they are nested. In that case we need to get the most specific // container, which is the one that does not contain any other targets. : validDropTargets.reduce((prevTarget, currTarget) => { if (!prevTarget) { return currTarget; } const prevContainer = prevTarget.getContainer(); const currContainer = currTarget.getContainer(); if (prevContainer.contains(currContainer)) { return currTarget; } return prevTarget; }); if (dropTarget !== this.lastDropTarget) { this.leaveLastTargetIfExists(mouseEvent, hDirection, vDirection, fromNudge); this.enterDragTargetIfExists(dropTarget, mouseEvent, hDirection, vDirection, fromNudge); this.lastDropTarget = dropTarget; } else if (dropTarget && dropTarget.onDragging) { const draggingEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge); dropTarget.onDragging(draggingEvent); } } private enterDragTargetIfExists(dropTarget: DropTarget, mouseEvent: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): void { if (!dropTarget) { return; } if (dropTarget.onDragEnter) { const dragEnterEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge); dropTarget.onDragEnter(dragEnterEvent); } this.setGhostIcon(dropTarget.getIconName ? dropTarget.getIconName() : null); } private leaveLastTargetIfExists(mouseEvent: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): void { if (!this.lastDropTarget) { return; } if (this.lastDropTarget.onDragLeave) { const dragLeaveEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, hDirection, vDirection, fromNudge); this.lastDropTarget.onDragLeave(dragLeaveEvent); } this.setGhostIcon(null); } private getAllContainersFromDropTarget(dropTarget: DropTarget): HTMLElement[] { let containers = [dropTarget.getContainer()]; const secondaryContainers = dropTarget.getSecondaryContainers ? dropTarget.getSecondaryContainers() : null; if (secondaryContainers) { containers = containers.concat(secondaryContainers); } return containers; } // checks if the mouse is on the drop target. it checks eContainer and eSecondaryContainers private isMouseOnDropTarget(mouseEvent: MouseEvent, dropTarget: DropTarget): boolean { let mouseOverTarget = false; this.getAllContainersFromDropTarget(dropTarget) .filter(eContainer => eContainer) // secondary can be missing .forEach(eContainer => { const rect = eContainer.getBoundingClientRect(); // if element is not visible, then width and height are zero if (rect.width === 0 || rect.height === 0) { return; } const horizontalFit = mouseEvent.clientX >= rect.left && mouseEvent.clientX <= rect.right; const verticalFit = mouseEvent.clientY >= rect.top && mouseEvent.clientY <= rect.bottom; if (horizontalFit && verticalFit) { mouseOverTarget = true; } }); return mouseOverTarget && dropTarget.isInterestedIn(this.dragSource.type); } public addDropTarget(dropTarget: DropTarget) { this.dropTargets.push(dropTarget); } public removeDropTarget(dropTarget: DropTarget) { this.dropTargets = this.dropTargets.filter(target => target.getContainer() !== dropTarget.getContainer()); } public hasExternalDropZones(): boolean { return this.dropTargets.some(zones => zones.external); } public findExternalZone(params: RowDropZoneParams): DropTarget { const externalTargets = this.dropTargets.filter(target => target.external); return find(externalTargets, zone => zone.getContainer() === params.getContainer()); } public getHorizontalDirection(event: MouseEvent): HorizontalDirection { const clientX = this.eventLastTime.clientX; const eClientX = event.clientX; if (clientX === eClientX) { return null; } return clientX > eClientX ? HorizontalDirection.Left : HorizontalDirection.Right; } public getVerticalDirection(event: MouseEvent): VerticalDirection { const clientY = this.eventLastTime.clientY; const eClientY = event.clientY; if (clientY === eClientY) { return null; } return clientY > eClientY ? VerticalDirection.Up : VerticalDirection.Down; } public createDropTargetEvent(dropTarget: DropTarget, event: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): DraggingEvent { // localise x and y to the target const dropZoneTarget = dropTarget.getContainer(); const rect = dropZoneTarget.getBoundingClientRect(); const { gridApi: api, columnApi, dragItem, dragSource } = this; const x = event.clientX - rect.left; const y = event.clientY - rect.top; return { event, x, y, vDirection, hDirection, dragSource, fromNudge, dragItem, api, columnApi, dropZoneTarget }; } private positionGhost(event: MouseEvent): void { const ghost = this.eGhost; const ghostRect = ghost.getBoundingClientRect(); const ghostHeight = ghostRect.height; // for some reason, without the '-2', it still overlapped by 1 or 2 pixels, which // then brought in scrollbars to the browser. no idea why, but putting in -2 here // works around it which is good enough for me. const browserWidth = getBodyWidth() - 2; const browserHeight = getBodyHeight() - 2; let top = event.pageY - (ghostHeight / 2); let left = event.pageX - 10; const usrDocument = this.gridOptionsWrapper.getDocument(); const windowScrollY = window.pageYOffset || usrDocument.documentElement.scrollTop; const windowScrollX = window.pageXOffset || usrDocument.documentElement.scrollLeft; // check ghost is not positioned outside of the browser if (browserWidth > 0 && ((left + ghost.clientWidth) > (browserWidth + windowScrollX))) { left = browserWidth + windowScrollX - ghost.clientWidth; } if (left < 0) { left = 0; } if (browserHeight > 0 && ((top + ghost.clientHeight) > (browserHeight + windowScrollY))) { top = browserHeight + windowScrollY - ghost.clientHeight; } if (top < 0) { top = 0; } ghost.style.left = `${left}px`; ghost.style.top = `${top}px`; } private removeGhost(): void { if (this.eGhost && this.eGhostParent) { this.eGhostParent.removeChild(this.eGhost); } this.eGhost = null; } private createGhost(): void { this.eGhost = loadTemplate(DragAndDropService.GHOST_TEMPLATE); const { theme } = this.environment.getTheme(); if (theme) { addCssClass(this.eGhost, theme); } this.eGhostIcon = this.eGhost.querySelector('.ag-dnd-ghost-icon') as HTMLElement; this.setGhostIcon(null); const eText = this.eGhost.querySelector('.ag-dnd-ghost-label') as HTMLElement; let dragItemName = this.dragSource.dragItemName; if (isFunction(dragItemName)) { dragItemName = (dragItemName as () => string)(); } eText.innerHTML = escapeString(dragItemName as string); this.eGhost.style.height = '25px'; this.eGhost.style.top = '20px'; this.eGhost.style.left = '20px'; const usrDocument = this.gridOptionsWrapper.getDocument(); this.eGhostParent = usrDocument.querySelector('body') as HTMLElement; if (!this.eGhostParent) { console.warn('ag-Grid: could not find document body, it is needed for dragging columns'); } else { this.eGhostParent.appendChild(this.eGhost); } } public setGhostIcon(iconName: string, shake = false): void { clearElement(this.eGhostIcon); let eIcon: HTMLElement; if (!iconName) { iconName = this.dragSource.defaultIconName || DragAndDropService.ICON_NOT_ALLOWED; } switch (iconName) { case DragAndDropService.ICON_PINNED: eIcon = this.ePinnedIcon; break; case DragAndDropService.ICON_MOVE: eIcon = this.eMoveIcon; break; case DragAndDropService.ICON_LEFT: eIcon = this.eLeftIcon; break; case DragAndDropService.ICON_RIGHT: eIcon = this.eRightIcon; break; case DragAndDropService.ICON_GROUP: eIcon = this.eGroupIcon; break; case DragAndDropService.ICON_AGGREGATE: eIcon = this.eAggregateIcon; break; case DragAndDropService.ICON_PIVOT: eIcon = this.ePivotIcon; break; case DragAndDropService.ICON_NOT_ALLOWED: eIcon = this.eDropNotAllowedIcon; break; case DragAndDropService.ICON_HIDE: eIcon = this.eHideIcon; break; } addOrRemoveCssClass(this.eGhostIcon, 'ag-shake-left-to-right', shake); if (eIcon === this.eHideIcon && this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns()) { return; } if (eIcon) { this.eGhostIcon.appendChild(eIcon); } } }
jenkins-sigaut/ag-grid
enterprise-modules/row-grouping/src/rowGrouping/batchRemover.ts
import { RowNode } from "@ag-grid-community/core"; // doing _.removeFromArray() multiple times on a large list can be a bottleneck. // when doing large deletes (eg removing 1,000 rows) then we would be calling _.removeFromArray() // a thousands of times, in particular RootNode.allGroupChildren could be a large list, and // 1,000 removes is time consuming as each one requires traversing the full list. // to get around this, we do all the removes in a batch. this class manages the batch. // // This problem was brought to light by a client (AG-2879), with dataset of 20,000 // in 10,000 groups (2 items per group), then deleting all rows with transaction, // it took about 20 seconds to delete. with the BathRemoved, the reduced to less than 1 second. interface RemoveDetails { removeFromChildrenAfterGroup: { [id: string]: boolean; }; removeFromAllLeafChildren: { [id: string]: boolean; }; } export class BatchRemover { private allSets: { [parentId: string]: RemoveDetails; } = {}; private allParents: RowNode[] = []; public removeFromChildrenAfterGroup(parent: RowNode, child: RowNode): void { const set = this.getSet(parent); set.removeFromChildrenAfterGroup[child.id!] = true; } public removeFromAllLeafChildren(parent: RowNode, child: RowNode): void { const set = this.getSet(parent); set.removeFromAllLeafChildren[child.id!] = true; } private getSet(parent: RowNode): RemoveDetails { if (!this.allSets[parent.id!]) { this.allSets[parent.id!] = { removeFromAllLeafChildren: {}, removeFromChildrenAfterGroup: {} }; this.allParents.push(parent); } return this.allSets[parent.id!]; } public flush(): void { this.allParents.forEach(parent => { const nodeDetails = this.allSets[parent.id!]; parent.childrenAfterGroup = parent.childrenAfterGroup!.filter( child => !nodeDetails.removeFromChildrenAfterGroup[child.id!] ); parent.allLeafChildren = parent.allLeafChildren.filter( child => !nodeDetails.removeFromAllLeafChildren[child.id!] ); parent.updateHasChildren(); }); this.allSets = {}; this.allParents.length = 0; } }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/entities/columnGroup.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { ColumnGroupChild } from "./columnGroupChild"; import { ColGroupDef } from "./colDef"; import { Column } from "./column"; import { AbstractColDef } from "./colDef"; import { OriginalColumnGroup } from "./originalColumnGroup"; import { GridOptionsWrapper } from "../gridOptionsWrapper"; export declare class ColumnGroup implements ColumnGroupChild { static HEADER_GROUP_SHOW_OPEN: string; static HEADER_GROUP_SHOW_CLOSED: string; static HEADER_GROUP_PADDING: string; static EVENT_LEFT_CHANGED: string; static EVENT_DISPLAYED_CHILDREN_CHANGED: string; static createUniqueId(groupId: string, instanceId: number): string; gridOptionsWrapper: GridOptionsWrapper; private children; private displayedChildren; private readonly groupId; private readonly instanceId; private readonly originalColumnGroup; private readonly pinned; private left; private oldLeft; private localEventService; private parent; constructor(originalColumnGroup: OriginalColumnGroup, groupId: string, instanceId: number, pinned: 'left' | 'right'); reset(): void; getParent(): ColumnGroup; setParent(parent: ColumnGroup): void; getUniqueId(): string; isEmptyGroup(): boolean; isMoving(): boolean; checkLeft(): void; getLeft(): number; getOldLeft(): number; setLeft(left: number): void; getPinned(): 'left' | 'right'; private createAgEvent; addEventListener(eventType: string, listener: Function): void; removeEventListener(eventType: string, listener: Function): void; getGroupId(): string; getInstanceId(): number; isChildInThisGroupDeepSearch(wantedChild: ColumnGroupChild): boolean; getActualWidth(): number; isResizable(): boolean; getMinWidth(): number; addChild(child: ColumnGroupChild): void; getDisplayedChildren(): ColumnGroupChild[]; getLeafColumns(): Column[]; getDisplayedLeafColumns(): Column[]; getDefinition(): AbstractColDef; getColGroupDef(): ColGroupDef; isPadding(): boolean; isExpandable(): boolean; isExpanded(): boolean; setExpanded(expanded: boolean): void; private addDisplayedLeafColumns; private addLeafColumns; getChildren(): ColumnGroupChild[]; getColumnGroupShow(): string | undefined; getOriginalColumnGroup(): OriginalColumnGroup; getPaddingLevel(): number; calculateDisplayedColumns(): void; }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/rendering/row/rowComp.ts
import { Beans } from "../beans"; import { CellComp } from "../cellComp"; import { DataChangedEvent, RowNode } from "../../entities/rowNode"; import { Column } from "../../entities/column"; import { Events, RowClickedEvent, RowDoubleClickedEvent, RowEditingStartedEvent, RowEditingStoppedEvent, RowEvent, RowValueChangedEvent, VirtualRowRemovedEvent } from "../../events"; import { ICellRendererComp } from "../cellRenderers/iCellRenderer"; import { RowContainerComponent } from "./rowContainerComponent"; import { Component } from "../../widgets/component"; import { ProcessRowParams } from "../../entities/gridOptions"; import { IFrameworkOverrides } from "../../interfaces/iFrameworkOverrides"; import { Constants } from "../../constants/constants"; import { ModuleNames } from "../../modules/moduleNames"; import { ModuleRegistry } from "../../modules/moduleRegistry"; import { setAriaExpanded, setAriaSelected, setAriaLabel, setAriaRowIndex } from "../../utils/aria"; import { escapeString } from "../../utils/string"; import { removeCssClass, addCssClass, addOrRemoveCssClass, setDomChildOrder, appendHtml, isElementChildOfClass, addStylesToElement } from "../../utils/dom"; import { removeFromArray, pushAll } from "../../utils/array"; import { missing, exists } from "../../utils/generic"; import { isStopPropagationForAgGrid } from "../../utils/event"; import { iterateObject, assign } from "../../utils/object"; import { cssStyleObjectToMarkup } from "../../utils/general"; import {AngularRowUtils} from "./angularRowUtils"; interface CellTemplate { template: string; cellComps: CellComp[]; } export class RowComp extends Component { public static DOM_DATA_KEY_RENDERED_ROW = 'renderedRow'; private static FULL_WIDTH_CELL_RENDERER = 'fullWidthCellRenderer'; private static GROUP_ROW_RENDERER = 'groupRowRenderer'; private static GROUP_ROW_RENDERER_COMP_NAME = 'agGroupRowRenderer'; private static LOADING_CELL_RENDERER = 'loadingCellRenderer'; private static LOADING_CELL_RENDERER_COMP_NAME = 'agLoadingCellRenderer'; private static DETAIL_CELL_RENDERER = 'detailCellRenderer'; private static DETAIL_CELL_RENDERER_COMP_NAME = 'agDetailCellRenderer'; private readonly rowNode: RowNode; private readonly beans: Beans; private ePinnedLeftRow: HTMLElement; private ePinnedRightRow: HTMLElement; private eBodyRow: HTMLElement; private eAllRowContainers: HTMLElement[] = []; private eFullWidthRow: HTMLElement; private eFullWidthRowBody: HTMLElement; private eFullWidthRowLeft: HTMLElement; private eFullWidthRowRight: HTMLElement; private readonly bodyContainerComp: RowContainerComponent; private readonly fullWidthContainerComp: RowContainerComponent; private readonly pinnedLeftContainerComp: RowContainerComponent; private readonly pinnedRightContainerComp: RowContainerComponent; private fullWidthRowComponent: ICellRendererComp; private fullWidthRowComponentBody: ICellRendererComp; private fullWidthRowComponentLeft: ICellRendererComp; private fullWidthRowComponentRight: ICellRendererComp; private fullWidthRowDestroyFuncs: (() => void)[] = []; private firstRowOnPage: boolean; private lastRowOnPage: boolean; private active = true; private fullWidthRow: boolean; private editingRow: boolean; private rowFocused: boolean; private rowContainerReadyCount = 0; private refreshNeeded = false; private columnRefreshPending = false; private cellComps: { [key: string]: CellComp; } = {}; // for animations, there are bits we want done in the next VM turn, to all DOM to update first. // instead of each row doing a setTimeout(func,0), we put the functions here and the rowRenderer // executes them all in one timeout private createSecondPassFuncs: Function[] = []; // these get called before the row is destroyed - they set up the DOM for the remove animation (ie they // set the DOM up for the animation), then the delayedDestroyFunctions get called when the animation is // complete (ie removes from the dom). private removeFirstPassFuncs: Function[] = []; // for animations, these functions get called 400ms after the row is cleared, called by the rowRenderer // so each row isn't setting up it's own timeout private removeSecondPassFuncs: Function[] = []; private fadeRowIn: boolean; private slideRowIn: boolean; private readonly useAnimationFrameForCreate: boolean; private rowIsEven: boolean; private paginationPage: number; private parentScope: any; private scope: any; private initialised = false; private elementOrderChanged = false; private lastMouseDownOnDragger = false; private rowLevel: number; private readonly printLayout: boolean; private readonly embedFullWidth: boolean; constructor( parentScope: any, bodyContainerComp: RowContainerComponent, pinnedLeftContainerComp: RowContainerComponent, pinnedRightContainerComp: RowContainerComponent, fullWidthContainerComp: RowContainerComponent, rowNode: RowNode, beans: Beans, animateIn: boolean, useAnimationFrameForCreate: boolean, printLayout: boolean, embedFullWidth: boolean ) { super(); this.parentScope = parentScope; this.beans = beans; this.bodyContainerComp = bodyContainerComp; this.pinnedLeftContainerComp = pinnedLeftContainerComp; this.pinnedRightContainerComp = pinnedRightContainerComp; this.fullWidthContainerComp = fullWidthContainerComp; this.rowNode = rowNode; this.rowIsEven = this.rowNode.rowIndex % 2 === 0; this.paginationPage = this.beans.paginationProxy.getCurrentPage(); this.useAnimationFrameForCreate = useAnimationFrameForCreate; this.printLayout = printLayout; this.embedFullWidth = embedFullWidth; this.setAnimateFlags(animateIn); } public init(): void { this.rowFocused = this.beans.focusController.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned); this.setupAngular1Scope(); this.rowLevel = this.beans.rowCssClassCalculator.calculateRowLevel(this.rowNode); this.setupRowContainers(); this.addListeners(); if (this.slideRowIn) { this.createSecondPassFuncs.push(() => { this.onTopChanged(); }); } if (this.fadeRowIn) { this.createSecondPassFuncs.push(() => { this.eAllRowContainers.forEach(eRow => removeCssClass(eRow, 'ag-opacity-zero')); }); } } private setupAngular1Scope(): void { const scopeResult = AngularRowUtils.createChildScopeOrNull(this.rowNode, this.parentScope, this.beans.gridOptionsWrapper); if (scopeResult) { this.scope = scopeResult.scope; this.addDestroyFunc(scopeResult.scopeDestroyFunc); } } private createTemplate(contents: string, extraCssClass: string = null): string { const templateParts: string[] = []; const rowHeight = this.rowNode.rowHeight; const rowClasses = this.getInitialRowClasses(extraCssClass).join(' '); const rowIdSanitised = escapeString(this.rowNode.id); const userRowStyles = this.preProcessStylesFromGridOptions(); const businessKey = this.getRowBusinessKey(); const businessKeySanitised = escapeString(businessKey); const rowTopStyle = this.getInitialRowTopStyle(); const rowIdx = this.rowNode.getRowIndexString(); const headerRowCount = this.beans.headerNavigationService.getHeaderRowCount(); templateParts.push(`<div`); templateParts.push(` role="row"`); templateParts.push(` row-index="${rowIdx}" aria-rowindex="${headerRowCount + this.rowNode.rowIndex + 1}"`); templateParts.push(rowIdSanitised ? ` row-id="${rowIdSanitised}"` : ``); templateParts.push(businessKey ? ` row-business-key="${businessKeySanitised}"` : ``); templateParts.push(` comp-id="${this.getCompId()}"`); templateParts.push(` class="${rowClasses}"`); if (this.beans.gridOptionsWrapper.isRowSelection()) { templateParts.push(` aria-selected="${this.rowNode.isSelected() ? 'true' : 'false'}"`); } if (this.rowNode.group) { templateParts.push(` aria-expanded=${this.rowNode.expanded ? 'true' : 'false'}`); } templateParts.push(` style="height: ${rowHeight}px; ${rowTopStyle} ${userRowStyles}">`); // add in the template for the cells templateParts.push(contents); templateParts.push(`</div>`); return templateParts.join(''); } public getCellForCol(column: Column): HTMLElement { const cellComp = this.cellComps[column.getColId()]; return cellComp ? cellComp.getGui() : null; } public afterFlush(): void { if (this.initialised) { return; } this.initialised = true; this.executeProcessRowPostCreateFunc(); } private executeProcessRowPostCreateFunc(): void { const func = this.beans.gridOptionsWrapper.getProcessRowPostCreateFunc(); if (!func) { return; } const params: ProcessRowParams = { eRow: this.eBodyRow, ePinnedLeftRow: this.ePinnedLeftRow, ePinnedRightRow: this.ePinnedRightRow, node: this.rowNode, api: this.beans.gridOptionsWrapper.getApi(), rowIndex: this.rowNode.rowIndex, addRenderedRowListener: this.addEventListener.bind(this), columnApi: this.beans.gridOptionsWrapper.getColumnApi(), context: this.beans.gridOptionsWrapper.getContext() }; func(params); } private getInitialRowTopStyle() { // print layout uses normal flow layout for row positioning if (this.printLayout) { return ''; } // if sliding in, we take the old row top. otherwise we just set the current row top. const pixels = this.slideRowIn ? this.roundRowTopToBounds(this.rowNode.oldRowTop) : this.rowNode.rowTop; const afterPaginationPixels = this.applyPaginationOffset(pixels); // we don't apply scaling if row is pinned const afterScalingPixels = this.rowNode.isRowPinned() ? afterPaginationPixels : this.beans.maxDivHeightScaler.getRealPixelPosition(afterPaginationPixels); const isSuppressRowTransform = this.beans.gridOptionsWrapper.isSuppressRowTransform(); return isSuppressRowTransform ? `top: ${afterScalingPixels}px; ` : `transform: translateY(${afterScalingPixels}px);`; } private getRowBusinessKey(): string { const businessKeyForNodeFunc = this.beans.gridOptionsWrapper.getBusinessKeyForNodeFunc(); if (typeof businessKeyForNodeFunc !== 'function') { return; } return businessKeyForNodeFunc(this.rowNode); } private areAllContainersReady(): boolean { return this.rowContainerReadyCount === 3; } private lazyCreateCells(cols: Column[], eRow: HTMLElement): void { if (!this.active) { return; } const cellTemplatesAndComps = this.createCells(cols); eRow.innerHTML = cellTemplatesAndComps.template; this.callAfterRowAttachedOnCells(cellTemplatesAndComps.cellComps, eRow); this.rowContainerReadyCount++; if (this.areAllContainersReady() && this.refreshNeeded) { this.refreshCells(); } } private createRowContainer( rowContainerComp: RowContainerComponent, cols: Column[], callback: (eRow: HTMLElement) => void ): void { const useAnimationsFrameForCreate = this.useAnimationFrameForCreate; const cellTemplatesAndComps: CellTemplate = useAnimationsFrameForCreate ? { cellComps: [], template: '' } : this.createCells(cols); const rowTemplate = this.createTemplate(cellTemplatesAndComps.template); // the RowRenderer is probably inserting many rows. rather than inserting each template one // at a time, the grid inserts all rows together - so the callback here is called by the // rowRenderer when all RowComps are created, then all the HTML is inserted in one go, // and then all the callbacks are called. this is NOT done in an animation frame. rowContainerComp.appendRowTemplate(rowTemplate, () => { const eRow: HTMLElement = rowContainerComp.getRowElement(this.getCompId()); this.refreshAriaLabel(eRow, this.rowNode.isSelected()); this.afterRowAttached(rowContainerComp, eRow); callback(eRow); if (useAnimationsFrameForCreate) { this.beans.taskQueue.createTask( this.lazyCreateCells.bind(this, cols, eRow), this.rowNode.rowIndex, 'createTasksP1' ); } else { this.callAfterRowAttachedOnCells(cellTemplatesAndComps.cellComps, eRow); this.rowContainerReadyCount = 3; } }); } private setupRowContainers(): void { const isFullWidthCell = this.rowNode.isFullWidthCell(); const isDetailCell = this.beans.doingMasterDetail && this.rowNode.detail; const pivotMode = this.beans.columnController.isPivotMode(); // we only use full width for groups, not footers. it wouldn't make sense to include footers if not looking // for totals. if users complain about this, then we should introduce a new property 'footerUseEntireRow' // so each can be set independently (as a customer complained about footers getting full width, hence // introducing this logic) const isGroupRow = this.rowNode.group && !this.rowNode.footer; const isFullWidthGroup = isGroupRow && this.beans.gridOptionsWrapper.isGroupUseEntireRow(pivotMode); if (this.rowNode.stub) { this.createFullWidthRows(RowComp.LOADING_CELL_RENDERER, RowComp.LOADING_CELL_RENDERER_COMP_NAME, false); } else if (isDetailCell) { this.createFullWidthRows(RowComp.DETAIL_CELL_RENDERER, RowComp.DETAIL_CELL_RENDERER_COMP_NAME, true); } else if (isFullWidthCell) { this.createFullWidthRows(RowComp.FULL_WIDTH_CELL_RENDERER, null, false); } else if (isFullWidthGroup) { this.createFullWidthRows(RowComp.GROUP_ROW_RENDERER, RowComp.GROUP_ROW_RENDERER_COMP_NAME, false); } else { this.setupNormalRowContainers(); } } private setupNormalRowContainers(): void { let centerCols: Column[]; let leftCols: Column[] = []; let rightCols: Column[] = []; if (this.printLayout) { centerCols = this.beans.columnController.getAllDisplayedColumns(); } else { centerCols = this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode); leftCols = this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode); rightCols = this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode); } this.createRowContainer(this.bodyContainerComp, centerCols, eRow => this.eBodyRow = eRow); this.createRowContainer(this.pinnedRightContainerComp, rightCols, eRow => this.ePinnedRightRow = eRow); this.createRowContainer(this.pinnedLeftContainerComp, leftCols, eRow => this.ePinnedLeftRow = eRow); } private createFullWidthRows(type: string, name: string, detailRow: boolean): void { this.fullWidthRow = true; if (this.embedFullWidth) { this.createFullWidthRowContainer(this.bodyContainerComp, null, null, type, name, (eRow: HTMLElement) => { this.eFullWidthRowBody = eRow; }, (cellRenderer: ICellRendererComp) => { this.fullWidthRowComponentBody = cellRenderer; }, detailRow); // printLayout doesn't put components into the pinned sections if (this.printLayout) { return; } this.createFullWidthRowContainer(this.pinnedLeftContainerComp, Constants.PINNED_LEFT, 'ag-cell-last-left-pinned', type, name, (eRow: HTMLElement) => { this.eFullWidthRowLeft = eRow; }, (cellRenderer: ICellRendererComp) => { this.fullWidthRowComponentLeft = cellRenderer; }, detailRow); this.createFullWidthRowContainer(this.pinnedRightContainerComp, Constants.PINNED_RIGHT, 'ag-cell-first-right-pinned', type, name, (eRow: HTMLElement) => { this.eFullWidthRowRight = eRow; }, (cellRenderer: ICellRendererComp) => { this.fullWidthRowComponentRight = cellRenderer; }, detailRow); } else { // otherwise we add to the fullWidth container as normal // let previousFullWidth = ensureDomOrder ? this.lastPlacedElements.eFullWidth : null; this.createFullWidthRowContainer(this.fullWidthContainerComp, null, null, type, name, (eRow: HTMLElement) => { this.eFullWidthRow = eRow; }, (cellRenderer: ICellRendererComp) => { this.fullWidthRowComponent = cellRenderer; }, detailRow ); } } private setAnimateFlags(animateIn: boolean): void { if (animateIn) { const oldRowTopExists = exists(this.rowNode.oldRowTop); // if the row had a previous position, we slide it in (animate row top) this.slideRowIn = oldRowTopExists; // if the row had no previous position, we fade it in (animate this.fadeRowIn = !oldRowTopExists; } else { this.slideRowIn = false; this.fadeRowIn = false; } } public isEditing(): boolean { return this.editingRow; } public stopRowEditing(cancel: boolean): void { this.stopEditing(cancel); } public isFullWidth(): boolean { return this.fullWidthRow; } public refreshFullWidth(): boolean { // returns 'true' if refresh succeeded const tryRefresh = (eRow: HTMLElement, cellComp: ICellRendererComp, pinned: string): boolean => { if (!eRow || !cellComp) { return true; } // no refresh needed // no refresh method present, so can't refresh, hard refresh needed if (!cellComp.refresh) { return false; } const params = this.createFullWidthParams(eRow, pinned); const refreshSucceeded = cellComp.refresh(params); return refreshSucceeded; }; const normalSuccess = tryRefresh(this.eFullWidthRow, this.fullWidthRowComponent, null); const bodySuccess = tryRefresh(this.eFullWidthRowBody, this.fullWidthRowComponentBody, null); const leftSuccess = tryRefresh(this.eFullWidthRowLeft, this.fullWidthRowComponentLeft, Constants.PINNED_LEFT); const rightSuccess = tryRefresh(this.eFullWidthRowRight, this.fullWidthRowComponentRight, Constants.PINNED_RIGHT); const allFullWidthRowsRefreshed = normalSuccess && bodySuccess && leftSuccess && rightSuccess; return allFullWidthRowsRefreshed; } private addListeners(): void { this.addManagedListener(this.rowNode, RowNode.EVENT_HEIGHT_CHANGED, this.onRowHeightChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_SELECTED, this.onRowSelected.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_INDEX_CHANGED, this.onRowIndexChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_TOP_CHANGED, this.onTopChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_EXPANDED_CHANGED, this.updateExpandedCss.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_HAS_CHILDREN_CHANGED, this.updateExpandedCss.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, this.onRowNodeDataChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, this.onRowNodeCellChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_HIGHLIGHT_CHANGED, this.onRowNodeHighlightChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_DRAGGING_CHANGED, this.onRowNodeDraggingChanged.bind(this)); this.addManagedListener(this.rowNode, RowNode.EVENT_UI_LEVEL_CHANGED, this.onUiLevelChanged.bind(this)); const eventService = this.beans.eventService; this.addManagedListener(eventService, Events.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED, this.onPaginationPixelOffsetChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_HEIGHT_SCALE_CHANGED, this.onTopChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_VIRTUAL_COLUMNS_CHANGED, this.onVirtualColumnsChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_COLUMN_RESIZED, this.onColumnResized.bind(this)); this.addManagedListener(eventService, Events.EVENT_CELL_FOCUSED, this.onCellFocusChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_PAGINATION_CHANGED, this.onPaginationChanged.bind(this)); this.addManagedListener(eventService, Events.EVENT_MODEL_UPDATED, this.onModelUpdated.bind(this)); this.addManagedListener(eventService, Events.EVENT_COLUMN_MOVED, this.onColumnMoved.bind(this)); this.addListenersForCellComps(); } private addListenersForCellComps(): void { this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_INDEX_CHANGED, () => { this.forEachCellComp(cellComp => cellComp.onRowIndexChanged()); }); this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, event => { this.forEachCellComp(cellComp => cellComp.onCellChanged(event)); }); } private onRowNodeDataChanged(event: DataChangedEvent): void { // if this is an update, we want to refresh, as this will allow the user to put in a transition // into the cellRenderer refresh method. otherwise this might be completely new data, in which case // we will want to completely replace the cells this.forEachCellComp(cellComp => cellComp.refreshCell({ suppressFlash: !event.update, newData: !event.update }) ); // check for selected also, as this could be after lazy loading of the row data, in which case // the id might of just gotten set inside the row and the row selected state may of changed // as a result. this is what happens when selected rows are loaded in virtual pagination. // - niall note - since moving to the stub component, this may no longer be true, as replacing // the stub component now replaces the entire row this.onRowSelected(); // as data has changed, then the style and class needs to be recomputed this.postProcessCss(); } private onRowNodeCellChanged(): void { // as data has changed, then the style and class needs to be recomputed this.postProcessCss(); } private postProcessCss(): void { this.postProcessStylesFromGridOptions(); this.postProcessClassesFromGridOptions(); this.postProcessRowClassRules(); this.postProcessRowDragging(); } private onRowNodeHighlightChanged(): void { const highlighted = this.rowNode.highlighted; this.eAllRowContainers.forEach(row => { removeCssClass(row, 'ag-row-highlight-above'); removeCssClass(row, 'ag-row-highlight-below'); if (highlighted) { addCssClass(row, 'ag-row-highlight-' + highlighted); } }); } private onRowNodeDraggingChanged(): void { this.postProcessRowDragging(); } private postProcessRowDragging(): void { const dragging = this.rowNode.dragging; this.eAllRowContainers.forEach(row => addOrRemoveCssClass(row, 'ag-row-dragging', dragging)); } private updateExpandedCss(): void { const expandable = this.rowNode.isExpandable(); const expanded = this.rowNode.expanded == true; this.eAllRowContainers.forEach(eRow => { addOrRemoveCssClass(eRow, 'ag-row-group', expandable); addOrRemoveCssClass(eRow, 'ag-row-group-expanded', expandable && expanded); addOrRemoveCssClass(eRow, 'ag-row-group-contracted', expandable && !expanded); setAriaExpanded(eRow, expandable && expanded); }); } private onDisplayedColumnsChanged(): void { if (this.fullWidthRow) { return; } this.refreshCells(); } private destroyFullWidthComponents(): void { this.fullWidthRowDestroyFuncs.forEach(f => f()); this.fullWidthRowDestroyFuncs = []; if (this.fullWidthRowComponent) { this.beans.detailRowCompCache.addOrDestroy(this.rowNode, null, this.fullWidthRowComponent); this.fullWidthRowComponent = null; } if (this.fullWidthRowComponentBody) { this.beans.detailRowCompCache.addOrDestroy(this.rowNode, null, this.fullWidthRowComponentBody); this.fullWidthRowComponentBody = null; } if (this.fullWidthRowComponentLeft) { this.beans.detailRowCompCache.addOrDestroy(this.rowNode, Constants.PINNED_LEFT, this.fullWidthRowComponentLeft); this.fullWidthRowComponentLeft = null; } if (this.fullWidthRowComponentRight) { this.beans.detailRowCompCache.addOrDestroy(this.rowNode, Constants.PINNED_RIGHT, this.fullWidthRowComponentRight); this.fullWidthRowComponentRight = null; } } private getContainerForCell(pinnedType: string): HTMLElement { switch (pinnedType) { case Constants.PINNED_LEFT: return this.ePinnedLeftRow; case Constants.PINNED_RIGHT: return this.ePinnedRightRow; default: return this.eBodyRow; } } private onVirtualColumnsChanged(): void { if (this.fullWidthRow) { return; } this.refreshCells(); } private onColumnResized(): void { if (this.fullWidthRow) { return; } this.refreshCells(); } private refreshCells() { if (!this.areAllContainersReady()) { this.refreshNeeded = true; return; } const suppressAnimationFrame = this.beans.gridOptionsWrapper.isSuppressAnimationFrame(); const skipAnimationFrame = suppressAnimationFrame || this.printLayout; if (skipAnimationFrame) { this.refreshCellsInAnimationFrame(); } else { if (this.columnRefreshPending) { return; } this.beans.taskQueue.createTask( this.refreshCellsInAnimationFrame.bind(this), this.rowNode.rowIndex, 'createTasksP1' ); } } private refreshCellsInAnimationFrame() { if (!this.active) { return; } this.columnRefreshPending = false; let centerCols: Column[]; let leftCols: Column[]; let rightCols: Column[]; if (this.printLayout) { centerCols = this.beans.columnController.getAllDisplayedColumns(); leftCols = []; rightCols = []; } else { centerCols = this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode); leftCols = this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode); rightCols = this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode); } this.insertCellsIntoContainer(this.eBodyRow, centerCols); this.insertCellsIntoContainer(this.ePinnedLeftRow, leftCols); this.insertCellsIntoContainer(this.ePinnedRightRow, rightCols); this.elementOrderChanged = false; const colIdsToRemove = Object.keys(this.cellComps); centerCols.forEach(col => removeFromArray(colIdsToRemove, col.getId())); leftCols.forEach(col => removeFromArray(colIdsToRemove, col.getId())); rightCols.forEach(col => removeFromArray(colIdsToRemove, col.getId())); // we never remove editing cells, as this would cause the cells to loose their values while editing // as the grid is scrolling horizontally. const eligibleToBeRemoved = colIdsToRemove.filter(this.isCellEligibleToBeRemoved.bind(this)); // remove old cells from gui, but we don't destroy them, we might use them again this.destroyCells(eligibleToBeRemoved); } private onColumnMoved() { this.elementOrderChanged = true; } private destroyCells(colIds: string[]): void { colIds.forEach((key: string) => { const cellComp = this.cellComps[key]; // could be old reference, ie removed cell if (missing(cellComp)) { return; } cellComp.detach(); cellComp.destroy(); this.cellComps[key] = null; }); } private isCellEligibleToBeRemoved(indexStr: string): boolean { const displayedColumns = this.beans.columnController.getAllDisplayedColumns(); const REMOVE_CELL = true; const KEEP_CELL = false; const renderedCell = this.cellComps[indexStr]; // always remove the cell if it's not rendered or if it's in the wrong pinned location if (!renderedCell || this.isCellInWrongRow(renderedCell)) { return REMOVE_CELL; } // we want to try and keep editing and focused cells const editing = renderedCell.isEditing(); const focused = this.beans.focusController.isCellFocused(renderedCell.getCellPosition()); const mightWantToKeepCell = editing || focused; if (mightWantToKeepCell) { const column = renderedCell.getColumn(); const cellStillDisplayed = displayedColumns.indexOf(column) >= 0; return cellStillDisplayed ? KEEP_CELL : REMOVE_CELL; } return REMOVE_CELL; } private ensureCellInCorrectContainer(cellComp: CellComp): void { // for print layout, we always put cells into centre, otherwise we put in correct pinned section if (this.printLayout) { return; } const element = cellComp.getGui(); const column = cellComp.getColumn(); const pinnedType = column.getPinned(); const eContainer = this.getContainerForCell(pinnedType); // if in wrong container, remove it const eOldContainer = cellComp.getParentRow(); const inWrongRow = eOldContainer !== eContainer; if (inWrongRow) { // take out from old row if (eOldContainer) { eOldContainer.removeChild(element); } eContainer.appendChild(element); cellComp.setParentRow(eContainer); this.elementOrderChanged = true; } } private isCellInWrongRow(cellComp: CellComp): boolean { const column = cellComp.getColumn(); const rowWeWant = this.getContainerForCell(column.getPinned()); const oldRow = cellComp.getParentRow(); // if in wrong container, remove it return oldRow !== rowWeWant; } private insertCellsIntoContainer(eRow: HTMLElement, cols: Column[]): void { if (!eRow) { return; } const cellTemplates: string[] = []; const newCellComps: CellComp[] = []; cols.forEach(col => { const colId = col.getId(); const existingCell = this.cellComps[colId]; // need to check the column is the same one, not a new column with the same ID if (existingCell && existingCell.getColumn() == col) { this.ensureCellInCorrectContainer(existingCell); } else { if (existingCell) { // here there is a col with the same id, so need to destroy the old cell first, // as the old column no longer exists. this happens often with pivoting, where // id's are pivot_1, pivot_2 etc, so common for new cols with same ID's this.destroyCells([colId]); } this.createNewCell(col, eRow, cellTemplates, newCellComps); } }); if (cellTemplates.length > 0) { appendHtml(eRow, cellTemplates.join('')); this.callAfterRowAttachedOnCells(newCellComps, eRow); } if (this.elementOrderChanged && this.beans.gridOptionsWrapper.isEnsureDomOrder()) { const correctChildOrder = cols.map(col => this.getCellForCol(col)); setDomChildOrder(eRow, correctChildOrder); } } private addDomData(eRowContainer: Element): void { const gow = this.beans.gridOptionsWrapper; gow.setDomData(eRowContainer, RowComp.DOM_DATA_KEY_RENDERED_ROW, this); this.addDestroyFunc(() => { gow.setDomData(eRowContainer, RowComp.DOM_DATA_KEY_RENDERED_ROW, null); } ); } private createNewCell(col: Column, eContainer: HTMLElement, cellTemplates: string[], newCellComps: CellComp[]): void { const newCellComp = new CellComp(this.scope, this.beans, col, this.rowNode, this, false, this.printLayout); const cellTemplate = newCellComp.getCreateTemplate(); cellTemplates.push(cellTemplate); newCellComps.push(newCellComp); this.cellComps[col.getId()] = newCellComp; newCellComp.setParentRow(eContainer); this.elementOrderChanged = true; } public onMouseEvent(eventName: string, mouseEvent: MouseEvent): void { switch (eventName) { case 'dblclick': this.onRowDblClick(mouseEvent); break; case 'click': this.onRowClick(mouseEvent); break; case 'mousedown': this.onRowMouseDown(mouseEvent); break; } } private createRowEvent(type: string, domEvent?: Event): RowEvent { return { type: type, node: this.rowNode, data: this.rowNode.data, rowIndex: this.rowNode.rowIndex, rowPinned: this.rowNode.rowPinned, context: this.beans.gridOptionsWrapper.getContext(), api: this.beans.gridOptionsWrapper.getApi(), columnApi: this.beans.gridOptionsWrapper.getColumnApi(), event: domEvent }; } private createRowEventWithSource(type: string, domEvent: Event): RowEvent { const event = this.createRowEvent(type, domEvent); // when first developing this, we included the rowComp in the event. // this seems very weird. so when introducing the event types, i left the 'source' // out of the type, and just include the source in the two places where this event // was fired (rowClicked and rowDoubleClicked). it doesn't make sense for any // users to be using this, as the rowComp isn't an object we expose, so would be // very surprising if a user was using it. (event as any).source = this; return event; } private onRowDblClick(mouseEvent: MouseEvent): void { if (isStopPropagationForAgGrid(mouseEvent)) { return; } const agEvent: RowDoubleClickedEvent = this.createRowEventWithSource(Events.EVENT_ROW_DOUBLE_CLICKED, mouseEvent); this.beans.eventService.dispatchEvent(agEvent); } private onRowMouseDown(mouseEvent: MouseEvent) { this.lastMouseDownOnDragger = isElementChildOfClass(mouseEvent.target as HTMLElement, 'ag-row-drag', 3); } public onRowClick(mouseEvent: MouseEvent) { const stop = isStopPropagationForAgGrid(mouseEvent) || this.lastMouseDownOnDragger; if (stop) { return; } const agEvent: RowClickedEvent = this.createRowEventWithSource(Events.EVENT_ROW_CLICKED, mouseEvent); this.beans.eventService.dispatchEvent(agEvent); // ctrlKey for windows, metaKey for Apple const multiSelectKeyPressed = mouseEvent.ctrlKey || mouseEvent.metaKey; const shiftKeyPressed = mouseEvent.shiftKey; // we do not allow selecting the group by clicking, when groupSelectChildren, as the logic to // handle this is broken. to observe, change the logic below and allow groups to be selected. // you will see the group gets selected, then all children get selected, then the grid unselects // the children (as the default behaviour when clicking is to unselect other rows) which results // in the group getting unselected (as all children are unselected). the correct thing would be // to change this, so that children of the selected group are not then subsequenly un-selected. const groupSelectsChildren = this.beans.gridOptionsWrapper.isGroupSelectsChildren(); if ( // we do not allow selecting groups by clicking (as the click here expands the group), or if it's a detail row, // so return if it's a group row (groupSelectsChildren && this.rowNode.group) || // this is needed so we don't unselect other rows when we click this row, eg if this row is not selectable, // and we click it, the selection should not change (ie any currently selected row should stay selected) !this.rowNode.selectable || // we also don't allow selection of pinned rows this.rowNode.rowPinned || // if no selection method enabled, do nothing !this.beans.gridOptionsWrapper.isRowSelection() || // if click selection suppressed, do nothing this.beans.gridOptionsWrapper.isSuppressRowClickSelection() ) { return; } const multiSelectOnClick = this.beans.gridOptionsWrapper.isRowMultiSelectWithClick(); const rowDeselectionWithCtrl = !this.beans.gridOptionsWrapper.isSuppressRowDeselection(); if (this.rowNode.isSelected()) { if (multiSelectOnClick) { this.rowNode.setSelectedParams({ newValue: false }); } else if (multiSelectKeyPressed) { if (rowDeselectionWithCtrl) { this.rowNode.setSelectedParams({ newValue: false }); } } else { // selected with no multi key, must make sure anything else is unselected this.rowNode.setSelectedParams({ newValue: !shiftKeyPressed, clearSelection: !shiftKeyPressed, rangeSelect: shiftKeyPressed }); } } else { const clearSelection = multiSelectOnClick ? false : !multiSelectKeyPressed; this.rowNode.setSelectedParams({ newValue: true, clearSelection: clearSelection, rangeSelect: shiftKeyPressed }); } } private createFullWidthRowContainer( rowContainerComp: RowContainerComponent, pinned: string, extraCssClass: string, cellRendererType: string, cellRendererName: string, eRowCallback: (eRow: HTMLElement) => void, cellRendererCallback: (comp: ICellRendererComp) => void, detailRow: boolean ): void { const rowTemplate = this.createTemplate('', extraCssClass); rowContainerComp.appendRowTemplate(rowTemplate, () => { const eRow: HTMLElement = rowContainerComp.getRowElement(this.getCompId()); const params = this.createFullWidthParams(eRow, pinned); const callback = (cellRenderer: ICellRendererComp) => { if (this.isAlive()) { const eGui = cellRenderer.getGui(); eRow.appendChild(eGui); if (detailRow) { this.setupDetailRowAutoHeight(eGui); } cellRendererCallback(cellRenderer); } else { this.beans.context.destroyBean(cellRenderer); } }; // if doing master detail, it's possible we have a cached row comp from last time detail was displayed const cachedRowComp = this.beans.detailRowCompCache.get(this.rowNode, pinned); if (cachedRowComp) { callback(cachedRowComp); } else { const res = this.beans.userComponentFactory.newFullWidthCellRenderer(params, cellRendererType, cellRendererName); if (!res) { const masterDetailModuleLoaded = ModuleRegistry.isRegistered(ModuleNames.MasterDetailModule); if (cellRendererName === 'agDetailCellRenderer' && !masterDetailModuleLoaded) { console.warn(`ag-Grid: cell renderer agDetailCellRenderer (for master detail) not found. Did you forget to include the master detail module?`); } else { console.error(`ag-Grid: fullWidthCellRenderer ${cellRendererName} not found`); } return; } res.then(callback); } this.afterRowAttached(rowContainerComp, eRow); eRowCallback(eRow); this.angular1Compile(eRow); }); } private setupDetailRowAutoHeight(eDetailGui: HTMLElement): void { if (!this.beans.gridOptionsWrapper.isDetailRowAutoHeight()) { return; } const checkRowSizeFunc = () => { const clientHeight = eDetailGui.clientHeight; // if the UI is not ready, the height can be 0, which we ignore, as otherwise a flicker will occur // as UI goes from the default height, to 0, then to the real height as UI becomes ready. this means // it's not possible for have 0 as auto-height, however this is an improbable use case, as even an // empty detail grid would still have some styling around it giving at least a few pixels. if (clientHeight != null && clientHeight > 0) { // we do the update in a timeout, to make sure we are not calling from inside the grid // doing another update const updateRowHeightFunc = () => { this.rowNode.setRowHeight(clientHeight); if (this.beans.clientSideRowModel) { this.beans.clientSideRowModel.onRowHeightChanged(); } else if (this.beans.serverSideRowModel) { this.beans.serverSideRowModel.onRowHeightChanged(); } }; this.beans.frameworkOverrides.setTimeout(updateRowHeightFunc, 0); } }; const resizeObserverDestroyFunc = this.beans.resizeObserverService.observeResize(eDetailGui, checkRowSizeFunc); this.fullWidthRowDestroyFuncs.push(resizeObserverDestroyFunc); checkRowSizeFunc(); } private angular1Compile(element: Element): void { if (!this.scope) { return; } this.beans.$compile(element)(this.scope); } private createFullWidthParams(eRow: HTMLElement, pinned: string): any { const params = { fullWidth: true, data: this.rowNode.data, node: this.rowNode, value: this.rowNode.key, $scope: this.scope ? this.scope : this.parentScope, $compile: this.beans.$compile, rowIndex: this.rowNode.rowIndex, api: this.beans.gridOptionsWrapper.getApi(), columnApi: this.beans.gridOptionsWrapper.getColumnApi(), context: this.beans.gridOptionsWrapper.getContext(), // these need to be taken out, as part of 'afterAttached' now eGridCell: eRow, eParentOfValue: eRow, pinned: pinned, addRenderedRowListener: this.addEventListener.bind(this) }; return params; } private getInitialRowClasses(extraCssClass: string): string[] { const params = { rowNode: this.rowNode, extraCssClass: extraCssClass, rowFocused: this.rowFocused, fadeRowIn: this.fadeRowIn, rowIsEven: this.rowIsEven, rowLevel: this.rowLevel, fullWidthRow: this.fullWidthRow, firstRowOnPage: this.isFirstRowOnPage(), lastRowOnPage: this.isLastRowOnPage(), printLayout: this.printLayout, expandable: this.rowNode.isExpandable(), scope: this.scope }; return this.beans.rowCssClassCalculator.getInitialRowClasses(params); } private onUiLevelChanged(): void { const newLevel = this.beans.rowCssClassCalculator.calculateRowLevel(this.rowNode); if (this.rowLevel != newLevel) { const classToAdd = 'ag-row-level-' + newLevel; const classToRemove = 'ag-row-level-' + this.rowLevel; this.eAllRowContainers.forEach((row) => { addCssClass(row, classToAdd); removeCssClass(row, classToRemove); }); } this.rowLevel = newLevel; } private isFirstRowOnPage(): boolean { return this.rowNode.rowIndex === this.beans.paginationProxy.getPageFirstRow(); } private isLastRowOnPage(): boolean { return this.rowNode.rowIndex === this.beans.paginationProxy.getPageLastRow(); } private onModelUpdated(): void { const newFirst = this.isFirstRowOnPage(); const newLast = this.isLastRowOnPage(); if (this.firstRowOnPage !== newFirst) { this.firstRowOnPage = newFirst; this.eAllRowContainers.forEach((row) => addOrRemoveCssClass(row, 'ag-row-first', newFirst)); } if (this.lastRowOnPage !== newLast) { this.lastRowOnPage = newLast; this.eAllRowContainers.forEach((row) => addOrRemoveCssClass(row, 'ag-row-last', newLast)); } } public stopEditing(cancel = false): void { this.forEachCellComp(renderedCell => { renderedCell.stopEditing(cancel); }); if (!this.editingRow) { return; } if (!cancel) { const event: RowValueChangedEvent = this.createRowEvent(Events.EVENT_ROW_VALUE_CHANGED); this.beans.eventService.dispatchEvent(event); } this.setEditingRow(false); } private setEditingRow(value: boolean): void { this.editingRow = value; this.eAllRowContainers.forEach(row => addOrRemoveCssClass(row, 'ag-row-editing', value)); const event: RowEvent = value ? this.createRowEvent(Events.EVENT_ROW_EDITING_STARTED) as RowEditingStartedEvent : this.createRowEvent(Events.EVENT_ROW_EDITING_STOPPED) as RowEditingStoppedEvent; this.beans.eventService.dispatchEvent(event); } public startRowEditing(keyPress: number | null = null, charPress: string | null = null, sourceRenderedCell: CellComp | null = null): void { // don't do it if already editing if (this.editingRow) { return; } this.forEachCellComp(renderedCell => { const cellStartedEdit = renderedCell === sourceRenderedCell; if (cellStartedEdit) { renderedCell.startEditingIfEnabled(keyPress, charPress, cellStartedEdit); } else { renderedCell.startEditingIfEnabled(null, null, cellStartedEdit); } }); this.setEditingRow(true); } public forEachCellComp(callback: (renderedCell: CellComp) => void): void { iterateObject(this.cellComps, (key: any, cellComp: CellComp) => { if (!cellComp) { return; } callback(cellComp); }); } private postProcessClassesFromGridOptions(): void { const cssClasses = this.beans.rowCssClassCalculator.processClassesFromGridOptions(this.rowNode); if (!cssClasses || !cssClasses.length) { return; } cssClasses.forEach(classStr => { this.eAllRowContainers.forEach(row => addCssClass(row, classStr)); }); } private postProcessRowClassRules(): void { this.beans.rowCssClassCalculator.processRowClassRules( this.rowNode, this.scope, (className: string) => { this.eAllRowContainers.forEach(row => addCssClass(row, className)); }, (className: string) => { this.eAllRowContainers.forEach(row => removeCssClass(row, className)); } ); } private preProcessStylesFromGridOptions(): string { const rowStyles = this.processStylesFromGridOptions(); return cssStyleObjectToMarkup(rowStyles); } private postProcessStylesFromGridOptions(): void { const rowStyles = this.processStylesFromGridOptions(); this.eAllRowContainers.forEach(row => addStylesToElement(row, rowStyles)); } private processStylesFromGridOptions(): any { // part 1 - rowStyle const rowStyle = this.beans.gridOptionsWrapper.getRowStyle(); if (rowStyle && typeof rowStyle === 'function') { console.warn('ag-Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead'); return; } // part 1 - rowStyleFunc const rowStyleFunc = this.beans.gridOptionsWrapper.getRowStyleFunc(); let rowStyleFuncResult: any; if (rowStyleFunc) { const params = { data: this.rowNode.data, node: this.rowNode, api: this.beans.gridOptionsWrapper.getApi(), context: this.beans.gridOptionsWrapper.getContext(), $scope: this.scope }; rowStyleFuncResult = rowStyleFunc(params); } return assign({}, rowStyle, rowStyleFuncResult); } private createCells(cols: Column[]): { template: string, cellComps: CellComp[]; } { const templateParts: string[] = []; const newCellComps: CellComp[] = []; cols.forEach(col => { const newCellComp = new CellComp(this.scope, this.beans, col, this.rowNode, this, false, this.printLayout); const cellTemplate = newCellComp.getCreateTemplate(); templateParts.push(cellTemplate); newCellComps.push(newCellComp); this.cellComps[col.getId()] = newCellComp; }); const templateAndComps = { template: templateParts.join(''), cellComps: newCellComps }; return templateAndComps; } private onRowSelected(): void { const selected = this.rowNode.isSelected(); this.eAllRowContainers.forEach((row) => { setAriaSelected(row, selected); addOrRemoveCssClass(row, 'ag-row-selected', selected); this.refreshAriaLabel(row, selected); }); } private refreshAriaLabel(node: HTMLElement, selected: boolean): void { if (selected && this.beans.gridOptionsWrapper.isSuppressRowDeselection()) { node.removeAttribute('aria-label'); return; } const translate = this.beans.gridOptionsWrapper.getLocaleTextFunc(); const label = translate( selected ? 'ariaRowDeselect' : 'ariaRowSelect', `Press SPACE to ${selected ? 'deselect' : 'select'} this row.` ); setAriaLabel(node, label); } // called: // + after row created for first time // + after horizontal scroll, so new cells due to column virtualisation private callAfterRowAttachedOnCells(newCellComps: CellComp[], eRow: HTMLElement): void { newCellComps.forEach(cellComp => { cellComp.setParentRow(eRow); cellComp.afterAttached(); // if we are editing the row, then the cell needs to turn // into edit mode if (this.editingRow) { cellComp.startEditingIfEnabled(); } }); } private afterRowAttached(rowContainerComp: RowContainerComponent, eRow: HTMLElement): void { this.addDomData(eRow); this.removeSecondPassFuncs.push(() => { rowContainerComp.removeRowElement(eRow); }); this.removeFirstPassFuncs.push(() => { if (exists(this.rowNode.rowTop)) { // the row top is updated anyway, however we set it here again // to something more reasonable for the animation - ie if the // row top is 10000px away, the row will flash out, so this // gives it a rounded value, so row animates out more slowly const rowTop = this.roundRowTopToBounds(this.rowNode.rowTop); this.setRowTop(rowTop); } else { addCssClass(eRow, 'ag-opacity-zero'); } }); this.eAllRowContainers.push(eRow); // adding hover functionality adds listener to this row, so we // do it lazily in an animation frame if (this.useAnimationFrameForCreate) { this.beans.taskQueue.createTask( this.addHoverFunctionality.bind(this, eRow), this.rowNode.rowIndex, 'createTasksP2' ); } else { this.addHoverFunctionality(eRow); } } private addHoverFunctionality(eRow: HTMLElement): void { // because we use animation frames to do this, it's possible the row no longer exists // by the time we get to add it if (!this.active) { return; } // because mouseenter and mouseleave do not propagate, we cannot listen on the gridPanel // like we do for all the other mouse events. // because of the pinning, we cannot simply add / remove the class based on the eRow. we // have to check all eRow's (body & pinned). so the trick is if any of the rows gets a // mouse hover, it sets such in the rowNode, and then all three reflect the change as // all are listening for event on the row node. // step 1 - add listener, to set flag on row node this.addManagedListener(eRow, 'mouseenter', () => this.rowNode.onMouseEnter()); this.addManagedListener(eRow, 'mouseleave', () => this.rowNode.onMouseLeave()); // step 2 - listen for changes on row node (which any eRow can trigger) this.addManagedListener(this.rowNode, RowNode.EVENT_MOUSE_ENTER, () => { // if hover turned off, we don't add the class. we do this here so that if the application // toggles this property mid way, we remove the hover form the last row, but we stop // adding hovers from that point onwards. if (!this.beans.gridOptionsWrapper.isSuppressRowHoverHighlight()) { addCssClass(eRow, 'ag-row-hover'); } }); this.addManagedListener(this.rowNode, RowNode.EVENT_MOUSE_LEAVE, () => { removeCssClass(eRow, 'ag-row-hover'); }); } // for animation, we don't want to animate entry or exit to a very far away pixel, // otherwise the row would move so fast, it would appear to disappear. so this method // moves the row closer to the viewport if it is far away, so the row slide in / out // at a speed the user can see. private roundRowTopToBounds(rowTop: number): number { const range = this.beans.gridPanel.getVScrollPosition(); const minPixel = this.applyPaginationOffset(range.top, true) - 100; const maxPixel = this.applyPaginationOffset(range.bottom, true) + 100; return Math.min(Math.max(minPixel, rowTop), maxPixel); } protected getFrameworkOverrides(): IFrameworkOverrides { return this.beans.frameworkOverrides; } private onRowHeightChanged(): void { // check for exists first - if the user is resetting the row height, then // it will be null (or undefined) momentarily until the next time the flatten // stage is called where the row will then update again with a new height if (exists(this.rowNode.rowHeight)) { const heightPx = `${this.rowNode.rowHeight}px`; this.eAllRowContainers.forEach(row => row.style.height = heightPx); } } public addEventListener(eventType: string, listener: Function): void { if (eventType === 'renderedRowRemoved' || eventType === 'rowRemoved') { eventType = Events.EVENT_VIRTUAL_ROW_REMOVED; console.warn('ag-Grid: Since version 11, event renderedRowRemoved is now called ' + Events.EVENT_VIRTUAL_ROW_REMOVED); } super.addEventListener(eventType, listener); } public removeEventListener(eventType: string, listener: Function): void { if (eventType === 'renderedRowRemoved' || eventType === 'rowRemoved') { eventType = Events.EVENT_VIRTUAL_ROW_REMOVED; console.warn('ag-Grid: Since version 11, event renderedRowRemoved and rowRemoved is now called ' + Events.EVENT_VIRTUAL_ROW_REMOVED); } super.removeEventListener(eventType, listener); } // note - this is NOT called by context, as we don't wire / unwire the CellComp for performance reasons. public destroy(animate = false): void { this.active = false; // why do we have this method? shouldn't everything below be added as a destroy func beside // the corresponding create logic? this.destroyFullWidthComponents(); if (animate) { this.removeFirstPassFuncs.forEach(func => func()); this.removeSecondPassFuncs.push(this.destroyContainingCells.bind(this)); } else { this.destroyContainingCells(); // we are not animating, so execute the second stage of removal now. // we call getAndClear, so that they are only called once const delayedDestroyFunctions = this.getAndClearDelayedDestroyFunctions(); delayedDestroyFunctions.forEach(func => func()); } const event: VirtualRowRemovedEvent = this.createRowEvent(Events.EVENT_VIRTUAL_ROW_REMOVED); this.dispatchEvent(event); this.beans.eventService.dispatchEvent(event); super.destroy(); } private destroyContainingCells(): void { const cellsToDestroy = Object.keys(this.cellComps); this.destroyCells(cellsToDestroy); } // we clear so that the functions are never executed twice public getAndClearDelayedDestroyFunctions(): Function[] { const result = this.removeSecondPassFuncs; this.removeSecondPassFuncs = []; return result; } private onCellFocusChanged(): void { const rowFocused = this.beans.focusController.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned); if (rowFocused !== this.rowFocused) { this.eAllRowContainers.forEach(row => addOrRemoveCssClass(row, 'ag-row-focus', rowFocused)); this.eAllRowContainers.forEach(row => addOrRemoveCssClass(row, 'ag-row-no-focus', !rowFocused)); this.rowFocused = rowFocused; } // if we are editing, then moving the focus out of a row will stop editing if (!rowFocused && this.editingRow) { this.stopEditing(false); } } private onPaginationChanged(): void { const currentPage = this.beans.paginationProxy.getCurrentPage(); // it is possible this row is in the new page, but the page number has changed, which means // it needs to reposition itself relative to the new page if (this.paginationPage !== currentPage) { this.paginationPage = currentPage; this.onTopChanged(); } } private onTopChanged(): void { this.setRowTop(this.rowNode.rowTop); } private onPaginationPixelOffsetChanged(): void { // the pixel offset is used when calculating rowTop to set on the row DIV this.onTopChanged(); } // applies pagination offset, eg if on second page, and page height is 500px, then removes // 500px from the top position, so a row with rowTop 600px is displayed at location 100px. // reverse will take the offset away rather than add. private applyPaginationOffset(topPx: number, reverse = false): number { if (this.rowNode.isRowPinned()) { return topPx; } const pixelOffset = this.beans.paginationProxy.getPixelOffset(); const multiplier = reverse ? 1 : -1; return topPx + (pixelOffset * multiplier); } private setRowTop(pixels: number): void { // print layout uses normal flow layout for row positioning if (this.printLayout) { return; } // need to make sure rowTop is not null, as this can happen if the node was once // visible (ie parent group was expanded) but is now not visible if (exists(pixels)) { const afterPaginationPixels = this.applyPaginationOffset(pixels); const afterScalingPixels = this.rowNode.isRowPinned() ? afterPaginationPixels : this.beans.maxDivHeightScaler.getRealPixelPosition(afterPaginationPixels); const topPx = `${afterScalingPixels}px`; if (this.beans.gridOptionsWrapper.isSuppressRowTransform()) { this.eAllRowContainers.forEach(row => row.style.top = topPx); } else { this.eAllRowContainers.forEach(row => row.style.transform = `translateY(${topPx})`); } } } // we clear so that the functions are never executed twice public getAndClearNextVMTurnFunctions(): Function[] { const result = this.createSecondPassFuncs; this.createSecondPassFuncs = []; return result; } public getRowNode(): RowNode { return this.rowNode; } public getRenderedCellForColumn(column: Column): CellComp | undefined { const cellComp = this.cellComps[column.getColId()]; if (cellComp) { return cellComp; } const spanList = Object.keys(this.cellComps) .map(name => this.cellComps[name]) .filter(cmp => cmp && cmp.getColSpanningList().indexOf(column) !== -1); return spanList.length ? spanList[0] : undefined; } private onRowIndexChanged(): void { // we only bother updating if the rowIndex is present. if it is not present, it means this row // is child of a group node, and the group node was closed, it's the only way to have no row index. // when this happens, row is about to be de-rendered, so we don't care, rowComp is about to die! if (this.rowNode.rowIndex != null) { this.onCellFocusChanged(); this.updateRowIndexes(); } } private updateRowIndexes(): void { const rowIndexStr = this.rowNode.getRowIndexString(); const rowIsEven = this.rowNode.rowIndex % 2 === 0; const rowIsEvenChanged = this.rowIsEven !== rowIsEven; const headerRowCount = this.beans.headerNavigationService.getHeaderRowCount(); if (rowIsEvenChanged) { this.rowIsEven = rowIsEven; } this.eAllRowContainers.forEach(eRow => { eRow.setAttribute('row-index', rowIndexStr); setAriaRowIndex(eRow, headerRowCount + this.rowNode.rowIndex + 1); if (!rowIsEvenChanged) { return; } addOrRemoveCssClass(eRow, 'ag-row-even', rowIsEven); addOrRemoveCssClass(eRow, 'ag-row-odd', !rowIsEven); }); } public ensureDomOrder(): void { const sides = [ { el: this.getBodyRowElement(), ct: this.bodyContainerComp }, { el: this.getPinnedLeftRowElement(), ct: this.pinnedLeftContainerComp }, { el: this.getPinnedRightRowElement(), ct: this.pinnedRightContainerComp }, { el: this.getFullWidthRowElement(), ct: this.fullWidthContainerComp } ]; sides.forEach(side => { if (!side.el) { return; } side.ct.ensureDomOrder(side.el); }); } // returns the pinned left container, either the normal one, or the embedded full with one if exists public getPinnedLeftRowElement(): HTMLElement { return this.ePinnedLeftRow ? this.ePinnedLeftRow : this.eFullWidthRowLeft; } // returns the pinned right container, either the normal one, or the embedded full with one if exists public getPinnedRightRowElement(): HTMLElement { return this.ePinnedRightRow ? this.ePinnedRightRow : this.eFullWidthRowRight; } // returns the body container, either the normal one, or the embedded full with one if exists public getBodyRowElement(): HTMLElement { return this.eBodyRow ? this.eBodyRow : this.eFullWidthRowBody; } // returns the full width container public getFullWidthRowElement(): HTMLElement { return this.eFullWidthRow; } }
jenkins-sigaut/ag-grid
charts-packages/ag-charts-community/dist/es6/main.d.ts
export * from "./caption"; export * from "./chart/axis/numberAxis"; export * from "./chart/axis/categoryAxis"; export * from "./chart/axis/groupedCategoryAxis"; export * from "./chart/axis/timeAxis"; export * from "./chart/cartesianChart"; export * from "./chart/chart"; export * from "./chart/chartAxis"; export * from "./chart/groupedCategoryChart"; export * from "./chart/polarChart"; export * from "./chart/marker/marker"; export * from "./chart/legend"; export * from "./chart/series/cartesian/areaSeries"; export * from "./chart/series/cartesian/barSeries"; export * from "./chart/series/cartesian/lineSeries"; export * from "./chart/series/cartesian/scatterSeries"; export * from "./chart/series/cartesian/histogramSeries"; export * from "./chart/series/polar/pieSeries"; export * from "./scale/bandScale"; export * from "./scale/linearScale"; export * from "./scene/clipRect"; export * from "./scene/dropShadow"; export * from "./scene/group"; export * from "./scene/scene"; export * from "./scene/shape/arc"; export * from "./scene/shape/line"; export * from "./scene/shape/path"; export * from "./scene/shape/rect"; export * from "./scene/shape/sector"; export * from "./scene/shape/shape"; export * from "./util/angle"; export * from "./util/array"; export * from "./util/padding"; export declare const time: { millisecond: import("./util/time/interval").CountableTimeInterval; second: import("./util/time/interval").CountableTimeInterval; minute: import("./util/time/interval").CountableTimeInterval; hour: import("./util/time/interval").CountableTimeInterval; day: import("./util/time/interval").CountableTimeInterval; sunday: import("./util/time/interval").CountableTimeInterval; monday: import("./util/time/interval").CountableTimeInterval; tuesday: import("./util/time/interval").CountableTimeInterval; wednesday: import("./util/time/interval").CountableTimeInterval; thursday: import("./util/time/interval").CountableTimeInterval; friday: import("./util/time/interval").CountableTimeInterval; saturday: import("./util/time/interval").CountableTimeInterval; month: import("./util/time/interval").CountableTimeInterval; year: import("./util/time/interval").CountableTimeInterval; utcMinute: import("./util/time/interval").CountableTimeInterval; utcHour: import("./util/time/interval").CountableTimeInterval; utcDay: import("./util/time/interval").CountableTimeInterval; utcMonth: import("./util/time/interval").CountableTimeInterval; utcYear: import("./util/time/interval").CountableTimeInterval; }; export * from "./chart/agChartOptions"; export * from "./chart/agChart"; export * from "./chart/themes/chartTheme";
jenkins-sigaut/ag-grid
grid-packages/ag-grid-enterprise/dist/lib/setFilter/setValueModel.d.ts
<filename>grid-packages/ag-grid-enterprise/dist/lib/setFilter/setValueModel.d.ts import { ISetFilterParams, AgPromise, ValueFormatterService, IEventEmitter } from 'ag-grid-community'; import { ISetFilterLocaleText } from './localeText'; export declare enum SetFilterModelValuesType { PROVIDED_LIST = 0, PROVIDED_CALLBACK = 1, TAKEN_FROM_GRID_VALUES = 2 } export declare class SetValueModel implements IEventEmitter { private readonly filterParams; private readonly colDef; private readonly column; private readonly doesRowPassOtherFilters; private readonly suppressSorting; private readonly setIsLoading; private readonly valueFormatterService; private readonly translate; static EVENT_AVAILABLE_VALUES_CHANGED: string; private readonly localEventService; private readonly formatter; private readonly clientSideValuesExtractor; private valuesType; private miniFilterText; /** Values provided to the filter for use. */ private providedValues; /** Values can be loaded asynchronously, so wait on this promise if you need to ensure values have been loaded. */ private allValuesPromise; /** All possible values for the filter, sorted if required. */ private allValues; /** Remaining values when filters from other columns have been applied. */ private availableValues; /** All values that are currently displayed, after the mini-filter has been applied. */ private displayedValues; /** Values that have been selected for this filter. */ private selectedValues; constructor(rowModel: IRowModel, valueGetter: (node: RowNode) => any, filterParams: ISetFilterParams, colDef: ColDef, column: Column, doesRowPassOtherFilters: (node: RowNode) => boolean, suppressSorting: boolean, setIsLoading: (loading: boolean) => void, valueFormatterService: ValueFormatterService, translate: (key: keyof ISetFilterLocaleText) => string); addEventListener(eventType: string, listener: Function, async?: boolean): void; removeEventListener(eventType: string, listener: Function, async?: boolean): void; /** * Re-fetches the values used in the filter from the value source. * If keepSelection is false, the filter selection will be reset to everything selected, * otherwise the current selection will be preserved. */ refreshValues(keepSelection?: boolean): AgPromise<void>; /** * Overrides the current values being used for the set filter. * If keepSelection is false, the filter selection will be reset to everything selected, * otherwise the current selection will be preserved. */ overrideValues(valuesToUse: (string | null)[], keepSelection?: boolean): AgPromise<void>; refreshAfterAnyFilterChanged(): AgPromise<void>; private updateAllValues; setValuesType(value: SetFilterModelValuesType): void; getValuesType(): SetFilterModelValuesType; isValueAvailable(value: string): boolean; private showAvailableOnly; private updateAvailableValues; private sortValues; private getValuesFromRows; /** Sets mini filter value. Returns true if it changed from last value, otherwise false. */ setMiniFilter(value?: string): boolean; getMiniFilter(): string; private updateDisplayedValues; getDisplayedValueCount(): number; getDisplayedValue(index: any): string; hasSelections(): boolean; getUniqueValueCount(): number; getUniqueValue(index: any): string | null; getValues(): string[]; selectAllMatchingMiniFilter(clearExistingSelection?: boolean): void; deselectAllMatchingMiniFilter(): void; selectValue(value: string): void; deselectValue(value: string): void; isValueSelected(value: string): boolean; isEverythingVisibleSelected(): boolean; isNothingVisibleSelected(): boolean; getModel(): (string | null)[] | null; setModel(model: (string | null)[] | null): AgPromise<void>; private resetSelectionState; }
jenkins-sigaut/ag-grid
enterprise-modules/server-side-row-model/dist/es6/serverSideRowModel/serverSideRowModel.d.ts
import { BeanStub, Column, ColumnVO, IServerSideDatasource, IServerSideRowModel, IServerSideStore, NumberSequence, RowBounds, RowNode, StoreRefreshAfterParams, RefreshStoreParams, ServerSideStoreState } from "@ag-grid-community/core"; export interface SSRMParams { sortModel: any; filterModel: any; lastAccessedSequence: NumberSequence; dynamicRowHeight: boolean; rowGroupCols: ColumnVO[]; valueCols: ColumnVO[]; pivotCols: ColumnVO[]; pivotMode: boolean; datasource?: IServerSideDatasource; } export declare class ServerSideRowModel extends BeanStub implements IServerSideRowModel { private gridOptionsWrapper; private columnController; private filterManager; private sortController; private gridApi; private columnApi; private rowRenderer; private sortListener; private nodeManager; private storeFactory; private rootNode; private datasource; private storeParams; private pauseStoreUpdateListening; private logger; ensureRowHeightsValid(startPixel: number, endPixel: number, startLimitIndex: number, endLimitIndex: number): boolean; private postConstruct; start(): void; private destroyDatasource; private setBeans; applyTransaction(rowDataTransaction: RowDataTransaction, route: string[]): void; private addEventListeners; setDatasource(datasource: IServerSideDatasource): void; isLastRowFound(): boolean; private onColumnEverything; private destroyRootStore; refreshAfterSort(newSortModel: any, params: StoreRefreshAfterParams): void; resetRootStore(): void; columnsToValueObjects(columns: Column[]): ColumnVO[]; private createStoreParams; getParams(): SSRMParams; private dispatchModelUpdated; private onStoreUpdated; onRowHeightChanged(): void; updateRowIndexesAndBounds(): void; retryLoads(): void; getRow(index: number): RowNode | null; expandAll(value: boolean): void; refreshAfterFilter(newFilterModel: any, params: StoreRefreshAfterParams): void; getRootStore(): IServerSideStore | undefined; getRowCount(): number; getTopLevelRowCount(): number; getTopLevelRowDisplayedIndex(topLevelIndex: number): number; getRowBounds(index: number): RowBounds; getRowIndexAtPixel(pixel: number): number; getCurrentPageHeight(): number; isEmpty(): boolean; isRowsToRender(): boolean; getType(): string; forEachNode(callback: (rowNode: RowNode, index: number) => void): void; executeOnStore(route: string[], callback: (cache: IServerSideStore) => void): void; refreshStore(params?: RefreshStoreParams): void; getStoreState(): ServerSideStoreState[]; getNodesInRangeForSelection(firstInRange: RowNode, lastInRange: RowNode): RowNode[]; getRowNode(id: string): RowNode | null; getBlockState(): any; isRowPresent(rowNode: RowNode): boolean; private extractSortModel; private isSortingWithValueColumn; private isSortingWithSecondaryColumn; private cacheExists; private createDetailNode; isLoading(): boolean; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/headerRendering/header/abstractHeaderWrapper.d.ts
<reponame>jenkins-sigaut/ag-grid // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { ColumnGroup } from "../../entities/columnGroup"; import { Column } from "../../entities/column"; import { ManagedFocusComponent } from "../../widgets/managedFocusComponent"; export declare abstract class AbstractHeaderWrapper extends ManagedFocusComponent { protected abstract readonly column: Column | ColumnGroup; protected abstract readonly pinned: string; protected abstract onFocusIn(e: FocusEvent): void; protected shouldStopEventPropagation(e: KeyboardEvent): boolean; getColumn(): Column | ColumnGroup; getPinned(): string; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/interfaces/iCsvCreator.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { CsvExportParams } from "./exportParams"; export interface ICsvCreator { getDataAsCsv(params?: CsvExportParams): string; exportDataAsCsv(params?: CsvExportParams): string; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/rendering/maxDivHeightScaler.d.ts
<filename>community-modules/core/dist/es6/rendering/maxDivHeightScaler.d.ts<gh_stars>0 // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { BeanStub } from "../context/beanStub"; import { GridPanel } from "../gridPanel/gridPanel"; /** * This class solves the 'max height' problem, where the user might want to show more data than * the max div height actually allows. */ export declare class MaxDivHeightScaler extends BeanStub { private gridPanel; private maxDivHeight; private scaling; private modelHeight; private uiContainerHeight; private pixelsToShave; private offset; private scrollY; private uiBodyHeight; private maxScrollY; private postConstruct; registerGridComp(gridPanel: GridPanel): void; isScaling(): boolean; getOffset(): number; updateOffset(): void; private calculateOffset; private clearOffset; private setOffset; setModelHeight(modelHeight: number): void; getUiContainerHeight(): number; getRealPixelPosition(modelPixel: number): number; private getUiBodyHeight; getScrollPositionForPixel(rowTop: number): number; }
jenkins-sigaut/ag-grid
community-modules/infinite-row-model/src/infiniteRowModel/infiniteBlock.ts
<gh_stars>0 import { _, Autowired, IGetRowsParams, NumberSequence, PostConstruct, PreDestroy, RowNode, Autowired, PostConstruct, IGetRowsParams, IEventEmitter, RowNodeBlock, RowRenderer, _ } from "@ag-grid-community/core"; import { InfiniteCacheParams } from "./infiniteCache"; export class InfiniteBlock extends RowNodeBlock implements IEventEmitter { @Autowired('rowRenderer') private rowRenderer: RowRenderer; private cacheParams: InfiniteCacheParams; constructor(pageNumber: number, params: InfiniteCacheParams) { super(pageNumber, params); this.cacheParams = params; } public getDisplayIndexStart(): number { return this.getBlockNumber() * this.cacheParams.blockSize; } // this is an estimate, as the last block will probably only be partially full. however // this method is used to know if this block is been rendered, before destroying, so // and this estimate works in that use case. public getDisplayIndexEnd(): number { return this.getDisplayIndexStart() + this.cacheParams.blockSize; } protected createBlankRowNode(rowIndex: number): RowNode { const rowNode = super.createBlankRowNode(); rowNode.uiLevel = 0; this.setIndexAndTopOnRowNode(rowNode, rowIndex); return rowNode; } protected setDataAndId(rowNode: RowNode, data: any, index: number): void { if (_.exists(data)) { // this means if the user is not providing id's we just use the // index for the row. this will allow selection to work (that is based // on index) as long user is not inserting or deleting rows, // or wanting to keep selection between server side sorting or filtering rowNode.setDataAndId(data, index.toString()); } else { rowNode.setDataAndId(undefined, undefined); } } public setRowNode(rowIndex: number, rowNode: RowNode): void { super.setRowNode(rowIndex, rowNode); this.setIndexAndTopOnRowNode(rowNode, rowIndex); } // no need for @postConstruct, as attached to parent protected init(): void { super.init(); } public getNodeIdPrefix(): string { return null; } public getRow(displayIndex: number): RowNode { return this.getRowUsingLocalIndex(displayIndex); } protected processServerFail(): void { // todo - this method has better handling in SSRM } protected createLoadParams(): any { // PROBLEM . . . . when the user sets sort via colDef.sort, then this code // is executing before the sort is set up, so server is not getting the sort // model. need to change with regards order - so the server side request is // AFTER thus it gets the right sort model. const params: IGetRowsParams = { startRow: this.getStartRow(), endRow: this.getEndRow(), successCallback: this.pageLoaded.bind(this, this.getVersion()), failCallback: this.pageLoadFailed.bind(this, this.getVersion()), sortModel: this.params.sortModel, filterModel: this.params.filterModel, context: this.gridOptionsWrapper.getContext() }; public forEachNode(callback: (rowNode: RowNode, index: number) => void, sequence: NumberSequence, rowCount: number): void { this.rowNodes.forEach((rowNode: RowNode, index: number) => { const rowIndex = this.startRow + index; if (rowIndex < rowCount) { callback(rowNode, sequence.next()); } }); } public getLastAccessed(): number { return this.lastAccessed; } public getRow(rowIndex: number, dontTouchLastAccessed = false): RowNode { if (!dontTouchLastAccessed) { this.lastAccessed = this.params.lastAccessedSequence.next(); } const localIndex = rowIndex - this.startRow; return this.rowNodes[localIndex]; } public getStartRow(): number { return this.startRow; } public getEndRow(): number { return this.endRow; } // creates empty row nodes, data is missing as not loaded yet protected createRowNodes(): void { this.rowNodes = []; for (let i = 0; i < this.params.blockSize!; i++) { const rowIndex = this.startRow + i; const rowNode = this.getContext().createBean(new RowNode()); rowNode.setRowHeight(this.params.rowHeight); rowNode.uiLevel = 0; rowNode.setRowIndex(rowIndex); rowNode.rowTop = this.params.rowHeight * rowIndex; this.rowNodes.push(rowNode); } } protected processServerResult(params: LoadSuccessParams): void { const rowNodesToRefresh: RowNode[] = []; this.rowNodes.forEach((rowNode: RowNode, index: number) => { const data = params.rowData ? params.rowData[index] : undefined; if (rowNode.stub) { rowNodesToRefresh.push(rowNode); } this.setDataAndId(rowNode, data, this.startRow + index); }); if (rowNodesToRefresh.length > 0) { this.rowRenderer.redrawRows(rowNodesToRefresh); } const finalRowCount = params.rowCount != null && params.rowCount >= 0 ? params.rowCount : undefined; this.parentCache.pageLoaded(this, finalRowCount); } @PreDestroy private destroyRowNodes(): void { this.rowNodes.forEach(rowNode => { // this is needed, so row render knows to fade out the row, otherwise it // sees row top is present, and thinks the row should be shown. maybe // rowNode should have a flag on whether it is visible??? rowNode.clearRowTop(); }); } }
jenkins-sigaut/ag-grid
enterprise-modules/charts/src/charts/chartComp/titleEdit.ts
import {_, Autowired, Component, PostConstruct} from "@ag-grid-community/core"; import {ChartMenu} from "./menu/chartMenu"; import {Chart} from "ag-charts-community"; import {ChartTranslator} from "./chartTranslator"; import {ChartProxy} from "./chartProxies/chartProxy"; type BBox = { x: number; y: number; width: number; height: number }; export class TitleEdit extends Component { private static TEMPLATE = /* html */ `<input class="ag-chart-title-edit" style="padding:0; border:none; border-radius: 0; min-height: 0; text-align: center;" /> `; @Autowired('chartTranslator') private chartTranslator: ChartTranslator; private chartProxy: ChartProxy<Chart, any>; private destroyableChartListeners: (() => void)[]; constructor(private readonly chartMenu: ChartMenu) { super(TitleEdit.TEMPLATE); } @PostConstruct public init(): void { this.addManagedListener(this.getGui(), 'keypress', (e: KeyboardEvent) => { if (e.key === 'Enter') { this.endEditing(); } }); this.addManagedListener(this.getGui(), 'blur', this.endEditing.bind(this)); } /* should be called when the containing component changes to a new chart proxy */ public setChartProxy(chartProxy: ChartProxy<Chart, any>) { if (this.chartProxy) { for (let i = 0; i++; i < this.destroyableChartListeners.length) { this.destroyableChartListeners[i](); } this.destroyableChartListeners = []; } this.chartProxy = chartProxy; const chart = this.chartProxy.getChart(); const canvas = chart.scene.canvas.element; const destroyDbleClickListener = this.addManagedListener(canvas, 'dblclick', event => { const { title } = chart; if (title && title.node.containsPoint(event.offsetX, event.offsetY)) { const bbox = title.node.computeBBox(); const xy = title.node.inverseTransformPoint(bbox.x, bbox.y); this.startEditing({ ...bbox, ...xy }); } }); const destroyMouseMoveListener = this.addManagedListener(canvas, 'mousemove', event => { const { title } = chart; const inTitle = title && title.node.containsPoint(event.offsetX, event.offsetY); canvas.style.cursor = inTitle ? 'pointer' : ''; }); this.destroyableChartListeners = [ destroyDbleClickListener, destroyMouseMoveListener ]; } private startEditing(titleBBox: BBox): void { if (this.chartMenu && this.chartMenu.isVisible()) { // currently we ignore requests to edit the chart title while the chart menu is showing // because the click to edit the chart will also close the chart menu, making the position // of the title change. return; } const minimumTargetInputWidth: number = 300; const maximumInputWidth: number = this.chartProxy.getChart().width; const inputWidth = Math.max(Math.min(titleBBox.width + 20, maximumInputWidth), minimumTargetInputWidth); const inputElement = this.getGui() as HTMLInputElement; _.addCssClass(inputElement, 'currently-editing'); const inputStyle = inputElement.style; // match style of input to title that we're editing inputStyle.fontFamily = this.chartProxy.getTitleOption('fontFamily'); inputStyle.fontWeight = this.chartProxy.getTitleOption('fontWeight'); inputStyle.fontStyle = this.chartProxy.getTitleOption('fontStyle'); inputStyle.fontSize = this.chartProxy.getTitleOption('fontSize') + 'px'; inputStyle.color = this.chartProxy.getTitleOption('color'); // populate the input with the title, unless the title is the placeholder: const oldTitle = this.chartProxy.getTitleOption('text'); const inputValue = oldTitle === this.chartTranslator.translate('titlePlaceholder') ? '' : oldTitle; inputElement.value = inputValue; const inputRect = inputElement.getBoundingClientRect(); inputStyle.left = Math.round(titleBBox.x + titleBBox.width / 2 - inputWidth / 2) + 'px'; inputStyle.top = Math.round(titleBBox.y + titleBBox.height / 2 - inputRect.height / 2) + 'px'; inputStyle.width = Math.round(inputWidth) + 'px'; inputElement.focus(); } private endEditing(): void { const value = (this.getGui() as HTMLInputElement).value; this.chartProxy.setTitleOption('text', value); this.eventService.dispatchEvent({'type': 'chartTitleEdit'}); _.removeCssClass(this.getGui(), 'currently-editing'); } }
jenkins-sigaut/ag-grid
enterprise-modules/clipboard/dist/es6/clipboard/clipboardService.d.ts
<reponame>jenkins-sigaut/ag-grid<filename>enterprise-modules/clipboard/dist/es6/clipboard/clipboardService.d.ts import { BeanStub, CellPositionUtils, Column, GridCore, IClipboardService, RowPositionUtils } from "@ag-grid-community/core"; export declare class ClipboardService extends BeanStub implements IClipboardService { private csvCreator; private loggerFactory; private selectionController; private rangeController; private rowModel; private valueService; private focusController; private rowRenderer; private columnController; private cellNavigationService; private columnApi; private gridApi; cellPositionUtils: CellPositionUtils; rowPositionUtils: RowPositionUtils; private clientSideRowModel; private logger; private gridCore; registerGridCore(gridCore: GridCore): void; private init; pasteFromClipboard(): void; private processClipboardData; private doPasteOperation; private pasteIntoActiveRange; private pasteStartingFromFocusedCell; private hasOnlyOneValueToPaste; copyRangeDown(): void; private removeLastLineIfBlank; private fireRowChanged; private pasteMultipleValues; private updateCellValue; copyToClipboard(includeHeaders?: boolean): void; private iterateActiveRanges; private iterateActiveRange; copySelectedRangeToClipboard(includeHeaders?: boolean): void; private copyFocusedCellToClipboard; private dispatchFlashCells; private processCell; private processHeader; copySelectedRowsToClipboard(includeHeaders?: boolean, columnKeys?: (string | Column)[]): void; private copyDataToClipboard; private executeOnTempElement; private getRangeSize; }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/utils/promise.ts
<reponame>jenkins-sigaut/ag-grid import { forEach } from './array'; export type ResolveAndRejectCallback<T> = (resolve: (value: T) => void, reject: (params: any) => void) => void; export enum AgPromiseStatus { IN_PROGRESS, RESOLVED } export class AgPromise<T> { private status: AgPromiseStatus = AgPromiseStatus.IN_PROGRESS; private resolution: T | null = null; private waiters: ((value: T) => void)[] = []; static all<T>(promises: AgPromise<T | null>[]): AgPromise<(T | null)[]> { return new AgPromise(resolve => { let remainingToResolve = promises.length; const combinedValues = new Array<T>(remainingToResolve); forEach(promises, (promise, index) => { promise.then(value => { combinedValues[index] = value; remainingToResolve--; if (remainingToResolve === 0) { resolve(combinedValues); } }); }); }); } static resolve<T>(value: T | null = null): AgPromise<T> { return new AgPromise<T>(resolve => resolve(value)); } constructor(callback: ResolveAndRejectCallback<T>) { callback(value => this.onDone(value), params => this.onReject(params)); } public then<V>(func: (result: T | null) => V): AgPromise<V> { return new AgPromise(resolve => { if (this.status === AgPromiseStatus.RESOLVED) { resolve(func(this.resolution)); } else { this.waiters.push(value => resolve(func(value))); } }); } public resolveNow<Z>(ifNotResolvedValue: Z, ifResolved: (current: T | null) => Z): Z { return this.status === AgPromiseStatus.RESOLVED ? ifResolved(this.resolution) : ifNotResolvedValue; } private onDone(value: T | null): void { this.status = AgPromiseStatus.RESOLVED; this.resolution = value; forEach(this.waiters, waiter => waiter(value)); } private onReject(params: any): void { console.warn('TBI'); } }
jenkins-sigaut/ag-grid
enterprise-modules/charts/src/charts/chartComp/menu/format/chart/titlePanel.ts
import {_, Autowired, Component, FontStyle, FontWeight, PostConstruct} from "@ag-grid-community/core"; import {ChartController} from "../../../chartController"; import {Font, FontPanel, FontPanelParams} from "../fontPanel"; import {ChartTranslator} from "../../../chartTranslator"; export default class TitlePanel extends Component { public static TEMPLATE = /* html */ `<div></div>`; @Autowired('chartTranslator') private chartTranslator: ChartTranslator; private activePanels: Component[] = []; private readonly chartController: ChartController; // When the title is disabled, and then re-enabled, we want the same title to be // present in the chart. It is kept here so it can later be restored. private disabledTitle: string; constructor(chartController: ChartController) { super(TitlePanel.TEMPLATE); this.chartController = chartController; } @PostConstruct private init() { this.initFontPanel(); } private hasTitle(): boolean { const chartProxy = this.chartController.getChartProxy(); const title: any = chartProxy.getChartOption('title'); return title && title.enabled && title.text && title.text.length > 0; } private initFontPanel(): void { const chartProxy = this.chartController.getChartProxy(); const hasTitle = this.hasTitle; const setFont = (font: Font) => { const chartProxy = this.chartController.getChartProxy(); if (font.family) { chartProxy.setTitleOption('fontFamily', font.family); } if (font.weight) { chartProxy.setTitleOption('fontWeight', font.weight); } if (font.style) { chartProxy.setTitleOption('fontStyle', font.style); } if (font.size) { chartProxy.setTitleOption('fontSize', font.size); } if (font.color) { chartProxy.setTitleOption('color', font.color); } }; const initialFont = { family: chartProxy.getChartOption('title.fontFamily'), style: chartProxy.getChartOption<FontStyle>('title.fontStyle'), weight: chartProxy.getChartOption<FontWeight>('title.fontWeight'), size: chartProxy.getChartOption<number>('title.fontSize'), color: chartProxy.getChartOption('title.color') }; if (!hasTitle) { setFont(initialFont); } const fontPanelParams: FontPanelParams = { name: this.chartTranslator.translate('title'), enabled: this.hasTitle(), suppressEnabledCheckbox: false, initialFont, setFont, setEnabled: (enabled) => { const chartProxy = this.chartController.getChartProxy(); if (enabled) { const newTitle = this.disabledTitle || this.chartTranslator.translate('titlePlaceholder'); chartProxy.setTitleOption('text', newTitle); this.disabledTitle = ''; } else { this.disabledTitle = this.chartController.getChartProxy().getTitleOption('text'); chartProxy.setTitleOption('text', ''); } } }; const fontPanelComp = this.createBean(new FontPanel(fontPanelParams)); this.getGui().appendChild(fontPanelComp.getGui()); this.activePanels.push(fontPanelComp); // edits to the title can disable it, so keep the checkbox in sync: this.addManagedListener(this.eventService, 'chartTitleEdit', () => { fontPanelComp.setEnabled(this.hasTitle()); }); } private destroyActivePanels(): void { this.activePanels.forEach(panel => { _.removeFromParent(panel.getGui()); this.destroyBean(panel); }); } protected destroy(): void { this.destroyActivePanels(); super.destroy(); } }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/modules/moduleRegistry.ts
import { Module } from "../interfaces/iModule"; import { ModuleNames } from "./moduleNames"; import { doOnce } from "../utils/function"; import { values } from "../utils/generic"; export class ModuleRegistry { // having in a map a) removes duplicates and b) allows fast lookup private static modulesMap: { [name: string]: Module; } = {}; private static moduleBased: boolean | undefined; public static register(module: Module, moduleBased = true): void { ModuleRegistry.modulesMap[module.moduleName] = module; if (ModuleRegistry.moduleBased === undefined) { ModuleRegistry.moduleBased = moduleBased; } else { if (ModuleRegistry.moduleBased !== moduleBased) { doOnce(() => { console.warn(`ag-Grid: You are mixing modules (i.e. @ag-grid-community/core) and packages (ag-grid-community) - you can only use one or the other of these mechanisms.`); console.warn('Please see https://www.ag-grid.com/documentation/javascript/packages-modules/ for more information.'); }, 'ModulePackageCheck'); } } } // noinspection JSUnusedGlobalSymbols public static registerModules(modules: Module[], moduleBased = true): void { if (!modules) { return; } modules.forEach(module => ModuleRegistry.register(module, moduleBased)); } public static assertRegistered(moduleName: ModuleNames, reason: string): boolean { if (this.isRegistered(moduleName)) { return true; } const warningKey = reason + moduleName; const warningMessage = `ag-Grid: unable to use ${reason} as module ${moduleName} is not present. Please see: https://www.ag-grid.com/documentation/javascript/modules/`; doOnce(() => { console.warn(warningMessage); }, warningKey); return false; } public static isRegistered(moduleName: ModuleNames): boolean { return !!ModuleRegistry.modulesMap[moduleName]; } public static getRegisteredModules(): Module[] { return values(ModuleRegistry.modulesMap); } public static isPackageBased(): boolean { return !ModuleRegistry.moduleBased; } }
jenkins-sigaut/ag-grid
charts-packages/ag-charts-react/lib/utils.d.ts
<reponame>jenkins-sigaut/ag-grid<filename>charts-packages/ag-charts-react/lib/utils.d.ts // ag-charts-react v3.0.0 export declare const assignProperties: (to: {}, from: {}) => void;
jenkins-sigaut/ag-grid
enterprise-modules/clipboard/src/clipboard/clipboardService.ts
import { _, Autowired, Bean, BeanStub, CellNavigationService, CellPosition, CellPositionUtils, CellRange, ChangedPath, IClientSideRowModel, Column, ColumnApi, ColumnController, Constants, CsvExportParams, Events, EventService, FlashCellsEvent, FocusController, GridApi, GridCore, IClipboardService, IRowModel, Logger, LoggerFactory, PasteEndEvent, PasteStartEvent, PostConstruct, ProcessCellForExportParams, ProcessHeaderForExportParams, RowNode, RowPosition, RowPositionUtils, RowRenderer, RowValueChangedEvent, SelectionController, ValueService, ICsvCreator, IRangeController, Optional } from "@ag-grid-community/core"; interface RowCallback { (gridRow: RowPosition, rowNode: RowNode, columns: Column[], rangeIndex: number, isLastRow?: boolean): void; } interface ColumnCallback { (columns: Column[]): void; } @Bean('clipboardService') export class ClipboardService extends BeanStub implements IClipboardService { @Autowired('csvCreator') private csvCreator: ICsvCreator; @Autowired('loggerFactory') private loggerFactory: LoggerFactory; @Autowired('selectionController') private selectionController: SelectionController; @Optional('rangeController') private rangeController: IRangeController; @Autowired('rowModel') private rowModel: IRowModel; @Autowired('valueService') private valueService: ValueService; @Autowired('focusController') private focusController: FocusController; @Autowired('rowRenderer') private rowRenderer: RowRenderer; @Autowired('columnController') private columnController: ColumnController; @Autowired('cellNavigationService') private cellNavigationService: CellNavigationService; @Autowired('columnApi') private columnApi: ColumnApi; @Autowired('gridApi') private gridApi: GridApi; @Autowired('cellPositionUtils') public cellPositionUtils: CellPositionUtils; @Autowired('rowPositionUtils') public rowPositionUtils: RowPositionUtils; private clientSideRowModel: IClientSideRowModel; private logger: Logger; private gridCore: GridCore; public registerGridCore(gridCore: GridCore): void { this.gridCore = gridCore; } @PostConstruct private init(): void { this.logger = this.loggerFactory.create('ClipboardService'); if (this.rowModel.getType() === Constants.ROW_MODEL_TYPE_CLIENT_SIDE) { this.clientSideRowModel = this.rowModel as IClientSideRowModel; } } public pasteFromClipboard(): void { this.logger.log('pasteFromClipboard'); // Method 1 - native clipboard API, available in modern chrome browsers const allowNavigator = !this.gridOptionsWrapper.isSuppressClipboardApi(); if (allowNavigator && navigator.clipboard) { navigator.clipboard.readText() .then(this.processClipboardData.bind(this)) .catch(() => { // no processing, if fails, do nothing, paste doesn't happen }); return; } // Method 2 - if modern API fails, the old school hack this.executeOnTempElement( (textArea: HTMLTextAreaElement) => textArea.focus(), (element: HTMLTextAreaElement) => { const data = element.value; this.processClipboardData(data); } ); } private processClipboardData(data: string): void { if (_.missingOrEmpty(data)) { return; } let parsedData: string[][] | null = _.stringToArray(data, this.gridOptionsWrapper.getClipboardDeliminator()); const userFunc = this.gridOptionsWrapper.getProcessDataFromClipboardFunc(); if (userFunc) { parsedData = userFunc({ data: parsedData }); } if (_.missingOrEmpty(parsedData)) { return; } if (this.gridOptionsWrapper.isSuppressLastEmptyLineOnPaste()) { this.removeLastLineIfBlank(parsedData!); } const pasteOperation = ( cellsToFlash: any, updatedRowNodes: RowNode[], focusedCell: CellPosition, changedPath: ChangedPath | undefined) => { const rangeActive = this.rangeController && this.rangeController.isMoreThanOneCell(); const pasteIntoRange = rangeActive && !this.hasOnlyOneValueToPaste(parsedData!); if (pasteIntoRange) { this.pasteIntoActiveRange(parsedData!, cellsToFlash, updatedRowNodes, changedPath); } else { this.pasteStartingFromFocusedCell(parsedData!, cellsToFlash, updatedRowNodes, focusedCell, changedPath); } }; this.doPasteOperation(pasteOperation); } // common code to paste operations, e.g. paste to cell, paste to range, and copy range down private doPasteOperation(pasteOperationFunc: ( cellsToFlash: any, updatedRowNodes: RowNode[], focusedCell: CellPosition, changedPath: ChangedPath | undefined) => void ): void { const api = this.gridOptionsWrapper.getApi(); const columnApi = this.gridOptionsWrapper.getColumnApi(); const source = 'clipboard'; this.eventService.dispatchEvent({ type: Events.EVENT_PASTE_START, api, columnApi, source } as PasteStartEvent); let changedPath: ChangedPath; if (this.clientSideRowModel) { const onlyChangedColumns = this.gridOptionsWrapper.isAggregateOnlyChangedColumns(); changedPath = new ChangedPath(onlyChangedColumns, this.clientSideRowModel.getRootNode()); } const cellsToFlash = {} as any; const updatedRowNodes: RowNode[] = []; const doc = this.gridOptionsWrapper.getDocument(); const focusedElementBefore = doc.activeElement; const focusedCell = this.focusController.getFocusedCell(); pasteOperationFunc(cellsToFlash, updatedRowNodes, focusedCell, changedPath); if (changedPath) { this.clientSideRowModel.doAggregate(changedPath); } this.rowRenderer.refreshCells(); this.dispatchFlashCells(cellsToFlash); this.fireRowChanged(updatedRowNodes); const focusedElementAfter = doc.activeElement; // if using the clipboard hack with a temp element, then the focus has been lost, // so need to put it back. otherwise paste operation loosed focus on cell and keyboard // navigation stops. if (focusedCell && focusedElementBefore != focusedElementAfter) { this.focusController.setFocusedCell(focusedCell.rowIndex, focusedCell.column, focusedCell.rowPinned, true); } this.eventService.dispatchEvent({ type: Events.EVENT_PASTE_END, api, columnApi, source } as PasteEndEvent); } private pasteIntoActiveRange( clipboardData: string[][], cellsToFlash: any, updatedRowNodes: RowNode[], changedPath: ChangedPath | undefined ) { // true if clipboard data can be evenly pasted into range, otherwise false const abortRepeatingPasteIntoRows = this.getRangeSize() % clipboardData.length != 0; let indexOffset = 0; let dataRowIndex = 0; const rowCallback: RowCallback = (currentRow: RowPosition, rowNode: RowNode, columns: Column[], index: number) => { const atEndOfClipboardData = index - indexOffset >= clipboardData.length; if (atEndOfClipboardData) { if (abortRepeatingPasteIntoRows) { return; } // increment offset and reset data index to repeat paste of data indexOffset += dataRowIndex; dataRowIndex = 0; } const currentRowData = clipboardData[index - indexOffset]; // otherwise we are not the first row, so copy updatedRowNodes.push(rowNode); const processCellFromClipboardFunc = this.gridOptionsWrapper.getProcessCellFromClipboardFunc(); columns.forEach((column, idx) => { if (!column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode)) { return; } // repeat data for columns we don't have data for - happens when to range is bigger than copied data range if (idx >= currentRowData.length) { idx = idx % currentRowData.length; } const newValue = this.processCell( rowNode, column, currentRowData[idx], Constants.EXPORT_TYPE_DRAG_COPY, processCellFromClipboardFunc); this.valueService.setValue(rowNode, column, newValue, Constants.SOURCE_PASTE); if (changedPath) { changedPath.addParentNode(rowNode.parent, [column]); } const cellId = this.cellPositionUtils.createIdFromValues(currentRow.rowIndex, column, currentRow.rowPinned); cellsToFlash[cellId] = true; }); dataRowIndex++; }; this.iterateActiveRanges(false, rowCallback); } private pasteStartingFromFocusedCell( parsedData: string[][], cellsToFlash: any, updatedRowNodes: RowNode[], focusedCell: CellPosition, changedPath: ChangedPath | undefined ) { if (!focusedCell) { return; } const currentRow: RowPosition = { rowIndex: focusedCell.rowIndex, rowPinned: focusedCell.rowPinned }; const columnsToPasteInto = this.columnController.getDisplayedColumnsStartingAt(focusedCell.column); this.pasteMultipleValues( parsedData, currentRow, updatedRowNodes, columnsToPasteInto, cellsToFlash, Constants.EXPORT_TYPE_CLIPBOARD, changedPath); } private hasOnlyOneValueToPaste(parsedData: string[][]) { return parsedData.length === 1 && parsedData[0].length === 1; } public copyRangeDown(): void { if (!this.rangeController || this.rangeController.isEmpty()) { return; } const firstRowValues: any[] = []; const pasteOperation = ( cellsToFlash: any, updatedRowNodes: RowNode[], focusedCell: CellPosition, changedPath: ChangedPath | undefined ) => { const processCellForClipboardFunc = this.gridOptionsWrapper.getProcessCellForClipboardFunc(); const processCellFromClipboardFunc = this.gridOptionsWrapper.getProcessCellFromClipboardFunc(); const rowCallback: RowCallback = (currentRow: RowPosition, rowNode: RowNode, columns: Column[]) => { // take reference of first row, this is the one we will be using to copy from if (!firstRowValues.length) { // two reasons for looping through columns columns.forEach(column => { // get the initial values to copy down const value = this.processCell( rowNode, column, this.valueService.getValue(column, rowNode), Constants.EXPORT_TYPE_DRAG_COPY, processCellForClipboardFunc); firstRowValues.push(value); }); } else { // otherwise we are not the first row, so copy updatedRowNodes.push(rowNode); columns.forEach((column, index) => { if (!column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode)) { return; } const firstRowValue = this.processCell( rowNode, column, firstRowValues[index], Constants.EXPORT_TYPE_DRAG_COPY, processCellFromClipboardFunc); this.valueService.setValue(rowNode, column, firstRowValue, Constants.SOURCE_PASTE); if (changedPath) { changedPath.addParentNode(rowNode.parent, [column]); } const cellId = this.cellPositionUtils.createIdFromValues(currentRow.rowIndex, column, currentRow.rowPinned); cellsToFlash[cellId] = true; }); } }; this.iterateActiveRanges(true, rowCallback); }; this.doPasteOperation(pasteOperation); } private removeLastLineIfBlank(parsedData: string[][]): void { // remove last row if empty, excel puts empty last row in const lastLine = _.last(parsedData); const lastLineIsBlank = lastLine && lastLine.length === 1 && lastLine[0] === ''; if (lastLineIsBlank) { _.removeFromArray(parsedData, lastLine); } } private fireRowChanged(rowNodes: RowNode[]): void { if (!this.gridOptionsWrapper.isFullRowEdit()) { return; } rowNodes.forEach(rowNode => { const event: RowValueChangedEvent = { type: Events.EVENT_ROW_VALUE_CHANGED, node: rowNode, data: rowNode.data, rowIndex: rowNode.rowIndex, rowPinned: rowNode.rowPinned, context: this.gridOptionsWrapper.getContext(), api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi() }; this.eventService.dispatchEvent(event); }); } private pasteMultipleValues( clipboardGridData: string[][], currentRow: RowPosition | null, updatedRowNodes: RowNode[], columnsToPasteInto: Column[], cellsToFlash: any, type: string, changedPath: ChangedPath | undefined) { let rowPointer = currentRow; clipboardGridData.forEach(clipboardRowData => { // if we have come to end of rows in grid, then skip if (!rowPointer) { return; } const rowNode = this.rowPositionUtils.getRowNode(rowPointer); if (rowNode) { updatedRowNodes.push(rowNode); clipboardRowData.forEach((value, index) => this.updateCellValue(rowNode, columnsToPasteInto[index], value, rowPointer, cellsToFlash, type, changedPath)); // move to next row down for next set of values rowPointer = this.cellNavigationService.getRowBelow({ rowPinned: rowPointer.rowPinned, rowIndex: rowPointer.rowIndex }); } }); return rowPointer; } private updateCellValue( rowNode: RowNode | null, column: Column, value: string, currentRow: RowPosition | null, cellsToFlash: any, type: string, changedPath: ChangedPath | undefined) { if ( !rowNode || !currentRow || !column || !column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode) ) { return; } const processedValue = this.processCell(rowNode, column, value, type, this.gridOptionsWrapper.getProcessCellFromClipboardFunc()); this.valueService.setValue(rowNode, column, processedValue, Constants.SOURCE_PASTE); const cellId = this.cellPositionUtils.createIdFromValues(currentRow.rowIndex, column, currentRow.rowPinned); cellsToFlash[cellId] = true; if (changedPath) { changedPath.addParentNode(rowNode.parent, [column]); } } public copyToClipboard(includeHeaders?: boolean): void { this.logger.log(`copyToClipboard: includeHeaders = ${includeHeaders}`); // don't override 'includeHeaders' if it has been explicitly set to 'false' if (includeHeaders == null) { includeHeaders = this.gridOptionsWrapper.isCopyHeadersToClipboard(); } const selectedRowsToCopy = !this.selectionController.isEmpty() && !this.gridOptionsWrapper.isSuppressCopyRowsToClipboard(); // default is copy range if exists, otherwise rows if (this.rangeController && this.rangeController.isMoreThanOneCell()) { this.copySelectedRangeToClipboard(includeHeaders); } else if (selectedRowsToCopy) { // otherwise copy selected rows if they exist this.copySelectedRowsToClipboard(includeHeaders); } else if (this.focusController.isAnyCellFocused()) { // if there is a focused cell, copy this this.copyFocusedCellToClipboard(includeHeaders); } else { // lastly if no focused cell, try range again. this can happen // if use has cellSelection turned off (so no focused cell) // but has a cell clicked, so there exists a cell range // of exactly one cell (hence the first 'if' above didn't // get executed). this.copySelectedRangeToClipboard(includeHeaders); } } private iterateActiveRanges(onlyFirst: boolean, rowCallback: RowCallback, columnCallback?: ColumnCallback): void { if (!this.rangeController || this.rangeController.isEmpty()) { return; } const cellRanges = this.rangeController.getCellRanges() as CellRange[]; if (onlyFirst) { this.iterateActiveRange(cellRanges[0], rowCallback, columnCallback, true); } else { cellRanges.forEach((range, idx) => this.iterateActiveRange(range, rowCallback, columnCallback, idx === cellRanges.length - 1)); } } private iterateActiveRange(range: CellRange, rowCallback: RowCallback, columnCallback?: ColumnCallback, isLastRange?: boolean): void { if (!this.rangeController) { return; } let currentRow = this.rangeController.getRangeStartRow(range); const lastRow = this.rangeController.getRangeEndRow(range); if (columnCallback && range.columns) { columnCallback(range.columns); } let rangeIndex = 0; let isLastRow = false; // the currentRow could be missing if the user sets the active range manually, and sets a range // that is outside of the grid (eg. sets range rows 0 to 100, but grid has only 20 rows). while (!isLastRow && currentRow != null) { const rowNode = this.rowPositionUtils.getRowNode(currentRow); isLastRow = this.rowPositionUtils.sameRow(currentRow, lastRow); rowCallback(currentRow, rowNode, range.columns, rangeIndex++, isLastRow && isLastRange); currentRow = this.cellNavigationService.getRowBelow(currentRow); } } public copySelectedRangeToClipboard(includeHeaders = false): void { if (!this.rangeController || this.rangeController.isEmpty()) { return; } const deliminator = this.gridOptionsWrapper.getClipboardDeliminator(); let data = ''; const cellsToFlash = {} as any; // adds columns to the data const columnCallback = (columns: Column[]) => { if (!includeHeaders) { return; } const processHeaderForClipboardFunc = this.gridOptionsWrapper.getProcessHeaderForClipboardFunc(); const columnNames = columns.map(column => { const name = this.columnController.getDisplayNameForColumn(column, 'clipboard', true); return this.processHeader(column, name, processHeaderForClipboardFunc) || ''; }); data += columnNames.join(deliminator) + '\r\n'; }; // adds cell values to the data const rowCallback: RowCallback = (currentRow: RowPosition, rowNode: RowNode, columns: Column[], _2: number, isLastRow?: boolean) => { const processCellForClipboardFunc = this.gridOptionsWrapper.getProcessCellForClipboardFunc(); columns.forEach((column, index) => { const value = this.valueService.getValue(column, rowNode); const processedValue = this.processCell(rowNode, column, value, Constants.EXPORT_TYPE_CLIPBOARD, processCellForClipboardFunc); if (index != 0) { data += deliminator; } if (_.exists(processedValue)) { data += processedValue; } const cellId = this.cellPositionUtils.createIdFromValues(currentRow.rowIndex, column, currentRow.rowPinned); cellsToFlash[cellId] = true; }); if (!isLastRow) { data += '\r\n'; } }; this.iterateActiveRanges(false, rowCallback, columnCallback); this.copyDataToClipboard(data); this.dispatchFlashCells(cellsToFlash); } private copyFocusedCellToClipboard(includeHeaders = false): void { const focusedCell = this.focusController.getFocusedCell(); if (focusedCell == null) { return; } const cellId = this.cellPositionUtils.createId(focusedCell); const currentRow: RowPosition = { rowPinned: focusedCell.rowPinned, rowIndex: focusedCell.rowIndex }; const rowNode = this.rowPositionUtils.getRowNode(currentRow); const column = focusedCell.column; const value = this.valueService.getValue(column, rowNode); let processedValue = this.processCell( rowNode, column, value, Constants.EXPORT_TYPE_CLIPBOARD, this.gridOptionsWrapper.getProcessCellForClipboardFunc()); processedValue = _.missing(processedValue) ? '' : processedValue.toString(); let data: string; if (includeHeaders) { const headerValue = this.columnController.getDisplayNameForColumn(column, 'clipboard', true); data = this.processHeader(column, headerValue, this.gridOptionsWrapper.getProcessHeaderForClipboardFunc()) + '\r\n' + processedValue; } else { data = processedValue; } this.copyDataToClipboard(data); this.dispatchFlashCells({ [cellId]: true }); } private dispatchFlashCells(cellsToFlash: {}): void { window.setTimeout(() => { const event: FlashCellsEvent = { type: Events.EVENT_FLASH_CELLS, cells: cellsToFlash, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }, 0); } private processCell<T>( rowNode: RowNode | null, column: Column, value: T, type: string, func?: ((params: ProcessCellForExportParams) => T)): T { if (func) { const params = { column, node: rowNode, value, api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext(), type, }; return func(params); } return value; } private processHeader<T>(column: Column, value: T, func?: ((params: ProcessHeaderForExportParams) => T)): T { if (func) { const params: ProcessHeaderForExportParams = { column, api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi(), context: this.gridOptionsWrapper.getContext() }; return func(params); } return value; } public copySelectedRowsToClipboard(includeHeaders = false, columnKeys?: (string | Column)[]): void { const params: CsvExportParams = { columnKeys: columnKeys, skipHeader: !includeHeaders, skipFooters: true, suppressQuotes: true, columnSeparator: this.gridOptionsWrapper.getClipboardDeliminator(), onlySelected: true, processCellCallback: this.gridOptionsWrapper.getProcessCellForClipboardFunc(), processHeaderCallback: this.gridOptionsWrapper.getProcessHeaderForClipboardFunc() }; const data = this.csvCreator.getDataAsCsv(params); this.copyDataToClipboard(data); } private copyDataToClipboard(data: string): void { const userProvidedFunc = this.gridOptionsWrapper.getSendToClipboardFunc(); // method 1 - user provided func if (userProvidedFunc) { userProvidedFunc({ data }); return; } // method 2 - native clipboard API, available in modern chrome browsers const allowNavigator = !this.gridOptionsWrapper.isSuppressClipboardApi(); if (allowNavigator && navigator.clipboard) { navigator.clipboard.writeText(data).catch(() => { // no processing, if fails, do nothing, copy doesn't happen }); return; } // method 3 - if all else fails, the old school hack this.executeOnTempElement(element => { const focusedElementBefore = this.gridOptionsWrapper.getDocument().activeElement as HTMLElement; element.value = data || ' '; // has to be non-empty value or execCommand will not do anything element.select(); element.focus(); const result = document.execCommand('copy'); if (!result) { console.warn('ag-grid: Browser did not allow document.execCommand(\'copy\'). Ensure ' + 'api.copySelectedRowsToClipboard() is invoked via a user event, i.e. button click, otherwise ' + 'the browser will prevent it for security reasons.'); } if (focusedElementBefore != null && focusedElementBefore.focus != null) { focusedElementBefore.focus(); } }); } private executeOnTempElement( callbackNow: (element: HTMLTextAreaElement) => void, callbackAfter?: (element: HTMLTextAreaElement) => void ): void { const eTempInput = document.createElement('textarea'); eTempInput.style.width = '1px'; eTempInput.style.height = '1px'; eTempInput.style.top = '0px'; eTempInput.style.left = '0px'; eTempInput.style.position = 'absolute'; eTempInput.style.opacity = '0.0'; const guiRoot = this.gridCore.getRootGui(); guiRoot.appendChild(eTempInput); try { callbackNow(eTempInput); } catch (err) { console.warn('ag-grid: Browser does not support document.execCommand(\'copy\') for clipboard operations'); } //It needs 100 otherwise OS X seemed to not always be able to paste... Go figure... if (callbackAfter) { window.setTimeout(() => { callbackAfter(eTempInput); guiRoot.removeChild(eTempInput); }, 100); } else { guiRoot.removeChild(eTempInput); } } private getRangeSize(): number { const ranges = this.rangeController.getCellRanges(); let startRangeIndex = 0; let endRangeIndex = 0; if (ranges.length > 0) { startRangeIndex = this.rangeController.getRangeStartRow(ranges[0]).rowIndex; endRangeIndex = this.rangeController.getRangeEndRow(ranges[0]).rowIndex; } return startRangeIndex - endRangeIndex + 1; } }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/utils/general.ts
import { ICellRendererComp } from '../rendering/cellRenderers/iCellRenderer'; import { AgPromise } from './promise'; import { loadTemplate } from './dom'; import { camelCaseToHyphen } from './string'; import { iterateObject } from './object'; /** @deprecated */ export function getNameOfClass(theClass: any) { const funcNameRegex = /function (.{1,})\(/; const funcAsString = theClass.toString(); const results = funcNameRegex.exec(funcAsString); return results && results.length > 1 ? results[1] : ""; } export function findLineByLeastSquares(values: number[]) { const len = values.length; let maxDecimals = 0; if (len <= 1) { return values; } for (let i = 0; i < values.length; i++) { const value = values[i]; if (Math.floor(value) === value) { continue; } maxDecimals = Math.max(maxDecimals, value.toString().split('.')[1].length); } let sum_x = 0; let sum_y = 0; let sum_xy = 0; let sum_xx = 0; let y = 0; for (let x = 0; x < len; x++) { y = values[x]; sum_x += x; sum_y += y; sum_xx += x * x; sum_xy += x * y; } const m = (len * sum_xy - sum_x * sum_y) / (len * sum_xx - sum_x * sum_x); const b = (sum_y / len) - (m * sum_x) / len; const result = []; for (let x = 0; x <= len; x++) { result.push(parseFloat((x * m + b).toFixed(maxDecimals))); } return result; } /** * Converts a CSS object into string * @param {Object} stylesToUse an object eg: {color: 'black', top: '25px'} * @return {string} A string like "color: black; top: 25px;" for html */ export function cssStyleObjectToMarkup(stylesToUse: any): string { if (!stylesToUse) { return ''; } const resParts: string[] = []; iterateObject(stylesToUse, (styleKey: string, styleValue: string) => { const styleKeyDashed = camelCaseToHyphen(styleKey); resParts.push(`${styleKeyDashed}: ${styleValue};`); }); return resParts.join(' '); } /** * Displays a message to the browser. this is useful in iPad, where you can't easily see the console. * so the javascript code can use this to give feedback. this is NOT intended to be called in production. * it is intended the ag-Grid developer calls this to troubleshoot, but then takes out the calls before * checking in. * @param {string} msg */ export function message(msg: string): void { const eMessage = document.createElement('div'); let eBox = document.querySelector('#__ag__message'); eMessage.innerHTML = msg; if (!eBox) { const template = `<div id="__ag__message" style="display: inline-block; position: absolute; top: 0px; left: 0px; color: white; background-color: black; z-index: 20; padding: 2px; border: 1px solid darkred; height: 200px; overflow-y: auto;"></div>`; eBox = loadTemplate(template); if (document.body) { document.body.appendChild(eBox); } } eBox.insertBefore(eMessage, eBox.children[0]); } /** * cell renderers are used in a few places. they bind to dom slightly differently to other cell renderes as they * can return back strings (instead of html elemnt) in the getGui() method. common code placed here to handle that. * @param {AgPromise<ICellRendererComp>} cellRendererPromise * @param {HTMLElement} eTarget */ export function bindCellRendererToHtmlElement(cellRendererPromise: AgPromise<ICellRendererComp>, eTarget: HTMLElement) { cellRendererPromise.then(cellRenderer => { const gui: HTMLElement | string = cellRenderer.getGui(); if (gui != null) { if (typeof gui === 'object') { eTarget.appendChild(gui); } else { eTarget.innerHTML = gui; } } }); }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/headerRendering/headerRootComp.d.ts
<reponame>jenkins-sigaut/ag-grid // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { GridPanel } from '../gridPanel/gridPanel'; import { HeaderContainer } from './headerContainer'; import { Component } from '../widgets/component'; import { ManagedFocusComponent } from '../widgets/managedFocusComponent'; export declare type HeaderContainerPosition = 'left' | 'right' | 'center'; export declare class HeaderRootComp extends ManagedFocusComponent { private static TEMPLATE; private ePinnedLeftHeader; private ePinnedRightHeader; private eHeaderContainer; private eHeaderViewport; private columnController; private gridApi; private autoWidthCalculator; private headerNavigationService; private gridPanel; private printLayout; private headerContainers; constructor(); protected postConstruct(): void; registerGridComp(gridPanel: GridPanel): void; private registerHeaderContainer; protected onTabKeyDown(e: KeyboardEvent): void; protected handleKeyDown(e: KeyboardEvent): void; protected onFocusOut(e: FocusEvent): void; private onDomLayoutChanged; setHorizontalScroll(offset: number): void; forEachHeaderElement(callback: (renderedHeaderElement: Component) => void): void; refreshHeader(): void; private onPivotModeChanged; setHeight(height: number): void; private addPreventHeaderScroll; getHeaderContainers(): Map<HeaderContainerPosition, HeaderContainer>; setHeaderContainerWidth(width: number): void; setLeftVisible(visible: boolean): void; setRightVisible(visible: boolean): void; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/constants/keyCode.d.ts
// Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> export declare class KeyCode { static BACKSPACE: number; static TAB: number; static ENTER: number; static SHIFT: number; static ESCAPE: number; static SPACE: number; static LEFT: number; static UP: number; static RIGHT: number; static DOWN: number; static DELETE: number; static A: number; static C: number; static V: number; static D: number; static Z: number; static Y: number; static F2: number; static PAGE_UP: number; static PAGE_DOWN: number; static PAGE_HOME: number; static PAGE_END: number; }
jenkins-sigaut/ag-grid
community-modules/core/src/ts/gridOptionsWrapper.ts
import { RowNode } from './entities/rowNode'; import { ChartRef, FillOperationParams, GetChartToolbarItems, GetContextMenuItems, GetMainMenuItems, GetRowNodeIdFunc, GridOptions, IsRowMaster, IsRowSelectable, IsServerSideGroupOpenByDefaultParams, NavigateToNextCellParams, NavigateToNextHeaderParams, PaginationNumberFormatterParams, PostProcessPopupParams, ProcessChartOptionsParams, ProcessDataFromClipboardParams, TabToNextCellParams, TabToNextHeaderParams } from './entities/gridOptions'; import { EventService } from './eventService'; import { Constants } from './constants/constants'; import { ComponentUtil } from './components/componentUtil'; import { GridApi } from './gridApi'; import { ColDef, ColGroupDef, IAggFunc, SuppressKeyboardEventParams } from './entities/colDef'; import { Autowired, Bean, PostConstruct, PreDestroy, Qualifier } from './context/context'; import { ColumnApi } from './columnController/columnApi'; import { ColumnController } from './columnController/columnController'; import { IViewportDatasource } from './interfaces/iViewportDatasource'; import { IDatasource } from './interfaces/iDatasource'; import { CellPosition } from './entities/cellPosition'; import { IServerSideDatasource } from './interfaces/iServerSideDatasource'; import { BaseExportParams, ProcessCellForExportParams, ProcessHeaderForExportParams } from './interfaces/exportParams'; import { AgEvent } from './events'; import { Environment, SASS_PROPERTIES } from './environment'; import { PropertyKeys } from './propertyKeys'; import { ColDefUtil } from './components/colDefUtil'; import { Events } from './eventKeys'; import { AutoHeightCalculator } from './rendering/row/autoHeightCalculator'; import { SideBarDef, SideBarDefParser } from './entities/sideBar'; import { ModuleNames } from './modules/moduleNames'; import { ChartOptions } from './interfaces/iChartOptions'; import { AgChartTheme, AgChartThemeOverrides } from "./interfaces/iAgChartOptions"; import { iterateObject } from './utils/object'; import { ModuleRegistry } from './modules/moduleRegistry'; import { exists, missing, values } from './utils/generic'; import { fuzzyCheckStrings } from './utils/fuzzyMatch'; import { doOnce } from './utils/function'; import { addOrRemoveCssClass } from './utils/dom'; import { getScrollbarWidth } from './utils/browser'; import { HeaderPosition } from './headerRendering/header/headerPosition'; const DEFAULT_ROW_HEIGHT = 25; const DEFAULT_DETAIL_ROW_HEIGHT = 300; const DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE = 5; const DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE = 5; const DEFAULT_KEEP_DETAIL_ROW_COUNT = 10; function isTrue(value: any): boolean { return value === true || value === 'true'; } function toNumber(value: any): number { if (typeof value == 'number') { return value; } if (typeof value == 'string') { return parseInt(value, 10); } } function zeroOrGreater(value: any, defaultValue: number): number { if (value >= 0) { return value; } // zero gets returned if number is missing or the wrong type return defaultValue; } function oneOrGreater(value: any, defaultValue: number): number { if (value > 0) { return value; } // zero gets returned if number is missing or the wrong type return defaultValue; } export interface PropertyChangedEvent extends AgEvent { currentValue: any; previousValue: any; } @Bean('gridOptionsWrapper') export class GridOptionsWrapper { private static MIN_COL_WIDTH = 10; public static PROP_HEADER_HEIGHT = 'headerHeight'; public static PROP_GROUP_REMOVE_SINGLE_CHILDREN = 'groupRemoveSingleChildren'; public static PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN = 'groupRemoveLowestSingleChildren'; public static PROP_PIVOT_HEADER_HEIGHT = 'pivotHeaderHeight'; public static PROP_SUPPRESS_CLIPBOARD_PASTE = 'suppressClipboardPaste'; public static PROP_GROUP_HEADER_HEIGHT = 'groupHeaderHeight'; public static PROP_PIVOT_GROUP_HEADER_HEIGHT = 'pivotGroupHeaderHeight'; public static PROP_FLOATING_FILTERS_HEIGHT = 'floatingFiltersHeight'; public static PROP_SUPPRESS_ROW_CLICK_SELECTION = 'suppressRowClickSelection'; public static PROP_SUPPRESS_ROW_DRAG = 'suppressRowDrag'; public static PROP_SUPPRESS_MOVE_WHEN_ROW_DRAG = 'suppressMoveWhenRowDragging'; public static PROP_POPUP_PARENT = 'popupParent'; public static PROP_DOM_LAYOUT = 'domLayout'; public static PROP_FILL_HANDLE_DIRECTION = 'fillHandleDirection'; @Autowired('gridOptions') private readonly gridOptions: GridOptions; @Autowired('columnController') private readonly columnController: ColumnController; @Autowired('eventService') private readonly eventService: EventService; @Autowired('environment') private readonly environment: Environment; @Autowired('autoHeightCalculator') private readonly autoHeightCalculator: AutoHeightCalculator; private propertyEventService: EventService = new EventService(); private domDataKey = '__AG_' + Math.random().toString(); private layoutElements: HTMLElement[] = []; // we store this locally, so we are not calling getScrollWidth() multiple times as it's an expensive operation private scrollbarWidth: number; private updateLayoutClassesListener: any; private destroyed = false; private agWire(@Qualifier('gridApi') gridApi: GridApi, @Qualifier('columnApi') columnApi: ColumnApi): void { this.gridOptions.api = gridApi; this.gridOptions.columnApi = columnApi; this.checkForDeprecated(); this.checkForViolations(); } @PreDestroy private destroy(): void { // need to remove these, as we don't own the lifecycle of the gridOptions, we need to // remove the references in case the user keeps the grid options, we want the rest // of the grid to be picked up by the garbage collector this.gridOptions.api = null; this.gridOptions.columnApi = null; this.removeEventListener(GridOptionsWrapper.PROP_DOM_LAYOUT, this.updateLayoutClassesListener); this.destroyed = true; } @PostConstruct public init(): void { if (!(this.gridOptions.suppressPropertyNamesCheck === true)) { this.checkGridOptionsProperties(); this.checkColumnDefProperties(); } // parse side bar options into correct format if (this.gridOptions.sideBar != null) { this.gridOptions.sideBar = SideBarDefParser.parse(this.gridOptions.sideBar); } const async = this.useAsyncEvents(); this.eventService.addGlobalListener(this.globalEventHandler.bind(this), async); if (this.isGroupSelectsChildren() && this.isSuppressParentsInRowNodes()) { console.warn("ag-Grid: 'groupSelectsChildren' does not work with 'suppressParentsInRowNodes', this selection method needs the part in rowNode to work"); } if (this.isGroupSelectsChildren()) { if (!this.isRowSelectionMulti()) { console.warn("ag-Grid: rowSelection must be 'multiple' for groupSelectsChildren to make sense"); } if (this.isRowModelServerSide()) { console.warn( 'ag-Grid: group selects children is NOT support for Server Side Row Model. ' + 'This is because the rows are lazy loaded, so selecting a group is not possible as' + 'the grid has no way of knowing what the children are.' ); } } if (this.isGroupRemoveSingleChildren() && this.isGroupHideOpenParents()) { console.warn( "ag-Grid: groupRemoveSingleChildren and groupHideOpenParents do not work with each other, you need to pick one. And don't ask us how to us these together on our support forum either you will get the same answer!" ); } if (this.isRowModelServerSide()) { const msg = (prop: string) => `ag-Grid: '${prop}' is not supported on the Server-Side Row Model`; if (exists(this.gridOptions.groupDefaultExpanded)) { console.warn(msg('groupDefaultExpanded')); } if (exists(this.gridOptions.groupDefaultExpanded)) { console.warn(msg('groupIncludeFooter')); } if (exists(this.gridOptions.groupDefaultExpanded)) { console.warn(msg('groupIncludeTotalFooter')); } } if (this.isEnableRangeSelection()) { ModuleRegistry.assertRegistered(ModuleNames.RangeSelectionModule, 'enableRangeSelection'); } if (!this.isEnableRangeSelection() && (this.isEnableRangeHandle() || this.isEnableFillHandle())) { console.warn("ag-Grid: 'enableRangeHandle' and 'enableFillHandle' will not work unless 'enableRangeSelection' is set to true"); } const warnOfDeprecaredIcon = (name: string) => { if (this.gridOptions.icons && this.gridOptions.icons[name]) { console.warn(`gridOptions.icons.${name} is no longer supported. For information on how to style checkboxes and radio buttons, see https://www.ag-grid.com/javascript-grid-icons/`); } }; warnOfDeprecaredIcon('radioButtonOff'); warnOfDeprecaredIcon('radioButtonOn'); warnOfDeprecaredIcon('checkboxChecked'); warnOfDeprecaredIcon('checkboxUnchecked'); warnOfDeprecaredIcon('checkboxIndeterminate'); this.updateLayoutClassesListener = this.updateLayoutClasses.bind(this); this.addEventListener(GridOptionsWrapper.PROP_DOM_LAYOUT, this.updateLayoutClassesListener); // sets an initial calculation for the scrollbar width this.getScrollbarWidth(); } private checkColumnDefProperties() { if (this.gridOptions.columnDefs == null) { return; } this.gridOptions.columnDefs.forEach(colDef => { const userProperties: string[] = Object.getOwnPropertyNames(colDef); const validProperties: string[] = [...ColDefUtil.ALL_PROPERTIES, ...ColDefUtil.FRAMEWORK_PROPERTIES]; this.checkProperties( userProperties, validProperties, validProperties, 'colDef', 'https://www.ag-grid.com/javascript-grid-column-properties/' ); }); } private checkGridOptionsProperties() { const userProperties: string[] = Object.getOwnPropertyNames(this.gridOptions); const validProperties: string[] = [ ...PropertyKeys.ALL_PROPERTIES, ...PropertyKeys.FRAMEWORK_PROPERTIES, ...values<any>(Events).map(event => ComponentUtil.getCallbackForEvent(event)) ]; const validPropertiesAndExceptions: string[] = [...validProperties, 'api', 'columnApi']; this.checkProperties( userProperties, validPropertiesAndExceptions, validProperties, 'gridOptions', 'https://www.ag-grid.com/javascript-grid-properties/' ); } private checkProperties( userProperties: string[], validPropertiesAndExceptions: string[], validProperties: string[], containerName: string, docsUrl: string ) { const invalidProperties: { [p: string]: string[]; } = fuzzyCheckStrings( userProperties, validPropertiesAndExceptions, validProperties ); iterateObject<any>(invalidProperties, (key, value) => { console.warn(`ag-grid: invalid ${containerName} property '${key}' did you mean any of these: ${value.slice(0, 8).join(", ")}`); }); if (Object.keys(invalidProperties).length > 0) { console.warn(`ag-grid: to see all the valid ${containerName} properties please check: ${docsUrl}`); } } public getDomDataKey(): string { return this.domDataKey; } // returns the dom data, or undefined if not found public getDomData(element: Node, key: string): any { const domData = (element as any)[this.getDomDataKey()]; return domData ? domData[key] : undefined; } public setDomData(element: Element, key: string, value: any): any { const domDataKey = this.getDomDataKey(); let domData = (element as any)[domDataKey]; if (missing(domData)) { domData = {}; (element as any)[domDataKey] = domData; } domData[key] = value; } public isRowSelection() { return this.gridOptions.rowSelection === 'single' || this.gridOptions.rowSelection === 'multiple'; } public isSuppressRowDeselection() { return isTrue(this.gridOptions.suppressRowDeselection); } public isRowSelectionMulti() { return this.gridOptions.rowSelection === 'multiple'; } public isRowMultiSelectWithClick() { return isTrue(this.gridOptions.rowMultiSelectWithClick); } public getContext() { return this.gridOptions.context; } public isPivotMode() { return isTrue(this.gridOptions.pivotMode); } public isSuppressExpandablePivotGroups() { return isTrue(this.gridOptions.suppressExpandablePivotGroups); } public getPivotColumnGroupTotals() { return this.gridOptions.pivotColumnGroupTotals; } public getPivotRowTotals() { return this.gridOptions.pivotRowTotals; } public isRowModelInfinite() { return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_INFINITE; } public isRowModelViewport() { return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_VIEWPORT; } public isRowModelServerSide() { return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_SERVER_SIDE; } public isRowModelDefault() { return (missing(this.gridOptions.rowModelType) || this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_CLIENT_SIDE); } public isFullRowEdit() { return this.gridOptions.editType === 'fullRow'; } public isSuppressFocusAfterRefresh() { return isTrue(this.gridOptions.suppressFocusAfterRefresh); } public isSuppressBrowserResizeObserver() { return isTrue(this.gridOptions.suppressBrowserResizeObserver); } public isSuppressMaintainUnsortedOrder() { return isTrue(this.gridOptions.suppressMaintainUnsortedOrder); } public isSuppressClearOnFillReduction() { return isTrue(this.gridOptions.suppressClearOnFillReduction); } public isShowToolPanel() { return isTrue(this.gridOptions.sideBar && Array.isArray(this.getSideBar().toolPanels)); } public getSideBar(): SideBarDef { return this.gridOptions.sideBar as SideBarDef; } public isSuppressTouch() { return isTrue(this.gridOptions.suppressTouch); } public isApplyColumnDefOrder() { return isTrue(this.gridOptions.applyColumnDefOrder); } public isSuppressRowTransform() { return isTrue(this.gridOptions.suppressRowTransform); } public isSuppressColumnStateEvents() { return isTrue(this.gridOptions.suppressColumnStateEvents); } public isAllowDragFromColumnsToolPanel() { return isTrue(this.gridOptions.allowDragFromColumnsToolPanel); } public useAsyncEvents() { return !isTrue(this.gridOptions.suppressAsyncEvents); } public isEnableCellChangeFlash() { return isTrue(this.gridOptions.enableCellChangeFlash); } public getCellFlashDelay(): number { return this.gridOptions.cellFlashDelay || 500; } public getCellFadeDelay(): number { return this.gridOptions.cellFadeDelay || 1000; } public isGroupSelectsChildren() { const result = isTrue(this.gridOptions.groupSelectsChildren); if (result && this.isTreeData()) { console.warn('ag-Grid: groupSelectsChildren does not work with tree data'); return false; } return result; } public isSuppressRowHoverHighlight() { return isTrue(this.gridOptions.suppressRowHoverHighlight); } public isGroupSelectsFiltered() { return isTrue(this.gridOptions.groupSelectsFiltered); } public isGroupHideOpenParents() { return isTrue(this.gridOptions.groupHideOpenParents); } // if we are doing hideOpenParents, then we always have groupMultiAutoColumn, otherwise hideOpenParents would not work public isGroupMultiAutoColumn() { return isTrue(this.gridOptions.groupMultiAutoColumn) || isTrue(this.gridOptions.groupHideOpenParents); } public isGroupRemoveSingleChildren() { return isTrue(this.gridOptions.groupRemoveSingleChildren); } public isGroupRemoveLowestSingleChildren() { return isTrue(this.gridOptions.groupRemoveLowestSingleChildren); } public isGroupIncludeFooter() { return isTrue(this.gridOptions.groupIncludeFooter); } public isGroupIncludeTotalFooter() { return isTrue(this.gridOptions.groupIncludeTotalFooter); } public isGroupSuppressBlankHeader() { return isTrue(this.gridOptions.groupSuppressBlankHeader); } public isSuppressRowClickSelection() { return isTrue(this.gridOptions.suppressRowClickSelection); } public isSuppressCellSelection() { return isTrue(this.gridOptions.suppressCellSelection); } public isSuppressMultiSort() { return isTrue(this.gridOptions.suppressMultiSort); } public isMultiSortKeyCtrl() { return this.gridOptions.multiSortKey === 'ctrl'; } public isGroupSuppressAutoColumn() { return isTrue(this.gridOptions.groupSuppressAutoColumn); } public isPivotSuppressAutoColumn() { return isTrue(this.gridOptions.pivotSuppressAutoColumn); } public isSuppressDragLeaveHidesColumns() { return isTrue(this.gridOptions.suppressDragLeaveHidesColumns); } public isSuppressScrollOnNewData() { return isTrue(this.gridOptions.suppressScrollOnNewData); } public isRowDragManaged() { return isTrue(this.gridOptions.rowDragManaged); } public isSuppressRowDrag() { return isTrue(this.gridOptions.suppressRowDrag); } public isSuppressMoveWhenRowDragging() { return isTrue(this.gridOptions.suppressMoveWhenRowDragging); } public isEnableMultiRowDragging() { return isTrue(this.gridOptions.enableMultiRowDragging); } // returns either 'print', 'autoHeight' or 'normal' (normal is the default) public getDomLayout(): string { const domLayout = this.gridOptions.domLayout || Constants.DOM_LAYOUT_NORMAL; const validLayouts = [ Constants.DOM_LAYOUT_PRINT, Constants.DOM_LAYOUT_AUTO_HEIGHT, Constants.DOM_LAYOUT_NORMAL ]; if (validLayouts.indexOf(domLayout) === -1) { doOnce( () => console.warn( `ag-Grid: ${domLayout} is not valid for DOM Layout, valid values are ${Constants.DOM_LAYOUT_NORMAL}, ${Constants.DOM_LAYOUT_AUTO_HEIGHT} and ${Constants.DOM_LAYOUT_PRINT}` ), 'warn about dom layout values' ); return Constants.DOM_LAYOUT_NORMAL; } return domLayout; } public isSuppressHorizontalScroll() { return isTrue(this.gridOptions.suppressHorizontalScroll); } public isSuppressMaxRenderedRowRestriction() { return isTrue(this.gridOptions.suppressMaxRenderedRowRestriction); } public isExcludeChildrenWhenTreeDataFiltering() { return isTrue(this.gridOptions.excludeChildrenWhenTreeDataFiltering); } public isAlwaysShowVerticalScroll() { return isTrue(this.gridOptions.alwaysShowVerticalScroll); } public isDebounceVerticalScrollbar() { return isTrue(this.gridOptions.debounceVerticalScrollbar); } public isSuppressLoadingOverlay() { return isTrue(this.gridOptions.suppressLoadingOverlay); } public isSuppressNoRowsOverlay() { return isTrue(this.gridOptions.suppressNoRowsOverlay); } public isSuppressFieldDotNotation() { return isTrue(this.gridOptions.suppressFieldDotNotation); } public getPinnedTopRowData(): any[] | undefined { return this.gridOptions.pinnedTopRowData; } public getPinnedBottomRowData(): any[] | undefined { return this.gridOptions.pinnedBottomRowData; } public isFunctionsPassive() { return isTrue(this.gridOptions.functionsPassive); } public isSuppressChangeDetection() { return isTrue(this.gridOptions.suppressChangeDetection); } public isSuppressAnimationFrame() { return isTrue(this.gridOptions.suppressAnimationFrame); } public getQuickFilterText(): string | undefined { return this.gridOptions.quickFilterText; } public isCacheQuickFilter() { return isTrue(this.gridOptions.cacheQuickFilter); } public isUnSortIcon() { return isTrue(this.gridOptions.unSortIcon); } public isSuppressMenuHide() { return isTrue(this.gridOptions.suppressMenuHide); } public isEnterMovesDownAfterEdit() { return isTrue(this.gridOptions.enterMovesDownAfterEdit); } public isEnterMovesDown() { return isTrue(this.gridOptions.enterMovesDown); } public isUndoRedoCellEditing() { return isTrue(this.gridOptions.undoRedoCellEditing); } public getUndoRedoCellEditingLimit(): number { return this.gridOptions.undoRedoCellEditingLimit; } public getRowStyle() { return this.gridOptions.rowStyle; } public getRowClass() { return this.gridOptions.rowClass; } public getRowStyleFunc() { return this.gridOptions.getRowStyle; } public getRowClassFunc() { return this.gridOptions.getRowClass; } public rowClassRules() { return this.gridOptions.rowClassRules; } public getServerSideStoreType(): string | undefined { return this.gridOptions.serverSideStoreType; } public getServerSideStoreParamsFunc(): ((params: GetServerSideStoreParamsParams) => ServerSideStoreParams) | undefined { return this.gridOptions.getServerSideStoreParams; } public getCreateChartContainerFunc(): ((params: ChartRef) => void) | undefined { return this.gridOptions.createChartContainer; } public getPopupParent() { return this.gridOptions.popupParent; } public getBlockLoadDebounceMillis() { return this.gridOptions.blockLoadDebounceMillis; } public getPostProcessPopupFunc(): ((params: PostProcessPopupParams) => void) | undefined { return this.gridOptions.postProcessPopup; } public getPaginationNumberFormatterFunc(): ((params: PaginationNumberFormatterParams) => string) | undefined { return this.gridOptions.paginationNumberFormatter; } public getChildCountFunc() { return this.gridOptions.getChildCount; } public getDefaultGroupSortComparator() { return this.gridOptions.defaultGroupSortComparator; } public getIsFullWidthCellFunc(): ((rowNode: RowNode) => boolean) | undefined { return this.gridOptions.isFullWidthCell; } public getFullWidthCellRendererParams() { return this.gridOptions.fullWidthCellRendererParams; } public isEmbedFullWidthRows() { return isTrue(this.gridOptions.embedFullWidthRows) || isTrue(this.gridOptions.deprecatedEmbedFullWidthRows); } public isDetailRowAutoHeight() { return isTrue(this.gridOptions.detailRowAutoHeight); } public getSuppressKeyboardEventFunc(): (params: SuppressKeyboardEventParams) => boolean { return this.gridOptions.suppressKeyboardEvent; } public getBusinessKeyForNodeFunc() { return this.gridOptions.getBusinessKeyForNode; } public getApi(): GridApi | undefined | null { return this.gridOptions.api; } public getColumnApi(): ColumnApi | undefined | null { return this.gridOptions.columnApi; } public isImmutableData() { return isTrue(this.gridOptions.immutableData); } public isEnsureDomOrder() { return isTrue(this.gridOptions.ensureDomOrder); } public isEnableCharts() { if (isTrue(this.gridOptions.enableCharts)) { return ModuleRegistry.assertRegistered(ModuleNames.GridChartsModule, 'enableCharts'); } return false; } public getColResizeDefault() { return this.gridOptions.colResizeDefault; } public isSingleClickEdit() { return isTrue(this.gridOptions.singleClickEdit); } public isSuppressClickEdit() { return isTrue(this.gridOptions.suppressClickEdit); } public isStopEditingWhenGridLosesFocus() { return isTrue(this.gridOptions.stopEditingWhenGridLosesFocus); } public getGroupDefaultExpanded(): number | undefined { return this.gridOptions.groupDefaultExpanded; } public getMaxConcurrentDatasourceRequests(): number { return this.gridOptions.maxConcurrentDatasourceRequests; } public getMaxBlocksInCache(): number | undefined { return this.gridOptions.maxBlocksInCache; } public getCacheOverflowSize(): number | undefined { return this.gridOptions.cacheOverflowSize; } public getPaginationPageSize(): number | undefined { return toNumber(this.gridOptions.paginationPageSize); } public isPaginateChildRows(): boolean { const shouldPaginate = this.isGroupRemoveSingleChildren() || this.isGroupRemoveLowestSingleChildren(); if (shouldPaginate) { return true; } return isTrue(this.gridOptions.paginateChildRows); } public getCacheBlockSize(): number | undefined { return this.gridOptions.cacheBlockSize; } public getInfiniteInitialRowCount(): number | undefined { return this.gridOptions.infiniteInitialRowCount; } public isPurgeClosedRowNodes() { return isTrue(this.gridOptions.purgeClosedRowNodes); } public isSuppressPaginationPanel() { return isTrue(this.gridOptions.suppressPaginationPanel); } public getRowData(): any[] | undefined { return this.gridOptions.rowData; } // this property is different - we never allow groupUseEntireRow if in pivot mode, // as otherwise we don't see the pivot values. public isGroupUseEntireRow(pivotMode: boolean) { return pivotMode ? false : isTrue(this.gridOptions.groupUseEntireRow); } public isEnableRtl() { return isTrue(this.gridOptions.enableRtl); } public getAutoGroupColumnDef(): ColDef | undefined { return this.gridOptions.autoGroupColumnDef; } public getRowGroupPanelShow() { return this.gridOptions.rowGroupPanelShow; } public getPivotPanelShow() { return this.gridOptions.pivotPanelShow; } public isAngularCompileRows() { return isTrue(this.gridOptions.angularCompileRows); } public isAngularCompileFilters() { return isTrue(this.gridOptions.angularCompileFilters); } public isDebug() { return isTrue(this.gridOptions.debug); } public getColumnDefs() { return this.gridOptions.columnDefs; } public getColumnTypes(): { [key: string]: ColDef; } | undefined { return this.gridOptions.columnTypes; } public getDatasource(): IDatasource | undefined { return this.gridOptions.datasource; } public getViewportDatasource(): IViewportDatasource { return this.gridOptions.viewportDatasource; } public getServerSideDatasource(): IServerSideDatasource | undefined { return this.gridOptions.serverSideDatasource; } public isAccentedSort() { return isTrue(this.gridOptions.accentedSort); } public isEnableBrowserTooltips() { return isTrue(this.gridOptions.enableBrowserTooltips); } public isEnableCellExpressions() { return isTrue(this.gridOptions.enableCellExpressions); } public isEnableGroupEdit() { return isTrue(this.gridOptions.enableGroupEdit); } public isSuppressMiddleClickScrolls() { return isTrue(this.gridOptions.suppressMiddleClickScrolls); } public isPreventDefaultOnContextMenu() { return isTrue(this.gridOptions.preventDefaultOnContextMenu); } public isSuppressPreventDefaultOnMouseWheel() { return isTrue(this.gridOptions.suppressPreventDefaultOnMouseWheel); } public isSuppressColumnVirtualisation() { return isTrue(this.gridOptions.suppressColumnVirtualisation); } public isSuppressContextMenu() { return isTrue(this.gridOptions.suppressContextMenu); } public isAllowContextMenuWithControlKey() { return isTrue(this.gridOptions.allowContextMenuWithControlKey); } public isSuppressCopyRowsToClipboard() { return isTrue(this.gridOptions.suppressCopyRowsToClipboard); } public isCopyHeadersToClipboard() { return isTrue(this.gridOptions.copyHeadersToClipboard); } public isSuppressClipboardPaste() { return isTrue(this.gridOptions.suppressClipboardPaste); } public isSuppressLastEmptyLineOnPaste() { return isTrue(this.gridOptions.suppressLastEmptyLineOnPaste); } public isPagination() { return isTrue(this.gridOptions.pagination); } public isSuppressEnterpriseResetOnNewColumns() { return isTrue(this.gridOptions.suppressEnterpriseResetOnNewColumns); } public getProcessDataFromClipboardFunc(): ((params: ProcessDataFromClipboardParams) => string[][]) | undefined { return this.gridOptions.processDataFromClipboard; } public getAsyncTransactionWaitMillis(): number | undefined { return exists(this.gridOptions.asyncTransactionWaitMillis) ? this.gridOptions.asyncTransactionWaitMillis : Constants.BATCH_WAIT_MILLIS; } public isSuppressMovableColumns() { return isTrue(this.gridOptions.suppressMovableColumns); } public isAnimateRows() { // never allow animating if enforcing the row order if (this.isEnsureDomOrder()) { return false; } return isTrue(this.gridOptions.animateRows); } public isSuppressColumnMoveAnimation() { return isTrue(this.gridOptions.suppressColumnMoveAnimation); } public isSuppressAggFuncInHeader() { return isTrue(this.gridOptions.suppressAggFuncInHeader); } public isSuppressAggAtRootLevel() { return isTrue(this.gridOptions.suppressAggAtRootLevel); } public isSuppressAggFilteredOnly() { return isTrue(this.gridOptions.suppressAggFilteredOnly); } public isShowOpenedGroup() { return isTrue(this.gridOptions.showOpenedGroup); } public isEnableRangeSelection(): boolean { return ModuleRegistry.isRegistered(ModuleNames.RangeSelectionModule) && isTrue(this.gridOptions.enableRangeSelection); } public isEnableRangeHandle(): boolean { return isTrue(this.gridOptions.enableRangeHandle); } public isEnableFillHandle(): boolean { return isTrue(this.gridOptions.enableFillHandle); } public getFillHandleDirection(): 'x' | 'y' | 'xy' { const direction = this.gridOptions.fillHandleDirection; if (!direction) { return 'xy'; } if (direction !== 'x' && direction !== 'y' && direction !== 'xy') { doOnce(() => console.warn(`ag-Grid: valid values for fillHandleDirection are 'x', 'y' and 'xy'. Default to 'xy'.`), 'warn invalid fill direction'); return 'xy'; } return direction as 'x' | 'y' | 'xy'; } public getFillOperation(): ((params: FillOperationParams) => any) | undefined { return this.gridOptions.fillOperation; } public isSuppressMultiRangeSelection(): boolean { return isTrue(this.gridOptions.suppressMultiRangeSelection); } public isPaginationAutoPageSize(): boolean { return isTrue(this.gridOptions.paginationAutoPageSize); } public isRememberGroupStateWhenNewData(): boolean { return isTrue(this.gridOptions.rememberGroupStateWhenNewData); } public getIcons() { return this.gridOptions.icons; } public getAggFuncs(): { [key: string]: IAggFunc; } | undefined { return this.gridOptions.aggFuncs; } public getSortingOrder(): (string | null)[] | undefined { return this.gridOptions.sortingOrder; } public getAlignedGrids(): GridOptions[] | undefined { return this.gridOptions.alignedGrids; } public isMasterDetail() { const masterDetail = isTrue(this.gridOptions.masterDetail); if (masterDetail) { return ModuleRegistry.assertRegistered(ModuleNames.MasterDetailModule, 'masterDetail'); } else { return false; } } public isKeepDetailRows(): boolean { return isTrue(this.gridOptions.keepDetailRows); } public getKeepDetailRowsCount(): number { if (this.gridOptions.keepDetailRowsCount > 0) { return this.gridOptions.keepDetailRowsCount; } return DEFAULT_KEEP_DETAIL_ROW_COUNT; } public getIsRowMasterFunc(): IsRowMaster | undefined { return this.gridOptions.isRowMaster; } public getIsRowSelectableFunc(): IsRowSelectable | undefined { return this.gridOptions.isRowSelectable; } public getGroupRowRendererParams() { return this.gridOptions.groupRowRendererParams; } public getOverlayLoadingTemplate() { return this.gridOptions.overlayLoadingTemplate; } public getOverlayNoRowsTemplate() { return this.gridOptions.overlayNoRowsTemplate; } public isSuppressAutoSize() { return isTrue(this.gridOptions.suppressAutoSize); } public isEnableCellTextSelection() { return isTrue(this.gridOptions.enableCellTextSelection); } public isSuppressParentsInRowNodes() { return isTrue(this.gridOptions.suppressParentsInRowNodes); } public isSuppressClipboardApi() { return isTrue(this.gridOptions.suppressClipboardApi); } public isFunctionsReadOnly() { return isTrue(this.gridOptions.functionsReadOnly); } public isFloatingFilter(): boolean | undefined { return this.gridOptions.floatingFilter; } public isEnableCellTextSelect(): boolean { return isTrue(this.gridOptions.enableCellTextSelection); } public isEnableOldSetFilterModel(): boolean { return isTrue(this.gridOptions.enableOldSetFilterModel); } public getDefaultColDef(): ColDef | undefined { return this.gridOptions.defaultColDef; } public getDefaultColGroupDef(): ColGroupDef | undefined { return this.gridOptions.defaultColGroupDef; } public getDefaultExportParams(): BaseExportParams | undefined { return this.gridOptions.defaultExportParams; } public isSuppressCsvExport() { return isTrue(this.gridOptions.suppressCsvExport); } public isAllowShowChangeAfterFilter() { return isTrue(this.gridOptions.allowShowChangeAfterFilter); } public isSuppressExcelExport() { return isTrue(this.gridOptions.suppressExcelExport); } public isSuppressMakeColumnVisibleAfterUnGroup() { return isTrue(this.gridOptions.suppressMakeColumnVisibleAfterUnGroup); } public getDataPathFunc(): ((dataItem: any) => string[]) | undefined { return this.gridOptions.getDataPath; } public getIsServerSideGroupFunc(): ((dataItem: any) => boolean) | undefined { return this.gridOptions.isServerSideGroup; } public getIsServerSideGroupOpenByDefaultFunc(): ((params: IsServerSideGroupOpenByDefaultParams) => boolean) | undefined { return this.gridOptions.isServerSideGroupOpenByDefault; } public getServerSideGroupKeyFunc(): ((dataItem: any) => string) | undefined { return this.gridOptions.getServerSideGroupKey; } public getGroupRowAggNodesFunc() { return this.gridOptions.groupRowAggNodes; } public getContextMenuItemsFunc(): GetContextMenuItems | undefined { return this.gridOptions.getContextMenuItems; } public getMainMenuItemsFunc(): GetMainMenuItems | undefined { return this.gridOptions.getMainMenuItems; } public getRowNodeIdFunc(): GetRowNodeIdFunc | undefined { return this.gridOptions.getRowNodeId; } public getNavigateToNextHeaderFunc(): ((params: NavigateToNextHeaderParams) => HeaderPosition) | undefined { return this.gridOptions.navigateToNextHeader; } public getTabToNextHeaderFunc(): ((params: TabToNextHeaderParams) => HeaderPosition) | undefined { return this.gridOptions.tabToNextHeader; } public getNavigateToNextCellFunc(): ((params: NavigateToNextCellParams) => CellPosition) | undefined { return this.gridOptions.navigateToNextCell; } public getTabToNextCellFunc(): ((params: TabToNextCellParams) => CellPosition) | undefined { return this.gridOptions.tabToNextCell; } public isTreeData(): boolean { const usingTreeData = isTrue(this.gridOptions.treeData); if (usingTreeData) { return ModuleRegistry.assertRegistered(ModuleNames.RowGroupingModule, 'Tree Data'); } else { return false; } } public isValueCache(): boolean { return isTrue(this.gridOptions.valueCache); } public isValueCacheNeverExpires(): boolean { return isTrue(this.gridOptions.valueCacheNeverExpires); } public isDeltaSort(): boolean { return isTrue(this.gridOptions.deltaSort); } public isAggregateOnlyChangedColumns(): boolean { return isTrue(this.gridOptions.aggregateOnlyChangedColumns); } public getProcessSecondaryColDefFunc(): ((colDef: ColDef) => void) | undefined { return this.gridOptions.processSecondaryColDef; } public getProcessSecondaryColGroupDefFunc(): ((colGroupDef: ColGroupDef) => void) | undefined { return this.gridOptions.processSecondaryColGroupDef; } public getSendToClipboardFunc() { return this.gridOptions.sendToClipboard; } public getProcessRowPostCreateFunc(): any { return this.gridOptions.processRowPostCreate; } public getProcessCellForClipboardFunc(): ((params: ProcessCellForExportParams) => any) | undefined { return this.gridOptions.processCellForClipboard; } public getProcessHeaderForClipboardFunc(): ((params: ProcessHeaderForExportParams) => any) | undefined { return this.gridOptions.processHeaderForClipboard; } public getProcessCellFromClipboardFunc(): ((params: ProcessCellForExportParams) => any) | undefined { return this.gridOptions.processCellFromClipboard; } public getViewportRowModelPageSize(): number { return oneOrGreater(this.gridOptions.viewportRowModelPageSize, DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE); } public getViewportRowModelBufferSize(): number { return zeroOrGreater(this.gridOptions.viewportRowModelBufferSize, DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE); } public isServerSideSortingAlwaysResets() { return isTrue(this.gridOptions.serverSideSortingAlwaysResets); } public isServerSideFilteringAlwaysResets() { return isTrue(this.gridOptions.serverSideFilteringAlwaysResets); } public getPostSortFunc(): ((rowNodes: RowNode[]) => void) | undefined { return this.gridOptions.postSort; } public getChartToolbarItemsFunc(): GetChartToolbarItems | undefined { return this.gridOptions.getChartToolbarItems; } public getChartThemeOverrides(): AgChartThemeOverrides | undefined { return this.gridOptions.chartThemeOverrides; } public getCustomChartThemes(): { [name: string]: AgChartTheme; } | undefined { return this.gridOptions.customChartThemes; } public getChartThemes(): string[] { // return default themes if user hasn't supplied any return this.gridOptions.chartThemes || ['ag-default', 'ag-material', 'ag-pastel', 'ag-vivid', 'ag-solar']; } public getProcessChartOptionsFunc(): (params: ProcessChartOptionsParams) => ChartOptions<any> { return this.gridOptions.processChartOptions; } public getClipboardDeliminator() { return exists(this.gridOptions.clipboardDeliminator) ? this.gridOptions.clipboardDeliminator : '\t'; } public setProperty(key: string, value: any, force = false): void { const gridOptionsNoType = this.gridOptions as any; const previousValue = gridOptionsNoType[key]; if (force || previousValue !== value) { gridOptionsNoType[key] = value; const event: PropertyChangedEvent = { type: key, currentValue: value, previousValue: previousValue }; this.propertyEventService.dispatchEvent(event); } } // this logic is repeated in lots of places. any element that had different CSS // dependent on the layout needs to have the layout class added ot it. public addLayoutElement(element: HTMLElement): void { this.layoutElements.push(element); this.updateLayoutClasses(); } private updateLayoutClasses(): void { const domLayout = this.getDomLayout(); const domLayoutAutoHeight = domLayout === Constants.DOM_LAYOUT_AUTO_HEIGHT; const domLayoutPrint = domLayout === Constants.DOM_LAYOUT_PRINT; const domLayoutNormal = domLayout === Constants.DOM_LAYOUT_NORMAL; this.layoutElements.forEach(e => { addOrRemoveCssClass(e, 'ag-layout-auto-height', domLayoutAutoHeight); addOrRemoveCssClass(e, 'ag-layout-normal', domLayoutNormal); addOrRemoveCssClass(e, 'ag-layout-print', domLayoutPrint); }); } public addEventListener(key: string, listener: Function): void { this.propertyEventService.addEventListener(key, listener); } public removeEventListener(key: string, listener: Function): void { this.propertyEventService.removeEventListener(key, listener); } public isSkipHeaderOnAutoSize(): boolean { return !!this.gridOptions.skipHeaderOnAutoSize; } public getAutoSizePadding(): number { const value = this.gridOptions.autoSizePadding; return value != null && value >= 0 ? value : 20; } // properties public getHeaderHeight(): number { if (typeof this.gridOptions.headerHeight === 'number') { return this.gridOptions.headerHeight; } return this.getFromTheme(25, 'headerHeight'); } public getFloatingFiltersHeight(): number { if (typeof this.gridOptions.floatingFiltersHeight === 'number') { return this.gridOptions.floatingFiltersHeight; } return this.getFromTheme(25, 'headerHeight'); } public getGroupHeaderHeight(): number { if (typeof this.gridOptions.groupHeaderHeight === 'number') { return this.gridOptions.groupHeaderHeight; } return this.getHeaderHeight(); } public getPivotHeaderHeight(): number { if (typeof this.gridOptions.pivotHeaderHeight === 'number') { return this.gridOptions.pivotHeaderHeight; } return this.getHeaderHeight(); } public getPivotGroupHeaderHeight(): number { if (typeof this.gridOptions.pivotGroupHeaderHeight === 'number') { return this.gridOptions.pivotGroupHeaderHeight; } return this.getGroupHeaderHeight(); } public isExternalFilterPresent() { if (typeof this.gridOptions.isExternalFilterPresent === 'function') { return this.gridOptions.isExternalFilterPresent(); } return false; } public doesExternalFilterPass(node: RowNode) { if (typeof this.gridOptions.doesExternalFilterPass === 'function') { return this.gridOptions.doesExternalFilterPass(node); } return false; } public getTooltipShowDelay(): number { const { tooltipShowDelay } = this.gridOptions; if (exists(tooltipShowDelay)) { if (tooltipShowDelay < 0) { console.warn('ag-grid: tooltipShowDelay should not be lower than 0'); } return Math.max(200, tooltipShowDelay); } return null; } public isTooltipMouseTrack() { return isTrue(this.gridOptions.tooltipMouseTrack); } public getDocument(): Document { // if user is providing document, we use the users one, // otherwise we use the document on the global namespace. let result: Document | null = null; if (this.gridOptions.getDocument && exists(this.gridOptions.getDocument)) { result = this.gridOptions.getDocument(); } if (result && exists(result)) { return result; } return document; } public getMinColWidth() { if (this.gridOptions.minColWidth > GridOptionsWrapper.MIN_COL_WIDTH) { return this.gridOptions.minColWidth; } const measuredMin = this.getFromTheme(null, 'headerCellMinWidth'); return Math.max(measuredMin, GridOptionsWrapper.MIN_COL_WIDTH); } public getMaxColWidth() { if (this.gridOptions.maxColWidth && this.gridOptions.maxColWidth > GridOptionsWrapper.MIN_COL_WIDTH) { return this.gridOptions.maxColWidth; } return null; } public getColWidth() { if (typeof this.gridOptions.colWidth !== 'number' || this.gridOptions.colWidth < GridOptionsWrapper.MIN_COL_WIDTH) { return 200; } return this.gridOptions.colWidth; } public getRowBuffer(): number { let rowBuffer = this.gridOptions.rowBuffer; if (typeof rowBuffer === 'number') { if (rowBuffer < 0) { doOnce(() => console.warn(`ag-Grid: rowBuffer should not be negative`), 'warn rowBuffer negative'); this.gridOptions.rowBuffer = rowBuffer = 0; } } else { rowBuffer = Constants.ROW_BUFFER_SIZE; } return rowBuffer; } public getRowBufferInPixels() { const rowsToBuffer = this.getRowBuffer(); const defaultRowHeight = this.getRowHeightAsNumber(); return rowsToBuffer * defaultRowHeight; } // the user might be using some non-standard scrollbar, eg a scrollbar that has zero // width and overlays (like the Safari scrollbar, but presented in Chrome). so we // allow the user to provide the scroll width before we work it out. public getScrollbarWidth() { if (this.scrollbarWidth == null) { const useGridOptions = typeof this.gridOptions.scrollbarWidth === 'number' && this.gridOptions.scrollbarWidth >= 0; const scrollbarWidth = useGridOptions ? this.gridOptions.scrollbarWidth : getScrollbarWidth(); if (scrollbarWidth != null) { this.scrollbarWidth = scrollbarWidth; this.eventService.dispatchEvent({ type: Events.EVENT_SCROLLBAR_WIDTH_CHANGED }); } } return this.scrollbarWidth; } private checkForDeprecated() { // casting to generic object, so typescript compiles even though // we are looking for attributes that don't exist const options: any = this.gridOptions; if (options.deprecatedEmbedFullWidthRows) { console.warn(`ag-Grid: since v21.2, deprecatedEmbedFullWidthRows has been replaced with embedFullWidthRows.`); } if (options.enableOldSetFilterModel) { console.warn( 'ag-Grid: since v22.x, enableOldSetFilterModel is deprecated. Please move to the new Set Filter Model as the old one may not be supported in v23 onwards.' ); } if (options.floatingFilter) { console.warn( 'ag-Grid: since v23.1, floatingFilter on the gridOptions is deprecated. Please use floatingFilter on the colDef instead.' ); if (!options.defaultColDef) { options.defaultColDef = {}; } if (options.defaultColDef.floatingFilter == null) { options.defaultColDef.floatingFilter = true; } } if (options.rowDeselection) { console.warn( 'ag-Grid: since v24.x, rowDeselection is deprecated and the behaviour is true by default. Please use `suppressRowDeselection` to prevent rows from being deselected.' ); } const checkRenamedProperty = (oldProp: string, newProp: string, version: string) => { if (options[oldProp] != null) { console.warn(`ag-grid: since version ${version}, '${oldProp}' is deprecated / renamed, please use the new property name '${newProp}' instead.`); if (options[newProp] == null) { options[newProp] = options[oldProp]; } } }; checkRenamedProperty('batchUpdateWaitMillis', 'asyncTransactionWaitMillis', '23.1.x'); checkRenamedProperty('deltaRowDataMode', 'immutableData', '23.1.x'); if (options.immutableColumns || options.deltaColumnMode) { console.warn( 'ag-Grid: since v24.0, immutableColumns and deltaColumnMode properties are gone. The grid now works like this as default. To keep column order maintained, set grid property applyColumnDefOrder=true' ); } checkRenamedProperty('suppressSetColumnStateEvents', 'suppressColumnStateEvents', '24.0.x'); if (options.groupRowInnerRenderer || options.groupRowInnerRendererParams || options.groupRowInnerRendererFramework) { console.warn('ag-Grid: since v24.0, grid properties groupRowInnerRenderer, groupRowInnerRendererFramework and groupRowInnerRendererParams are no longer used.'); console.warn(' Instead use the grid properties groupRowRendererParams.innerRenderer, groupRowRendererParams.innerRendererFramework and groupRowRendererParams.innerRendererParams.'); console.warn(' For example instead of this:'); console.warn(' groupRowInnerRenderer: "myRenderer"'); console.warn(' groupRowInnerRendererParams: {x: a}'); console.warn(' Replace with this:'); console.warn(' groupRowRendererParams: {'); console.warn(' innerRenderer: "myRenderer",'); console.warn(' innerRendererParams: {x: a}'); console.warn(' }'); console.warn(' We have copied the properties over for you. However to stop this error message, please change your application code.'); if (!options.groupRowRendererParams) { options.groupRowRendererParams = {}; } const params = options.groupRowRendererParams; if (options.groupRowInnerRenderer) { params.innerRenderer = options.groupRowInnerRenderer; } if (options.groupRowInnerRendererParams) { params.innerRendererParams = options.groupRowInnerRendererParams; } if (options.groupRowInnerRendererFramework) { params.innerRendererFramework = options.groupRowInnerRendererFramework; } } if (options.rememberGroupStateWhenNewData) { console.warn('ag-Grid: since v24.0, grid property rememberGroupStateWhenNewData is deprecated. This feature was provided before Transaction Updates worked (which keep group state). Now that transaction updates are possible and they keep group state, this feature is no longer needed.'); } if (options.detailCellRendererParams && options.detailCellRendererParams.autoHeight) { console.warn('ag-Grid: since v24.1, grid property detailCellRendererParams.autoHeight is replaced with grid property detailRowAutoHeight. This allows this feature to work when you provide a custom DetailCellRenderer'); options.detailRowAutoHeight = true; } if (options.suppressKeyboardEvent) { console.warn( `ag-Grid: since v24.1 suppressKeyboardEvent in the gridOptions has been deprecated and will be removed in future versions of ag-Grid. If you need this to be set for every column use the defaultColDef property.` ); } } private checkForViolations() { if (this.isTreeData()) { this.treeDataViolations(); } } private treeDataViolations() { if (this.isRowModelDefault()) { if (missing(this.getDataPathFunc())) { console.warn( 'ag-Grid: property usingTreeData=true with rowModel=clientSide, but you did not ' + 'provide getDataPath function, please provide getDataPath function if using tree data.' ); } } if (this.isRowModelServerSide()) { if (missing(this.getIsServerSideGroupFunc())) { console.warn( 'ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not ' + 'provide isServerSideGroup function, please provide isServerSideGroup function if using tree data.' ); } if (missing(this.getServerSideGroupKeyFunc())) { console.warn( 'ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not ' + 'provide getServerSideGroupKey function, please provide getServerSideGroupKey function if using tree data.' ); } } } public getLocaleTextFunc(): (key: string, defaultValue: string) => string { if (this.gridOptions.localeTextFunc) { return this.gridOptions.localeTextFunc; } const { localeText } = this.gridOptions; return (key: string, defaultValue: string) => { return localeText && localeText[key] ? localeText[key] : defaultValue; }; } // responsible for calling the onXXX functions on gridOptions public globalEventHandler(eventName: string, event?: any): void { // prevent events from being fired _after_ the grid has been destroyed if (this.destroyed) { return; } const callbackMethodName = ComponentUtil.getCallbackForEvent(eventName); if (typeof (this.gridOptions as any)[callbackMethodName] === 'function') { (this.gridOptions as any)[callbackMethodName](event); } } // we don't allow dynamic row height for virtual paging public getRowHeightAsNumber(): number { if (!this.gridOptions.rowHeight || missing(this.gridOptions.rowHeight)) { return this.getDefaultRowHeight(); } if (this.gridOptions.rowHeight && this.isNumeric(this.gridOptions.rowHeight)) { return this.gridOptions.rowHeight; } console.warn('ag-Grid row height must be a number if not using standard row model'); return this.getDefaultRowHeight(); } public getRowHeightForNode(rowNode: RowNode, allowEstimate = false): { height: number; estimated: boolean; } { // check the function first, in case use set both function and // number, when using virtual pagination then function can be // used for pinned rows and the number for the body rows. if (typeof this.gridOptions.getRowHeight === 'function') { if (allowEstimate) { return { height: this.getDefaultRowHeight(), estimated: true }; } const params = { node: rowNode, data: rowNode.data, api: this.gridOptions.api, context: this.gridOptions.context }; const height = this.gridOptions.getRowHeight(params); if (this.isNumeric(height)) { return { height, estimated: false }; } } if (rowNode.detail && this.isMasterDetail()) { if (this.isNumeric(this.gridOptions.detailRowHeight)) { return { height: this.gridOptions.detailRowHeight, estimated: false }; } return { height: DEFAULT_DETAIL_ROW_HEIGHT, estimated: false }; } const defaultRowHeight = this.getDefaultRowHeight(); const rowHeight = this.gridOptions.rowHeight && this.isNumeric(this.gridOptions.rowHeight) ? this.gridOptions.rowHeight : defaultRowHeight; const minRowHeight = Math.min(defaultRowHeight, rowHeight); if (this.columnController.isAutoRowHeightActive()) { if (allowEstimate) { return { height: rowHeight, estimated: true }; } const autoHeight = this.autoHeightCalculator.getPreferredHeightForRow(rowNode); // never return less than the default row height - covers when auto height // cells are blank. return { height: Math.max(autoHeight, minRowHeight), estimated: false }; } return { height: rowHeight, estimated: false }; } public isDynamicRowHeight(): boolean { return typeof this.gridOptions.getRowHeight === 'function'; } public getListItemHeight() { return this.getFromTheme(20, 'listItemHeight'); } public chartMenuPanelWidth() { return this.environment.chartMenuPanelWidth(); } private isNumeric(value: any) { return !isNaN(value) && typeof value === 'number' && isFinite(value); } // Material data table has strict guidelines about whitespace, and these values are different than the ones // ag-grid uses by default. We override the default ones for the sake of making it better out of the box private getFromTheme(defaultValue: number, sassVariableName: SASS_PROPERTIES): number { const { theme } = this.environment.getTheme(); if (theme && theme.indexOf('ag-theme') === 0) { return this.environment.getSassVariable(theme, sassVariableName); } return defaultValue; } private getDefaultRowHeight(): number { return this.getFromTheme(DEFAULT_ROW_HEIGHT, 'rowHeight'); } }
jenkins-sigaut/ag-grid
grid-packages/ag-grid-docs/documentation/src/pages/component-cell-editor/examples/component-editor/mood-editor.component_angular.ts
<filename>grid-packages/ag-grid-docs/documentation/src/pages/component-cell-editor/examples/component-editor/mood-editor.component_angular.ts import { AfterViewInit, Component, ViewChild, ViewContainerRef } from "@angular/core"; import { ICellEditorAngularComp } from "@ag-grid-community/angular"; @Component({ selector: 'editor-cell', template: ` <div #container class="mood" tabindex="0" (keydown)="onKeyDown($event)"> <img src="https://www.ag-grid.com/example-assets/smileys/happy.png" (click)="onClick(true)" [ngClass]="{'selected' : happy, 'default' : !happy}"> <img src="https://www.ag-grid.com/example-assets/smileys/sad.png" (click)="onClick(false)" [ngClass]="{'selected' : !happy, 'default' : happy}"> </div> `, styles: [` .mood { border-radius: 15px; border: 1px solid grey; background: #e6e6e6; padding: 15px; text-align: center; display: inline-block; outline: none } .default { padding-left: 10px; padding-right: 10px; border: 1px solid transparent; padding: 4px; } .selected { padding-left: 10px; padding-right: 10px; border: 1px solid lightgreen; padding: 4px; } `] }) export class MoodEditor implements ICellEditorAngularComp, AfterViewInit { private params: any; @ViewChild('container', { read: ViewContainerRef }) public container; public happy: boolean = false; // dont use afterGuiAttached for post gui events - hook into ngAfterViewInit instead for this ngAfterViewInit() { window.setTimeout(() => { this.container.element.nativeElement.focus(); }); } agInit(params: any): void { this.params = params; this.setHappy(params.value === "Happy"); } getValue(): any { return this.happy ? "Happy" : "Sad"; } isPopup(): boolean { return true; } setHappy(happy: boolean): void { this.happy = happy; } toggleMood(): void { this.setHappy(!this.happy); } onClick(happy: boolean) { this.setHappy(happy); this.params.api.stopEditing(); } onKeyDown(event): void { let key = event.which || event.keyCode; if (key == 37 || // left key == 39) { // right this.toggleMood(); event.stopPropagation(); } } }
jenkins-sigaut/ag-grid
enterprise-modules/charts/src/charts/chartComp/menu/settings/chartSettingsPanel.ts
import { _, Component, PostConstruct, RefSelector } from "@ag-grid-community/core"; import { MiniChartsContainer } from "./miniChartsContainer"; import { AgChartThemePalette } from "ag-charts-community"; import { ChartController } from "../../chartController"; type AnimationDirection = 'left' | 'right'; export class ChartSettingsPanel extends Component { public static TEMPLATE = /* html */ `<div class="ag-chart-settings-wrapper"> <div ref="eMiniChartsContainer" class="ag-chart-settings-mini-charts-container"></div> <div ref="eNavBar" class="ag-chart-settings-nav-bar"> <div ref="ePrevBtn" class="ag-chart-settings-prev"> <button type="button" class="ag-chart-settings-prev-button"></button> </div> <div ref="eCardSelector" class="ag-chart-settings-card-selector"></div> <div ref="eNextBtn" class="ag-chart-settings-next"> <button type="button" class="ag-chart-settings-next-button"></button> </div> </div> </div>`; @RefSelector('eMiniChartsContainer') private readonly eMiniChartsContainer: HTMLElement; @RefSelector('eNavBar') private readonly eNavBar: HTMLElement; @RefSelector('eCardSelector') private readonly eCardSelector: HTMLElement; @RefSelector('ePrevBtn') private readonly ePrevBtn: HTMLElement; @RefSelector('eNextBtn') private readonly eNextBtn: HTMLElement; private miniCharts: MiniChartsContainer[] = []; private cardItems: HTMLElement[] = []; private readonly chartController: ChartController; private activePaletteIndex = 0; private palettes: AgChartThemePalette[] = []; private themes: string[] = []; private isAnimating: boolean; constructor(chartController: ChartController) { super(ChartSettingsPanel.TEMPLATE); this.chartController = chartController; } @PostConstruct private postConstruct() { this.resetPalettes(); this.ePrevBtn.insertAdjacentElement('afterbegin', _.createIconNoSpan('previous', this.gridOptionsWrapper)); this.eNextBtn.insertAdjacentElement('afterbegin', _.createIconNoSpan('next', this.gridOptionsWrapper)); this.addManagedListener(this.ePrevBtn, 'click', () => this.setActivePalette(this.getPrev(), 'left')); this.addManagedListener(this.eNextBtn, 'click', () => this.setActivePalette(this.getNext(), 'right')); this.addManagedListener(this.chartController, ChartController.EVENT_CHART_UPDATED, this.resetPalettes.bind(this)); } private resetPalettes(): void { const palettes = this.chartController.getPalettes(); if (_.shallowCompare(palettes, this.palettes)) { return; } this.palettes = palettes; this.themes = this.chartController.getThemes(); this.activePaletteIndex = _.findIndex(this.themes, name => name === this.chartController.getThemeName()); this.cardItems = []; _.clearElement(this.eCardSelector); this.destroyMiniCharts(); this.palettes.forEach((palette, index) => { const isActivePalette = this.activePaletteIndex === index; const { fills, strokes } = palette; const miniChartsContainer = this.createBean(new MiniChartsContainer(this.chartController, fills, strokes)); this.miniCharts.push(miniChartsContainer); this.eMiniChartsContainer.appendChild(miniChartsContainer.getGui()); this.addCardLink(index); if (isActivePalette) { miniChartsContainer.refreshSelected(); } else { _.addCssClass(miniChartsContainer.getGui(), 'ag-hidden'); } }); _.addOrRemoveCssClass(this.eNavBar, 'ag-hidden', this.palettes.length <= 1); _.radioCssClass(this.cardItems[this.activePaletteIndex], 'ag-selected', 'ag-not-selected'); } private addCardLink(index: number): void { const link = document.createElement('div'); _.addCssClass(link, 'ag-chart-settings-card-item'); this.addManagedListener(link, 'click', () => { const { activePaletteIndex } = this; this.setActivePalette(index, index < activePaletteIndex ? 'left' : 'right'); }); this.eCardSelector.appendChild(link); this.cardItems.push(link); } private getPrev(): number { let prev = this.activePaletteIndex - 1; if (prev < 0) { prev = this.palettes.length - 1; } return prev; } private prev() { ; } private getNext(): number { let next = this.activePaletteIndex + 1; if (next >= this.palettes.length) { next = 0; } return next; } private setActivePalette(index: number, animationDirection: AnimationDirection) { if (this.isAnimating || this.activePaletteIndex === index) { return; } _.radioCssClass(this.cardItems[index], 'ag-selected', 'ag-not-selected'); const currentPalette = this.miniCharts[this.activePaletteIndex]; const currentGui = currentPalette.getGui(); const futurePalette = this.miniCharts[index]; const nextGui = futurePalette.getGui(); currentPalette.refreshSelected(); futurePalette.refreshSelected(); const multiplier = animationDirection === 'left' ? -1 : 1; const final = nextGui.style.left = `${(_.getAbsoluteWidth(this.getGui()) * multiplier)}px`; const animatingClass = 'ag-animating'; _.removeCssClass(nextGui, 'ag-hidden'); _.addCssClass(currentGui, animatingClass); _.addCssClass(nextGui, animatingClass); this.activePaletteIndex = index; this.chartController.setChartThemeName(this.themes[index]); this.isAnimating = true; window.setTimeout(() => { currentGui.style.left = `${-parseFloat(final)}px`; nextGui.style.left = '0px'; }, 0); window.setTimeout(() => { this.isAnimating = false; _.removeCssClass(currentGui, animatingClass); _.removeCssClass(nextGui, animatingClass); _.addCssClass(currentGui, 'ag-hidden'); }, 300); } private destroyMiniCharts(): void { _.clearElement(this.eMiniChartsContainer); this.miniCharts = this.destroyBeans(this.miniCharts); } protected destroy(): void { this.destroyMiniCharts(); super.destroy(); } }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/widgets/agToggleButton.d.ts
<gh_stars>0 // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { AgCheckbox } from './agCheckbox'; import { IInputField } from './agAbstractInputField'; export declare class AgToggleButton extends AgCheckbox { constructor(config?: IInputField); setValue(value: boolean, silent?: boolean): this; }
jenkins-sigaut/ag-grid
community-modules/core/dist/es6/components/agStackComponentsRegistry.d.ts
<reponame>jenkins-sigaut/ag-grid // Type definitions for @ag-grid-community/core v25.0.0 // Project: http://www.ag-grid.com/ // Definitions by: <NAME> <https://github.com/ag-grid/> import { ComponentMeta } from "../context/context"; import { BeanStub } from "../context/beanStub"; export declare class AgStackComponentsRegistry extends BeanStub { private componentsMappedByName; setupComponents(components: ComponentMeta[]): void; private addComponent; getComponentClass(htmlTag: string): any; }
jenkins-sigaut/ag-grid
charts-packages/ag-charts-react/lib/main.d.ts
<gh_stars>0 // ag-charts-react v3.0.0 export * from './agChartsReact';
super-effective/colorutil
src/tests/hexToHsl.test.ts
import hexToHsl from '../hexToHsl'; import { HEX_TEAL, HEX_WHITE, HEX_BLACK, HEX_RED, HEX_YELLOW, HEX_GREEN, HEX_CYAN, HEX_BLUE, HEX_MAGENTA, HSL_BLACK, HSL_BLUE, HSL_CYAN, HSL_GREEN, HSL_MAGENTA, HSL_RED, HSL_TEAL, HSL_WHITE, HSL_YELLOW, } from './data/colors'; /** * HEX to HSL */ describe('hexToHsl', () => { test('hexToHsl - color', () => { const teal = hexToHsl(HEX_TEAL); expect(teal).toStrictEqual(HSL_TEAL); }); test('hexToHsl - white short', () => { const white = hexToHsl('#fff'); expect(white).toStrictEqual(HSL_WHITE); }); test('hexToHsl - white long', () => { const white = hexToHsl(HEX_WHITE); expect(white).toStrictEqual(HSL_WHITE); }); test('hexToHsl - black short', () => { const white = hexToHsl('#000'); expect(white).toStrictEqual(HSL_BLACK); }); test('hexToHsl - black long', () => { const white = hexToHsl(HEX_BLACK); expect(white).toStrictEqual(HSL_BLACK); }); test('hexToHsl - short length throws an error', () => { expect(() => hexToHsl('#00')).toThrow(Error); }); test('hexToHsl - long length throws an error', () => { expect(() => hexToHsl('#0000000')).toThrow(Error); }); test('hexToHsl - invalid hex', () => { expect(() => hexToHsl('#j@0000')).toThrow(Error); }); test('hexToHsl - red', () => { const teal = hexToHsl(HEX_RED); expect(teal).toStrictEqual(HSL_RED); }); test('hexToHsl - yellow', () => { const teal = hexToHsl(HEX_YELLOW); expect(teal).toStrictEqual(HSL_YELLOW); }); test('hexToHsl - green', () => { const teal = hexToHsl(HEX_GREEN); expect(teal).toStrictEqual(HSL_GREEN); }); test('hexToHsl - cyan', () => { const teal = hexToHsl(HEX_CYAN); expect(teal).toStrictEqual(HSL_CYAN); }); test('hexToHsl - blue', () => { const teal = hexToHsl(HEX_BLUE); expect(teal).toStrictEqual(HSL_BLUE); }); test('hexToHsl - magenta', () => { const teal = hexToHsl(HEX_MAGENTA); expect(teal).toStrictEqual(HSL_MAGENTA); }); });
super-effective/colorutil
src/hexToHsv.ts
<reponame>super-effective/colorutil import { Hsv } from './colorTypes'; import hexToRgb from './hexToRgb'; import rgbToHsv from './rgbToHsv'; /** * Converts a hex color string to its hue, saturation, and value * @param {string} colorHex The color value in hex format * @returns {Hsv} The HSV values for the color */ export default function hexToHsv(colorHex: string): Hsv { // Hex validation handled by hexToRgb const { red, green, blue, } = hexToRgb(colorHex); return rgbToHsv(red, green, blue); }
super-effective/colorutil
src/tests/data/colors.ts
// Known HEX Values export const HEX_TEAL = '#3cd6bf'; export const HEX_WHITE = '#ffffff'; export const HEX_BLACK = '#000000'; export const HEX_RED = '#ff0000'; export const HEX_YELLOW = '#ffff00'; export const HEX_GREEN = '#00ff00'; export const HEX_CYAN = '#00ffff'; export const HEX_BLUE = '#0000ff'; export const HEX_MAGENTA = '#ff00ff'; // Known RGB Values export const RGB_TEAL = { red: 60, green: 214, blue: 191, }; export const RGB_DARK_TEAL = { red: 41, green: 140, blue: 125, }; export const RGB_WHITE = { red: 255, green: 255, blue: 255, }; export const RGB_BLACK = { red: 0, green: 0, blue: 0, }; export const RGB_RED = { red: 255, green: 0, blue: 0, }; export const RGB_YELLOW = { red: 255, green: 255, blue: 0, }; export const RGB_GREEN = { red: 0, green: 255, blue: 0, }; export const RGB_CYAN = { red: 0, green: 255, blue: 255, }; export const RGB_BLUE = { red: 0, green: 0, blue: 255, }; export const RGB_MAGENTA = { red: 255, green: 0, blue: 255, }; // Known CMYK Values export const CMYK_TEAL = { cyan: 0.719626168224299, magenta: 0, yellow: 0.1074766355140187, black: 0.16078431372549018, } export const CMYK_RED = { cyan: 0, magenta: 1, yellow: 1, black: 0, } export const CMYK_GREEN = { cyan: 1, magenta: 0, yellow: 1, black: 0, } export const CMYK_BLUE = { cyan: 1, magenta: 1, yellow: 0, black: 0, } export const CMYK_BLACK = { cyan: 0, magenta: 0, yellow: 0, black: 1, } // Known HSL Values export const HSL_TEAL = { hue: 171.03896103896102, saturation: 0.6525423728813562, lightness: 0.5372549019607843, }; export const HSL_DARK_TEAL = { hue: 170.90909090909088, saturation: 0.5469613259668509, lightness: 0.35490196078431374, }; export const HSL_WHITE = { hue: 0, saturation: 0, lightness: 1, }; export const HSL_BLACK = { hue: 0, saturation: 0, lightness: 0, }; export const HSL_RED = { hue: 0, saturation: 1, lightness: 0.5, }; export const HSL_YELLOW = { hue: 60, saturation: 1, lightness: 0.5, }; export const HSL_GREEN = { hue: 120, saturation: 1, lightness: 0.5, }; export const HSL_CYAN = { hue: 180, saturation: 1, lightness: 0.5, }; export const HSL_BLUE = { hue: 240, saturation: 1, lightness: 0.5, }; export const HSL_MAGENTA = { hue: 300, saturation: 1, lightness: 0.5, }; // Known HSV Values export const HSV_TEAL = { hue: 171.03896103896102, saturation: 0.7196261682242991, value: 0.8392156862745098, }; export const HSV_WHITE = { hue: 0, saturation: 0, value: 1, }; export const HSV_BLACK = { hue: 0, saturation: 0, value: 0, }; export const HSV_RED = { hue: 0, saturation: 1, value: 1, }; export const HSV_YELLOW = { hue: 60, saturation: 1, value: 1, }; export const HSV_GREEN = { hue: 120, saturation: 1, value: 1, }; export const HSV_CYAN = { hue: 180, saturation: 1, value: 1, }; export const HSV_BLUE = { hue: 240, saturation: 1, value: 1, }; export const HSV_MAGENTA = { hue: 300, saturation: 1, value: 1, };
super-effective/colorutil
src/hexToRgb.ts
<filename>src/hexToRgb.ts<gh_stars>1-10 import { Rgb } from 'colorTypes'; /** * Converts a hex color string to its red, green, and blue component values * @param {string} colorHex The color value in hex format * @returns {Rgb} The RGB values for the color */ export default function hexToRgb(colorHex: string): Rgb { let sanitizedHex = colorHex.replace(/[^a-fA-F0-9]/g, ''); if (sanitizedHex.length !== 6 && sanitizedHex.length !== 3) { throw new Error(`Color should be either 3 or 6 characters in length - received a length of ${sanitizedHex.length}`); } if (sanitizedHex.length === 3) { sanitizedHex = `${sanitizedHex[0].repeat(2)}${sanitizedHex[1].repeat(2)}${sanitizedHex[2].repeat(2)}`; } const rgb = parseInt(sanitizedHex, 16); if (Number.isNaN(rgb)) { throw new Error(`Unable to parse hex color ${colorHex}`); } const red = (rgb >> 16) & 0xff; const green = (rgb >> 8) & 0xff; const blue = (rgb) & 0xff; return { red, green, blue, }; }
super-effective/colorutil
src/tests/rgbToHex.test.ts
<reponame>super-effective/colorutil import rgbToHex from '../rgbToHex'; import { RGB_TEAL, HEX_TEAL, RGB_WHITE, HEX_WHITE, RGB_BLACK, HEX_BLACK, } from './data/colors'; /** * RGB to HEX */ describe('rgbToHex', () => { test('rgbToHex - multi value', () => { const teal = rgbToHex(RGB_TEAL.red, RGB_TEAL.green, RGB_TEAL.blue); expect(teal).toBe(HEX_TEAL); }); test('rgbToHex - white', () => { const white = rgbToHex(RGB_WHITE.red, RGB_WHITE.green, RGB_WHITE.blue); expect(white).toBe(HEX_WHITE); }); test('rgbToHex - black', () => { const black = rgbToHex(RGB_BLACK.red, RGB_BLACK.green, RGB_BLACK.blue); expect(black).toBe(HEX_BLACK); }); });
super-effective/colorutil
src/tests/hslToRgb.test.ts
<reponame>super-effective/colorutil<gh_stars>1-10 import hslToRgb from '../hslToRgb'; import { RGB_DARK_TEAL, RGB_TEAL, RGB_WHITE, RGB_BLACK, RGB_RED, RGB_YELLOW, RGB_GREEN, RGB_CYAN, RGB_BLUE, RGB_MAGENTA, HSL_BLACK, HSL_BLUE, HSL_CYAN, HSL_GREEN, HSL_MAGENTA, HSL_RED, HSL_TEAL, HSL_WHITE, HSL_YELLOW, HSL_DARK_TEAL, } from './data/colors'; /** * HSL to RGB */ describe('hslToRgb', () => { test('hslToRgb - color', () => { const teal = hslToRgb(HSL_TEAL.hue, HSL_TEAL.saturation, HSL_TEAL.lightness); expect(teal).toStrictEqual(RGB_TEAL); }); test('hslToRgb - dark color', () => { const teal = hslToRgb(HSL_DARK_TEAL.hue, HSL_DARK_TEAL.saturation, HSL_DARK_TEAL.lightness); expect(teal).toStrictEqual(RGB_DARK_TEAL); }); test('hslToRgb - white', () => { const white = hslToRgb(HSL_WHITE.hue, HSL_WHITE.saturation, HSL_WHITE.lightness); expect(white).toStrictEqual(RGB_WHITE); }); test('hslToRgb - black', () => { const black = hslToRgb(HSL_BLACK.hue, HSL_BLACK.saturation, HSL_BLACK.lightness); expect(black).toStrictEqual(RGB_BLACK); }); // Bounds checks test('hslToRgb - invalid hue, < 0', () => { expect(() => hslToRgb(-1, HSL_RED.saturation, HSL_RED.lightness)).toThrow(Error); }); test('hslToRgb - invalid hue, > 1', () => { expect(() => hslToRgb(361, HSL_RED.saturation, HSL_RED.lightness)).toThrow(Error); }); test('hslToRgb - invalid saturation, < 0', () => { expect(() => hslToRgb(HSL_RED.hue, -1, HSL_RED.lightness)).toThrow(Error); }); test('hslToRgb - invalid saturation, > 1', () => { expect(() => hslToRgb(HSL_RED.hue, 1.1, HSL_RED.lightness)).toThrow(Error); }); test('hslToRgb - invalid value, < 0', () => { expect(() => hslToRgb(HSL_RED.hue, HSL_RED.saturation, -1)).toThrow(Error); }); test('hslToRgb - invalid value, > 1', () => { expect(() => hslToRgb(HSL_RED.hue, HSL_RED.saturation, 1.1)).toThrow(Error); }); // Color ranges test('hslToRgb - red', () => { const teal = hslToRgb(HSL_RED.hue, HSL_RED.saturation, HSL_RED.lightness); expect(teal).toStrictEqual(RGB_RED); }); test('hslToRgb - yellow', () => { const teal = hslToRgb(HSL_YELLOW.hue, HSL_YELLOW.saturation, HSL_YELLOW.lightness); expect(teal).toStrictEqual(RGB_YELLOW); }); test('hslToRgb - green', () => { const teal = hslToRgb(HSL_GREEN.hue, HSL_GREEN.saturation, HSL_GREEN.lightness); expect(teal).toStrictEqual(RGB_GREEN); }); test('hslToRgb - cyan', () => { const teal = hslToRgb(HSL_CYAN.hue, HSL_CYAN.saturation, HSL_CYAN.lightness); expect(teal).toStrictEqual(RGB_CYAN); }); test('hslToRgb - blue', () => { const teal = hslToRgb(HSL_BLUE.hue, HSL_BLUE.saturation, HSL_BLUE.lightness); expect(teal).toStrictEqual(RGB_BLUE); }); test('hslToRgb - magenta', () => { const teal = hslToRgb(HSL_MAGENTA.hue, HSL_MAGENTA.saturation, HSL_MAGENTA.lightness); expect(teal).toStrictEqual(RGB_MAGENTA); }); });
super-effective/colorutil
src/tests/rgbToHsl.test.ts
<filename>src/tests/rgbToHsl.test.ts<gh_stars>1-10 import rgbToHsl from '../rgbToHsl'; import { HSL_BLACK, HSL_BLUE, HSL_DARK_TEAL, HSL_GREEN, HSL_RED, HSL_TEAL, RGB_BLACK, RGB_BLUE, RGB_DARK_TEAL, RGB_GREEN, RGB_RED, RGB_TEAL, } from './data/colors'; /** * RGB to HSV */ describe('rgbToHsl', () => { test('rgbToHsl - multi value', () => { const teal = rgbToHsl(RGB_TEAL.red, RGB_TEAL.green, RGB_TEAL.blue); expect(teal).toStrictEqual(HSL_TEAL); }); test('rgbToHsl - dark multi value', () => { const teal = rgbToHsl(RGB_DARK_TEAL.red, RGB_DARK_TEAL.green, RGB_DARK_TEAL.blue); expect(teal).toStrictEqual(HSL_DARK_TEAL); }); test('rgbToHsl - red', () => { const red = rgbToHsl(RGB_RED.red, RGB_RED.green, RGB_RED.blue); expect(red).toStrictEqual(HSL_RED); }); test('rgbToHsl - green', () => { const green = rgbToHsl(RGB_GREEN.red, RGB_GREEN.green, RGB_GREEN.blue); expect(green).toStrictEqual(HSL_GREEN); }); test('rgbToHsl - blue', () => { const blue = rgbToHsl(RGB_BLUE.red, RGB_BLUE.green, RGB_BLUE.blue); expect(blue).toStrictEqual(HSL_BLUE); }); test('rgbToHsl - black', () => { const black = rgbToHsl(RGB_BLACK.red, RGB_BLACK.green, RGB_BLACK.blue); expect(black).toStrictEqual(HSL_BLACK); }); });
super-effective/colorutil
src/tests/colorutils.test.ts
<reponame>super-effective/colorutil<gh_stars>1-10 import { HEX_BLACK, HEX_BLUE, HEX_GREEN, HEX_RED, HEX_TEAL, HEX_WHITE, HSV_BLACK, HSV_BLUE, HSV_GREEN, HSV_RED, HSV_TEAL, HSV_WHITE, } from './data/colors'; import { hexToHsv, hsvToHex, } from '../colorutils'; describe('Consistency checks', () => { test('hex > hsv > hex - teal', () => { const startHex = HEX_TEAL; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hex > hsv > hex - red', () => { const startHex = HEX_RED; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hex > hsv > hex - green', () => { const startHex = HEX_GREEN; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hex > hsv > hex - blue', () => { const startHex = HEX_BLUE; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hex > hsv > hex - black', () => { const startHex = HEX_BLACK; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hex > hsv > hex - white', () => { const startHex = HEX_WHITE; const hsv = hexToHsv(startHex); const hex = hsvToHex(hsv.hue, hsv.saturation, hsv.value); expect(hex).toStrictEqual(startHex); }); test('hsv > hex > hsv - teal', () => { const startHsv = HSV_TEAL; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); test('hsv > hex > hsv - red', () => { const startHsv = HSV_RED; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); test('hsv > hex > hsv - green', () => { const startHsv = HSV_GREEN; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); test('hsv > hex > hsv - blue', () => { const startHsv = HSV_BLUE; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); test('hsv > hex > hsv - black', () => { const startHsv = HSV_BLACK; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); test('hsv > hex > hsv - white', () => { const startHsv = HSV_WHITE; const hex = hsvToHex(startHsv.hue, startHsv.saturation, startHsv.value); const hsv = hexToHsv(hex); expect(hsv).toStrictEqual(startHsv); }); });
super-effective/colorutil
src/colorTypes.ts
/** * @typedef {Object} Rgb * @property {number} red - The red component of the color (0 - 255) * @property {number} green - The green component of the color (0 - 255) * @property {number} blue - The blue component of the color (0 - 255) */ export type Rgb = { red: number; green: number; blue: number; } /** * @typedef {Object} Hsl * @property {number} hue - The hue of the color (0 - 360) * @property {number} saturation - The saturation the color (0.0 - 1.0) * @property {number} lightness - The lightness of the color (0.0 - 1.0) */ export type Hsl = { hue: number; saturation: number; lightness: number; } /** * @typedef {Object} Hsv * @property {number} hue - The hue of the color (0 - 360) * @property {number} saturation - The saturation the color (0.0 - 1.0) * @property {number} value - The value of the color (0.0 - 1.0) */ export type Hsv = { hue: number; saturation: number; value: number; } export type Cmyk = { cyan: number; magenta: number; yellow: number; black: number; }
super-effective/colorutil
src/rgbToHex.ts
/** * Takes given red, green, and blue values and returns the hex color representation * @param {number} red The red component of the color (0 - 255) * @param {number} green The green component of the color (0 - 255) * @param {number} blue The blue component of the color (0 - 255) * @returns {string} The hex string representation of the color */ export default function rgbToHex(red: number, green: number, blue: number): string { const rgb = blue | (green << 8) | (red << 16); return `#${(0x1000000 + rgb).toString(16).slice(1)}`; }
super-effective/colorutil
src/tests/hexToRgb.test.ts
<reponame>super-effective/colorutil<filename>src/tests/hexToRgb.test.ts import hexToRgb from '../hexToRgb'; import { HEX_TEAL, RGB_TEAL, RGB_WHITE, HEX_WHITE, RGB_BLACK, HEX_BLACK, } from './data/colors'; /** * HEX to RGB */ describe('hexToRgb', () => { test('hexToRgb - color', () => { const teal = hexToRgb(HEX_TEAL); expect(teal).toStrictEqual(RGB_TEAL); }); test('hexToRgb - white short', () => { const white = hexToRgb('#fff'); expect(white).toStrictEqual(RGB_WHITE); }); test('hexToRgb - white long', () => { const white = hexToRgb(HEX_WHITE); expect(white).toStrictEqual(RGB_WHITE); }); test('hexToRgb - black short', () => { const white = hexToRgb('#000'); expect(white).toStrictEqual(RGB_BLACK); }); test('hexToRgb - black long', () => { const white = hexToRgb(HEX_BLACK); expect(white).toStrictEqual(RGB_BLACK); }); test('hexToRgb - empty throws an error', () => { expect(() => hexToRgb('')).toThrow(Error); }); test('hexToRgb - short length throws an error', () => { expect(() => hexToRgb('#00')).toThrow(Error); }); test('hexToRgb - long length throws an error', () => { expect(() => hexToRgb('#0000000')).toThrow(Error); }); test('hexToRgb - invalid hex', () => { expect(() => hexToRgb('#j@0000')).toThrow(Error); }); });
super-effective/colorutil
src/tests/hsvToRgb.test.ts
import hsvToRgb from '../hsvToRgb'; import { HSV_TEAL, RGB_TEAL, HSV_WHITE, RGB_WHITE, HSV_BLACK, RGB_BLACK, HSV_RED, RGB_RED, HSV_YELLOW, RGB_YELLOW, HSV_GREEN, RGB_GREEN, HSV_CYAN, RGB_CYAN, HSV_BLUE, RGB_BLUE, HSV_MAGENTA, RGB_MAGENTA, } from './data/colors'; /** * HSV to RGB */ describe('hsvToRgb', () => { test('hsvToRgb - color', () => { const teal = hsvToRgb(HSV_TEAL.hue, HSV_TEAL.saturation, HSV_TEAL.value); expect(teal).toStrictEqual(RGB_TEAL); }); test('hsvToRgb - white', () => { const white = hsvToRgb(HSV_WHITE.hue, HSV_WHITE.saturation, HSV_WHITE.value); expect(white).toStrictEqual(RGB_WHITE); }); test('hsvToRgb - black', () => { const black = hsvToRgb(HSV_BLACK.hue, HSV_BLACK.saturation, HSV_BLACK.value); expect(black).toStrictEqual(RGB_BLACK); }); // Bounds checks test('hsvToRgb - invalid hue, < 0', () => { expect(() => hsvToRgb(-1, HSV_RED.saturation, HSV_RED.value)).toThrow(Error); }); test('hsvToRgb - invalid hue, > 1', () => { expect(() => hsvToRgb(361, HSV_RED.saturation, HSV_RED.value)).toThrow(Error); }); test('hsvToRgb - invalid saturation, < 0', () => { expect(() => hsvToRgb(HSV_RED.hue, -1, HSV_RED.value)).toThrow(Error); }); test('hsvToRgb - invalid saturation, > 1', () => { expect(() => hsvToRgb(HSV_RED.hue, 1.1, HSV_RED.value)).toThrow(Error); }); test('hsvToRgb - invalid value, < 0', () => { expect(() => hsvToRgb(HSV_RED.hue, HSV_RED.saturation, -1)).toThrow(Error); }); test('hsvToRgb - invalid value, > 1', () => { expect(() => hsvToRgb(HSV_RED.hue, HSV_RED.saturation, 1.1)).toThrow(Error); }); // Color ranges test('hsvToRgb - red', () => { const teal = hsvToRgb(HSV_RED.hue, HSV_RED.saturation, HSV_RED.value); expect(teal).toStrictEqual(RGB_RED); }); test('hsvToRgb - yellow', () => { const teal = hsvToRgb(HSV_YELLOW.hue, HSV_YELLOW.saturation, HSV_YELLOW.value); expect(teal).toStrictEqual(RGB_YELLOW); }); test('hsvToRgb - green', () => { const teal = hsvToRgb(HSV_GREEN.hue, HSV_GREEN.saturation, HSV_GREEN.value); expect(teal).toStrictEqual(RGB_GREEN); }); test('hsvToRgb - cyan', () => { const teal = hsvToRgb(HSV_CYAN.hue, HSV_CYAN.saturation, HSV_CYAN.value); expect(teal).toStrictEqual(RGB_CYAN); }); test('hsvToRgb - blue', () => { const teal = hsvToRgb(HSV_BLUE.hue, HSV_BLUE.saturation, HSV_BLUE.value); expect(teal).toStrictEqual(RGB_BLUE); }); test('hsvToRgb - magenta', () => { const teal = hsvToRgb(HSV_MAGENTA.hue, HSV_MAGENTA.saturation, HSV_MAGENTA.value); expect(teal).toStrictEqual(RGB_MAGENTA); }); });
super-effective/colorutil
src/hsvToRgb.ts
<reponame>super-effective/colorutil import { Rgb } from 'colorTypes'; /** * Takes given hue, saturation and value and returns the respective RGB values * @param {number} hue The hue of the color (0.0 - 360.0) * @param {number} saturation The saturation of the color (0.0 - 1.0) * @param {number} value The value of the color (0.0 - 1.0) * @returns {Rgb} The RGB values for the color */ export default function hsvToRgb(hue: number, saturation: number, value: number): Rgb { // Bounds check if ((hue < 0 || hue > 360) || (saturation < 0 || saturation > 1) || (value < 0 || value > 1)) { throw new Error('Invalid hue, saturation, or value - all values must be between 0 and 1'); } let red = 0; let green = 0; let blue = 0; const huePercent = hue / 360; const i = Math.floor(huePercent * 6); const f = huePercent * 6 - i; const p = value * (1 - saturation); const q = value * (1 - f * saturation); const t = value * (1 - (1 - f) * saturation); switch (i % 6) { case 0: { red = value; green = t; blue = p; break; } case 1: { red = q; green = value; blue = p; break; } case 2: { red = p; green = value; blue = t; break; } case 3: { red = p; green = q; blue = value; break; } case 4: { red = t; green = p; blue = value; break; } case 5: { red = value; green = p; blue = q; break; } default: { // Shouldn't reach here - break break; } } red = Math.round(red * 255); green = Math.round(green * 255); blue = Math.round(blue * 255); return { red, green, blue, }; }
super-effective/colorutil
src/cmykToHex.ts
<reponame>super-effective/colorutil<filename>src/cmykToHex.ts import cmykToRgb from './cmykToRgb'; import rgbToHex from './rgbToHex'; /** * Takes given cyan, magenta, yellow, and black values and returns the hex representation * @param {number} cyan The cyan component of the color (percentage represented as 0 - 1) * @param {number} magenta The magenta component of the color (percentage represented as 0 - 1) * @param {number} yellow The yellow component of the color (percentage represented as 0 - 1) * @param {number} black The black component of the color (percentage represented as 0 - 1) * @returns {string} The hex representation of the color */ export default function cmykToHex(cyan: number, magenta: number, yellow: number, black: number): string { const { red, green, blue, } = cmykToRgb(cyan, magenta, yellow, black); return rgbToHex(red, green, blue) }
super-effective/colorutil
src/hslToRgb.ts
<reponame>super-effective/colorutil import { Rgb } from 'colorTypes'; function hueToRgb(p: number, q: number, t: number) { let clampedT = t; if (t < 0) { clampedT += 360; } if (clampedT > 360) { clampedT -= 360; } if(clampedT < 60) { return p + (q - p) * 6 * (clampedT / 360); } if(clampedT < 180) { return q; } if(clampedT < 240) { return p + (q - p) * ((240 - clampedT) / 360) * 6; } return p; } /** * Takes given hue, saturation and lightness and returns the respective RGB values * @param {number} hue The hue of the color (0.0 - 360.0) * @param {number} saturation The saturation of the color (0.0 - 1.0) * @param {number} lightness The value of the color (0.0 - 1.0) * @returns {Rgb} The RGB values for the color */ export default function hslToRgb(hue: number, saturation: number, lightness: number): Rgb { // Bounds check if ((hue < 0 || hue > 360) || (saturation < 0 || saturation > 1) || (lightness < 0 || lightness > 1)) { throw new Error('Invalid hue, saturation, or value - all values must be between 0 and 1'); } // Achromatic if (saturation === 0) { const rgb = Math.round(lightness * 255); return { red: rgb, green: rgb, blue: rgb, }; } const q = (lightness < 0.5) ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; const p = 2 * lightness - q; const red = hueToRgb(p, q, hue + 120); const green = hueToRgb(p, q, hue); const blue = hueToRgb(p, q, hue - 120); return { red: Math.round(red * 255), green: Math.round(green * 255), blue: Math.round(blue * 255), }; }
super-effective/colorutil
src/cmykToRgb.ts
import { Rgb } from './colorTypes'; /** * Takes given cyan, magenta, yellow, and black values and returns the RGB representation * @param {number} cyan The cyan component of the color (percentage represented as 0 - 1) * @param {number} magenta The magenta component of the color (percentage represented as 0 - 1) * @param {number} yellow The yellow component of the color (percentage represented as 0 - 1) * @param {number} black The black component of the color (percentage represented as 0 - 1) * @returns {Rgb} The Rgb representation of the color */ export default function cmykToRgb(cyan: number, magenta: number, yellow: number, black: number): Rgb { const blackModifier = 1 - (black); const red = Math.round(255 * (1 - cyan) * blackModifier); const green = Math.round(255 * (1 - magenta) * blackModifier); const blue = Math.round(255 * (1 - yellow) * blackModifier); return { red, green, blue, } }
super-effective/colorutil
src/hexToHsl.ts
import { Hsl } from './colorTypes'; import hexToRgb from './hexToRgb'; import rgbToHsl from './rgbToHsl'; /** * Converts a hex color string to its hue, saturation, and lightness * @param {string} colorHex The color value in hex format * @returns {Hsl} The HSL values for the color */ export default function hexToHsl(colorHex: string): Hsl { // Hex validation handled by hexToRgb const { red, green, blue, } = hexToRgb(colorHex); return rgbToHsl(red, green, blue); }
super-effective/colorutil
src/tests/hexToCmyk.test.ts
<gh_stars>1-10 import hexToCmyk from '../hexToCmyk'; import { CMYK_BLACK, CMYK_BLUE, CMYK_GREEN, CMYK_RED, CMYK_TEAL, HEX_BLACK, HEX_BLUE, HEX_GREEN, HEX_RED, HEX_TEAL, } from './data/colors'; /** * RGB to CMYK */ describe('hexToCmyk', () => { test('hexToCmyk - multi value', () => { const teal = hexToCmyk(HEX_TEAL); expect(teal).toStrictEqual(CMYK_TEAL); }); test('hexToCmyk - red', () => { const red = hexToCmyk(HEX_RED); expect(red).toStrictEqual(CMYK_RED); }); test('hexToCmyk - green', () => { const green = hexToCmyk(HEX_GREEN); expect(green).toStrictEqual(CMYK_GREEN); }); test('hexToCmyk - blue', () => { const blue = hexToCmyk(HEX_BLUE); expect(blue).toStrictEqual(CMYK_BLUE); }); test('hexToCmyk - black', () => { const black = hexToCmyk(HEX_BLACK); expect(black).toStrictEqual(CMYK_BLACK); }); });
super-effective/colorutil
src/tests/hsvToHex.test.ts
import hsvToHex from '../hsvToHex'; import { HSV_TEAL, HEX_TEAL, HSV_WHITE, HEX_WHITE, HSV_BLACK, HEX_BLACK, HSV_RED, } from './data/colors'; /** * HSV to HEX */ describe('hsvToHex', () => { test('hsvToHex - color', () => { const teal = hsvToHex(HSV_TEAL.hue, HSV_TEAL.saturation, HSV_TEAL.value); expect(teal).toBe(HEX_TEAL); }); test('hsvToHex - white', () => { const white = hsvToHex(HSV_WHITE.hue, HSV_WHITE.saturation, HSV_WHITE.value); expect(white).toBe(HEX_WHITE); }); test('hsvToHex - black', () => { const black = hsvToHex(HSV_BLACK.hue, HSV_BLACK.saturation, HSV_BLACK.value); expect(black).toBe(HEX_BLACK); }); // Bounds checks test('hsvToHex - invalid hue, < 0', () => { expect(() => hsvToHex(-1, HSV_RED.saturation, HSV_RED.value)).toThrow(Error); }); test('hsvToHex - invalid hue, > 1', () => { expect(() => hsvToHex(361, HSV_RED.saturation, HSV_RED.value)).toThrow(Error); }); test('hsvToHex - invalid saturation, < 0', () => { expect(() => hsvToHex(HSV_RED.hue, -1, HSV_RED.value)).toThrow(Error); }); test('hsvToHex - invalid saturation, > 1', () => { expect(() => hsvToHex(HSV_RED.hue, 1.1, HSV_RED.value)).toThrow(Error); }); test('hsvToHex - invalid value, < 0', () => { expect(() => hsvToHex(HSV_RED.hue, HSV_RED.saturation, -1)).toThrow(Error); }); test('hsvToHex - invalid value, > 1', () => { expect(() => hsvToHex(HSV_RED.hue, HSV_RED.saturation, 1.1)).toThrow(Error); }); });
super-effective/colorutil
src/hsvToHex.ts
import hsvToRgb from './hsvToRgb'; import rgbToHex from './rgbToHex'; /** * Takes given hue, saturation and value and returns the hex color representation * @param {number} hue The hue of the color (0.0 - 360.0) * @param {number} saturation The saturation of the color (0.0 - 1.0) * @param {number} value The value of the color (0.0 - 1.0) * @returns {string} The hex string representation of the color */ export default function hsvToHex(hue: number, saturation: number, value: number): string { // Bounds check handled by hsvToRgb const { red, green, blue, } = hsvToRgb(hue, saturation, value); return rgbToHex(red, green, blue); }
super-effective/colorutil
src/tests/rgbToHsv.test.ts
<filename>src/tests/rgbToHsv.test.ts import rgbToHsv from '../rgbToHsv'; import { RGB_BLACK, RGB_BLUE, RGB_GREEN, RGB_RED, RGB_TEAL, HSV_BLUE, HSV_GREEN, HSV_RED, HSV_TEAL, HSV_BLACK, } from './data/colors'; /** * RGB to HSV */ describe('rgbToHsv', () => { test('rgbToHsv - multi value', () => { const teal = rgbToHsv(RGB_TEAL.red, RGB_TEAL.green, RGB_TEAL.blue); expect(teal).toStrictEqual(HSV_TEAL); }); test('rgbToHsv - red', () => { const red = rgbToHsv(RGB_RED.red, RGB_RED.green, RGB_RED.blue); expect(red).toStrictEqual(HSV_RED); }); test('rgbToHsv - green', () => { const green = rgbToHsv(RGB_GREEN.red, RGB_GREEN.green, RGB_GREEN.blue); expect(green).toStrictEqual(HSV_GREEN); }); test('rgbToHsv - blue', () => { const blue = rgbToHsv(RGB_BLUE.red, RGB_BLUE.green, RGB_BLUE.blue); expect(blue).toStrictEqual(HSV_BLUE); }); test('rgbToHsv - black', () => { const black = rgbToHsv(RGB_BLACK.red, RGB_BLACK.green, RGB_BLACK.blue); expect(black).toStrictEqual(HSV_BLACK); }); });
super-effective/colorutil
src/tests/cmykToHex.test.ts
<filename>src/tests/cmykToHex.test.ts<gh_stars>1-10 import cmykToHex from '../cmykToHex'; import { CMYK_BLACK, CMYK_BLUE, CMYK_GREEN, CMYK_RED, CMYK_TEAL, HEX_BLACK, HEX_BLUE, HEX_GREEN, HEX_RED, HEX_TEAL, } from './data/colors'; /** * CMYK to HEX */ describe('cmykToHex', () => { test('cmykToHex - multi value', () => { const teal = cmykToHex(CMYK_TEAL.cyan, CMYK_TEAL.magenta, CMYK_TEAL.yellow, CMYK_TEAL.black); expect(teal).toStrictEqual(HEX_TEAL); }); test('cmykToHex - red', () => { const red = cmykToHex(CMYK_RED.cyan, CMYK_RED.magenta, CMYK_RED.yellow, CMYK_RED.black); expect(red).toStrictEqual(HEX_RED); }); test('cmykToHex - green', () => { const green = cmykToHex(CMYK_GREEN.cyan, CMYK_GREEN.magenta, CMYK_GREEN.yellow, CMYK_GREEN.black); expect(green).toStrictEqual(HEX_GREEN); }); test('cmykToHex - blue', () => { const blue = cmykToHex(CMYK_BLUE.cyan, CMYK_BLUE.magenta, CMYK_BLUE.yellow, CMYK_BLUE.black); expect(blue).toStrictEqual(HEX_BLUE); }); test('cmykToHex - black', () => { const black = cmykToHex(CMYK_BLACK.cyan, CMYK_BLACK.magenta, CMYK_BLACK.yellow, CMYK_BLACK.black); expect(black).toStrictEqual(HEX_BLACK); }); });
super-effective/colorutil
src/hslToHex.ts
<reponame>super-effective/colorutil import hslToRgb from './hslToRgb'; import rgbToHex from './rgbToHex'; /** * Takes given hue, saturation and lightness and returns the hex color representation * @param {number} hue The hue of the color (0.0 - 360.0) * @param {number} saturation The saturation of the color (0.0 - 1.0) * @param {number} lightness The lightness of the color (0.0 - 1.0) * @returns {string} The hex string representation of the color */ export default function hslToHex(hue: number, saturation: number, lightness: number): string { // Bounds check handled by hslToRgb const { red, green, blue, } = hslToRgb(hue, saturation, lightness); return rgbToHex(red, green, blue); }
super-effective/colorutil
src/hexToCmyk.ts
import { Cmyk } from './colorTypes'; import hexToRgb from './hexToRgb'; import rgbToCmyk from './rgbToCmyk'; /** * Converts a hex color string to its CMYK representation * @param {string} colorHex The color value in hex format * @returns {Cmyk} The CMYK values for the color */ export default function hexToCmyk(colorHex: string): Cmyk { // Hex validation handled by hexToRgb const { red, green, blue, } = hexToRgb(colorHex); return rgbToCmyk(red, green, blue); }
super-effective/colorutil
src/getPerceivedLuminance.ts
<reponame>super-effective/colorutil /** * Get the perceived brightness of a given color * See: https://www.w3.org/TR/AERT/#color-contrast * @param {number} red The red component of the color (0 - 255) * @param {number} green The green component of the color (0 - 255) * @param {number} blue The blue component of the color (0 - 255) * @returns {number} The perceived brightness of the color (0.0 - 1.0) */ export default function getPerceivedLuminance(red: number, green: number, blue: number): number { return ((red * 0.299) + (green * 0.587) + (blue * 0.114)) / 255; }
super-effective/colorutil
src/rgbToHsl.ts
<reponame>super-effective/colorutil<filename>src/rgbToHsl.ts import { Hsl } from './colorTypes'; /** * Takes given red, green, and blue values and returns the HSL representation * @param {number} red The red component of the color (0 - 255) * @param {number} green The green component of the color (0 - 255) * @param {number} blue The blue component of the color (0 - 255) * @returns {Hsl} The HSL representation of the color */ export default function rgbToHsl(red: number, green: number, blue: number): Hsl { const redPercent = red / 255; const greenPercent = green / 255; const bluePercent = blue / 255; const max = Math.max(redPercent, greenPercent, bluePercent); const min = Math.min(redPercent, greenPercent, bluePercent); const lightness = (max + min) / 2; let hue = 0; let saturation = 0; if (red === green && red === blue) { // Achromatic - no color } else { const diff = max - min; saturation = lightness > 0.5 ? (diff / (2 - max - min)) : diff / (max + min); switch (max) { case redPercent: { hue = (greenPercent - bluePercent) / diff + (greenPercent < bluePercent ? 6 : 0); break; } case greenPercent: { hue = (bluePercent - redPercent) / diff + 2; break; } case bluePercent: { hue = (redPercent - greenPercent) / diff + 4; break; } default: { // Shouldn't reach here - break break; } } hue /= 6; hue *= 360; } return { hue, saturation, lightness, }; }
super-effective/colorutil
src/rgbToHsv.ts
<filename>src/rgbToHsv.ts import { Hsv } from './colorTypes'; /** * Takes given red, green, and blue values and returns the HSV representation * @param {number} red The red component of the color (0 - 255) * @param {number} green The green component of the color (0 - 255) * @param {number} blue The blue component of the color (0 - 255) * @returns {Hsv} The HSV representation of the color */ export default function rgbToHsv(red: number, green: number, blue: number): Hsv { const redPercent = red / 255; const greenPercent = green / 255; const bluePercent = blue / 255; const max = Math.max(redPercent, greenPercent, bluePercent); const min = Math.min(redPercent, greenPercent, bluePercent); const diff = max - min; let hue = 0; const saturation = (max === 0) ? 0 : diff / max; const value = max; if (min === max) { // Achromatic - no color } else { switch (max) { case redPercent: { hue = (greenPercent - bluePercent) / diff + (greenPercent < bluePercent ? 6 : 0); break; } case greenPercent: { hue = (bluePercent - redPercent) / diff + 2; break; } case bluePercent: { hue = (redPercent - greenPercent) / diff + 4; break; } default: { // Shouldn't reach here - break break; } } hue /= 6; hue *= 360; } return { hue, saturation, value, }; }
super-effective/colorutil
src/rgbToCmyk.ts
import { Cmyk } from './colorTypes'; /** * Takes given red, green, and blue values and returns the CMYK representation * @param {number} red The red component of the color (0 - 255) * @param {number} green The green component of the color (0 - 255) * @param {number} blue The blue component of the color (0 - 255) * @returns {Cmyk} The CMYK representation of the color */ export default function rgbToCmyk(red: number, green: number, blue: number): Cmyk { const redPercent = red / 255; const greenPercent = green / 255; const bluePercent = blue / 255; const black = Math.min(1 - redPercent, 1 - greenPercent, 1 - bluePercent); const cyan = (1 - redPercent - black) / (1 - black) || 0; const magenta = (1 - greenPercent - black) / (1 - black) || 0; const yellow = (1 - bluePercent - black) / (1 - black) || 0; return { cyan, magenta, yellow, black, } }
super-effective/colorutil
src/sanitizeHex.ts
/** * Removes invalid characters and formats color hex to 6 characters * @param {string} colorHex The color value in hex format to sanitize * @returns {string} The sanitized hex color */ export default function sanitizeHex(colorHex: string): string { let sanitizedHex = colorHex.replace(/[^a-fA-F0-9]/g, ''); if (sanitizedHex.length === 0) { sanitizedHex = '000000'; } else if (sanitizedHex.length === 1) { sanitizedHex = sanitizedHex[0].repeat(6); } else if (sanitizedHex.length === 2) { sanitizedHex = `${sanitizedHex[0].repeat(3)}${sanitizedHex[1].repeat(3)}`; } else if (sanitizedHex.length >= 3 && sanitizedHex.length < 6) { sanitizedHex = `${sanitizedHex[0].repeat(2)}${sanitizedHex[1].repeat(2)}${sanitizedHex[2].repeat(2)}`; } else if (sanitizedHex.length > 6) { sanitizedHex = sanitizedHex.substr(0, 6); } return `#${sanitizedHex}`; }