preact#createContext TypeScript Examples

The following examples show how to use preact#createContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: container.tsx    From gridjs with MIT License 6 votes vote down vote up
constructor(props, context) {
    super(props, context);

    // global Config context which is passed to all components
    this.configContext = createContext(null);

    this.state = {
      status: Status.Loading,
      header: props.header,
      data: null,
    };
  }
Example #2
Source File: message-row.test.tsx    From gridjs with MIT License 6 votes vote down vote up
describe('MessageRow component', () => {
  let config: Config;
  const configContext = createContext(null);

  beforeEach(() => {
    config = new Config();
  });

  it('should match the snapshot', () => {
    const td = mount(
      <configContext.Provider value={config}>
        <MessageRow message="boo" />
      </configContext.Provider>,
    );
    expect(td.html()).toMatchSnapshot();
  });

  it('should prevent emit rowClick', async () => {
    config.eventEmitter = new EventEmitter<TableEvents>();
    const onClick = jest.fn();

    const rows = mount(
      <configContext.Provider value={config}>
        <MessageRow message="boo" />
      </configContext.Provider>,
    ).find('tr');

    config.eventEmitter.on('rowClick', onClick);
    rows.map((tr) => tr.simulate('click'));

    expect(rows.length).toEqual(1);
    expect(onClick).toHaveBeenCalledTimes(0);
  });
});
Example #3
Source File: Intermediate.tsx    From revite with GNU Affero General Public License v3.0 6 votes vote down vote up
IntermediateActionsContext = createContext<{
    openLink: (href?: string, trusted?: boolean) => boolean;
    openScreen: (screen: Screen) => void;
    writeClipboard: (text: string) => void;
}>({
    openLink: null!,
    openScreen: null!,
    writeClipboard: null!,
})
Example #4
Source File: td.test.tsx    From gridjs with MIT License 6 votes vote down vote up
describe('TD component', () => {
  let config: Config;
  const configContext = createContext(null);

  beforeEach(() => {
    config = new Config();
  });

  it('should match the snapshot', () => {
    const td = mount(
      <configContext.Provider value={config}>
        <TD cell={new Cell('boo')} />
      </configContext.Provider>,
    );
    expect(td.html()).toMatchSnapshot();
  });

  it('should emit cellClick', async () => {
    config.eventEmitter = new EventEmitter<TableEvents>();
    const onClick = jest.fn();

    const cells = mount(
      <configContext.Provider value={config}>
        <TD cell={new Cell('boo')} />
      </configContext.Provider>,
    ).find('td');

    config.eventEmitter.on('cellClick', onClick);
    cells.map((td) => td.simulate('click'));

    expect(cells.length).toEqual(1);
    expect(onClick).toHaveBeenCalledTimes(1);
  });
});
Example #5
Source File: index.tsx    From remind with MIT License 6 votes vote down vote up
export function createContainer<Value, State = void>(
  useHook: (initialState?: State) => Value,
): Container<Value, State> {
  const Context = createContext<Value | typeof EMPTY>(EMPTY)

  function Provider(props: ContainerProviderProps<State>) {
    const value = useHook(props.initialState)
    return <Context.Provider value={value}>{props.children}</Context.Provider>
  }

  function useContainer(): Value {
    const value = useContext(Context)
    if (value === EMPTY) {
      throw new Error('Component must be wrapped with <Container.Provider>')
    }

    return value
  }

  return { Provider, useContainer }
}
Example #6
Source File: AppContext.tsx    From help-widget with MIT License 5 votes vote down vote up
GlobalsContext = createContext<Globals>({ widgetOpen: false, setWidgetOpen: (o) => undefined })
Example #7
Source File: MessageArea.tsx    From revite with GNU Affero General Public License v3.0 5 votes vote down vote up
MessageAreaWidthContext = createContext(0)
Example #8
Source File: RevoltClient.tsx    From revite with GNU Affero General Public License v3.0 5 votes vote down vote up
LogOutContext = createContext(() => {})
Example #9
Source File: RevoltClient.tsx    From revite with GNU Affero General Public License v3.0 5 votes vote down vote up
StatusContext = createContext<ClientStatus>(null!)
Example #10
Source File: RevoltClient.tsx    From revite with GNU Affero General Public License v3.0 5 votes vote down vote up
AppContext = createContext<Client>(null!)
Example #11
Source File: Intermediate.tsx    From revite with GNU Affero General Public License v3.0 5 votes vote down vote up
IntermediateContext = createContext({
    screen: { id: "none" },
    focusTaken: false,
})
Example #12
Source File: theme.ts    From remind with MIT License 5 votes vote down vote up
ThemeContext = createContext(defaultTheme)
Example #13
Source File: locale.ts    From remind with MIT License 5 votes vote down vote up
LocaleContext = createContext(defaultLocale)
Example #14
Source File: localisation.context.tsx    From passwords-fountain with MIT License 5 votes vote down vote up
LocalisationContext = createContext<ContextValue>([
    i18n.language,
    (): void => {
        // placeholder setter fn
    },
])
Example #15
Source File: Router.tsx    From help-widget with MIT License 5 votes vote down vote up
RouterContext = createContext<{ route: string, setRoute: (route: string) => void }>(
    { route: DEFAULT_ROUTE, setRoute: (_: string) => undefined })
Example #16
Source File: CoreContext.ts    From adyen-web with MIT License 5 votes vote down vote up
CoreContext = createContext({ i18n: new Language(), loadingContext: '', commonProps: {} as CommonPropsTypes })
Example #17
Source File: AppContext.tsx    From help-widget with MIT License 5 votes vote down vote up
ServiceContext = createContext<WidgetApi | undefined>(undefined)
Example #18
Source File: AppContext.tsx    From help-widget with MIT License 5 votes vote down vote up
ConfigContext = createContext<AppConfigurations>({} as AppConfigurations)
Example #19
Source File: tr.test.tsx    From gridjs with MIT License 5 votes vote down vote up
describe('TR component', () => {
  let config: Config;
  const configContext = createContext(null);

  beforeEach(() => {
    config = new Config();
  });

  it('should match the snapshot', () => {
    const tr = mount(
      <configContext.Provider value={config}>
        <TR>
          <TD cell={new Cell('boo')} />
        </TR>
      </configContext.Provider>,
    );
    expect(tr.html()).toMatchSnapshot();
  });

  it('should emit rowClick', async () => {
    config.eventEmitter = new EventEmitter<TableEvents>();
    const onClick = jest.fn();

    const rows = mount(
      <configContext.Provider value={config}>
        <TR>
          <TD cell={new Cell('boo')} />
        </TR>
      </configContext.Provider>,
    ).find('tr');

    config.eventEmitter.on('rowClick', onClick);
    rows.map((tr) => tr.simulate('click'));

    expect(rows.length).toEqual(1);
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it('should attach the custom tr className', async () => {
    const tr = mount(
      <configContext.Provider
        value={{
          ...config,
          ...{
            className: {
              tr: 'custom-tr-classname',
            },
          },
        }}
      >
        <TR>
          <TD cell={new Cell('boo')} />
        </TR>
      </configContext.Provider>,
    );

    expect(tr.find('tr.custom-tr-classname')).toHaveLength(1);
  });
});
Example #20
Source File: markdown.tsx    From obsidian-dataview with MIT License 5 votes vote down vote up
DataviewContext = createContext<DataviewContexts>(undefined!)
Example #21
Source File: table.test.tsx    From gridjs with MIT License 4 votes vote down vote up
describe('Table component', () => {
  let config: Config;
  const configContext = createContext(null);

  beforeEach(() => {
    config = new Config();
    config.data = [
      [1, 2, 3],
      ['a', 'b', 'c'],
    ];

    config.autoWidth = true;
    config.storage = StorageUtils.createFromUserConfig(config);
    config.dispatcher = new Dispatcher();
    config.translator = new Translator();
    config.pipeline = new Pipeline([
      new StorageExtractor({ storage: config.storage }),
      new ArrayToTabularTransformer(),
    ]);
  });

  it('should render a table', async () => {
    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with loading', async () => {
    config.className = {
      loading: 'my-loading-class',
    };

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={new Tabular()}
          status={Status.Loading}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.find('.my-loading-class').hostNodes().name()).toBe('td');
    expect(table.find('.my-loading-class').hostNodes().text()).toBe(
      'Loading...',
    );
    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with header', async () => {
    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={Header.fromUserConfig({ columns: ['h1', 'h2', 'h3'] })}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with width', async () => {
    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          width="300px"
          height={config.height}
          header={Header.fromUserConfig({ columns: ['h1', 'h2', 'h3'] })}
          status={Status.Rendered}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with column width', async () => {
    const header = Header.fromUserConfig({ columns: ['h1', 'h2', 'h3'] });
    header.columns[0].width = '10%';
    header.columns[2].width = '300px';

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with column sort', async () => {
    const header = Header.fromUserConfig({ columns: ['h1', 'h2', 'h3'] });
    header.columns[0].sort = {
      enabled: true,
    };
    header.columns[2].sort = {
      enabled: true,
    };

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table without autoFix', async () => {
    const header = Header.fromUserConfig({
      columns: ['h1', 'h2', 'h3'],
      autoWidth: false,
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table without data', async () => {
    const header = Header.fromUserConfig({
      columns: ['h1', 'h2', 'h3'],
    });

    config.className = {
      notfound: 'my-notfound-class',
    };

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={Tabular.fromArray<TCell>([])}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render a table with null', async () => {
    const header = Header.fromUserConfig({
      columns: ['h1', 'h2', 'h3'],
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={null}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should attach styles', async () => {
    const header = Header.fromUserConfig({
      columns: ['h1', 'h2', 'h3'],
    });

    config.style = {
      th: {
        border: '1px solid black',
      },
      table: {
        padding: '2px',
        margin: '1px',
      },
    };

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={null}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render header with complex content', async () => {
    const header = Header.fromUserConfig({
      columns: [
        {
          id: 'h1',
          name: html('<h1>h1</h1>'),
        },
        'h2',
        {
          id: 'h3',
          name: html('<b>h3</b>'),
        },
      ],
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={null}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should render header with TColumn object', async () => {
    const header = Header.fromUserConfig({
      columns: [
        {
          name: html('<h1>h1</h1>'),
          id: 'boo',
        },
        'h2',
        {
          name: 'h3',
        },
      ],
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={null}
          header={header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should attach the fixedHeader classname', async () => {
    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3],
        ['a', 'b', 'c'],
      ],
      columns: ['c', 'd', 'e'],
      fixedHeader: true,
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    return new Promise<void>((resolve) => {
      setTimeout(() => {
        expect(table.html()).toMatchSnapshot();
        resolve();
      }, 0);
    });
  });

  it('should only attached fixedHeader to some columns', async () => {
    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3],
        ['a', 'b', 'c'],
      ],
      columns: [
        'c',
        'd',
        {
          name: 'e',
          fixedHeader: false,
        },
      ],
      fixedHeader: true,
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    return new Promise<void>((resolve) => {
      setTimeout(() => {
        expect(table.html()).toMatchSnapshot();
        resolve();
      }, 0);
    });
  });

  it('should set the correct top attribute for nested headers', async () => {
    // to mock the offsetTop
    Object.defineProperty(HTMLElement.prototype, 'offsetTop', {
      configurable: true,
      value: 50,
    });

    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3, 4, 5, 6],
        ['a', 'b', 'c', 'd', 'e', 'f'],
      ],
      columns: [
        {
          name: 'c',
          columns: ['c1', 'c2'],
        },
        'd',
        {
          name: 'e',
          columns: [
            {
              name: 'e1',
              columns: ['e11', 'e12'],
            },
            {
              name: 'e2',
              columns: ['e21'],
            },
          ],
        },
      ],
      fixedHeader: true,
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    return new Promise<void>((resolve) => {
      setTimeout(() => {
        expect(table.html()).toMatchSnapshot();
        resolve();
      }, 0);
    });
  });

  it('should set the correct sort attribute for nested headers', async () => {
    const data = [
      [1, 2, 3, 4, 5, 6],
      ['a', 'b', 'c', 'd', 'e', 'f'],
    ];

    const flattenData = data
      .reduce((prev, x) => [...prev, ...x], [])
      .map((x) => x.toString());

    const config = Config.fromUserConfig({
      data: data,
      columns: [
        {
          name: 'c',
          columns: ['c1', 'c2'],
        },
        'd',
        {
          name: 'e',
          columns: [
            {
              name: 'e1',
              columns: ['e11', 'e12'],
            },
            {
              name: 'e2',
              columns: ['e21'],
            },
          ],
        },
      ],
      sort: true,
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    return new Promise<void>((resolve) => {
      setTimeout(() => {
        expect(
          table
            .find('td')
            .map((x) => x.text())
            .every((x) => x),
        ).toBeTrue();

        expect(
          table
            .find('td')
            .map((x) => x.text())
            .every((x) => flattenData.indexOf(x.toString()) > -1),
        ).toBeTrue();

        expect(table.html()).toMatchSnapshot();

        resolve();
      }, 0);
    });
  });

  it('should render custom attributes for cells', async () => {
    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3],
        ['a', 'b', 'c'],
      ],
      columns: [
        {
          name: 'c',
          attributes: (_: TCell, __: Row, column: TColumn) =>
            column.name === 'c' ? { height: '30px' } : {},
        },
        {
          name: 'd',
          attributes: (cell: TCell) =>
            cell === 'b'
              ? {
                  'data-row-c': true,
                }
              : {},
        },
        {
          name: 'e',
          attributes: {
            rowSpan: 3,
            'data-boo': 'xx',
          },
        },
      ],
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should only render custom attributes for the cell header', async () => {
    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3],
        ['a', 'b', 'c'],
      ],
      columns: [
        {
          name: 'c',
          attributes: (cell, row, col) => {
            // both cell and row are empty when attributes function is called for a th
            if (!cell && !row) {
              return {
                'data-col-c': col.id,
              };
            }

            return {};
          },
        },
        {
          name: 'd',
        },
        {
          name: 'e',
        },
      ],
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
  });

  it('should hide the columns with hidden: true', async () => {
    const config = Config.fromUserConfig({
      data: [
        [1, 2, 3],
        ['a', 'b', 'c'],
      ],
      columns: [
        {
          name: 'c',
          hidden: true,
        },
        {
          name: 'd',
          hidden: true,
          sort: true,
        },
        {
          name: 'e',
        },
      ],
      search: true,
      dispatcher: new Dispatcher<any>(),
    });

    const table = mount(
      <configContext.Provider value={config}>
        <Table
          data={await config.pipeline.process()}
          header={config.header}
          status={Status.Rendered}
          width={config.width}
          height={config.height}
        />
      </configContext.Provider>,
    );

    expect(table.html()).toMatchSnapshot();
    expect(table.find('td').length).toBe(2);
    expect(table.find('th').text()).toBe('e');
    expect(table.find('th').length).toBe(1);
  });
});
Example #22
Source File: search.test.tsx    From gridjs with MIT License 4 votes vote down vote up
describe('Search plugin', () => {
  let config: Config;
  const configContext = createContext(null);
  const plugin: Plugin<any> = {
    id: 'mysearch',
    position: PluginPosition.Header,
    component: {},
  };

  beforeEach(() => {
    config = new Config();
    config.autoWidth = true;
    config.dispatcher = new Dispatcher();
    config.eventEmitter = new EventEmitter<GridEvents>();
    config.translator = new Translator();
    config.pipeline = PipelineUtils.createFromConfig(config);
    config.header = Header.fromUserConfig({
      columns: ['Name', 'Phone Number'],
    });
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should render the search box', async () => {
    const mock = jest.spyOn(SearchActions.prototype, 'search');

    const search = mount(
      <configContext.Provider value={config}>
        <Search plugin={plugin} enabled={true} keyword={'boo'} />
      </configContext.Provider>,
    );

    expect(mock).toBeCalledWith('boo');
    expect(search.html()).toMatchSnapshot();
  });

  it('should not call search if keyword is undefined', async () => {
    const mock = jest.spyOn(SearchActions.prototype, 'search');

    mount(
      <configContext.Provider value={config}>
        <Search plugin={plugin} enabled={true} />
      </configContext.Provider>,
    );

    expect(mock).not.toBeCalled();
  });

  it('should call search action after input change', async () => {
    const mock = jest.spyOn(SearchActions.prototype, 'search');

    const wrapper = mount(
      <configContext.Provider value={config}>
        <Search plugin={plugin} enabled={true} />
      </configContext.Provider>,
    );

    // https://github.com/preactjs/enzyme-adapter-preact-pure/issues/45
    const input = wrapper.find('input');
    input.getDOMNode<HTMLInputElement>().value = '123';

    input.simulate('input');

    expect(mock).toBeCalledWith('123');
  });

  it('should add config.className.search', async () => {
    const search = mount(
      <configContext.Provider
        value={{
          ...config,
          className: {
            search: 'test-search-class-name',
          },
        }}
      >
        <Search plugin={plugin} enabled={true} keyword={'boo'} />
      </configContext.Provider>,
    );

    expect(
      search.find('.test-search-class-name').hasClass('gridjs-search'),
    ).toBeTrue();
    expect(search.find('.test-search-class-name').name()).toBe('div');
  });
});
Example #23
Source File: pagination.test.tsx    From gridjs with MIT License 4 votes vote down vote up
describe('Pagination plugin', () => {
  let config: Config;
  const configContext = createContext(null);
  const plugin: Plugin<any> = {
    id: 'mypagination',
    position: PluginPosition.Footer,
    component: {},
  };

  beforeEach(() => {
    config = Config.fromUserConfig({
      header: Header.fromColumns(['a', 'b', 'c']),
      data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
      ],
    });
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should render the pagination with no records', async () => {
    config = Config.fromUserConfig({
      header: Header.fromColumns(['a', 'b', 'c']),
      data: [],
    });

    const pagination = mount(
      <configContext.Provider
        value={{
          ...config,
          data: [],
        }}
      >
        <Pagination plugin={plugin} enabled={true} />
      </configContext.Provider>,
    );

    await config.pipeline.process();
    expect(pagination.html()).toMatchSnapshot();
  });

  it('should render the pagination with one page', async () => {
    const pagination = mount(
      <configContext.Provider value={config}>
        <Pagination plugin={plugin} enabled={true} limit={3} />
      </configContext.Provider>,
    );

    await config.pipeline.process();
    expect(pagination.html()).toMatchSnapshot();
  });

  it('should render the pagination with three page', async () => {
    const pagination = mount(
      <configContext.Provider value={config}>
        <Pagination plugin={plugin} enabled={true} limit={1} />
      </configContext.Provider>,
    );

    await config.pipeline.process();
    pagination.update();

    expect(pagination.html()).toMatchSnapshot();
  });

  it('should add config.className.pagination', async () => {
    const pagination = mount(
      <configContext.Provider
        value={{
          ...config,
          className: {
            pagination: 'my-pagination-class',
            paginationButton: 'my-button',
            paginationButtonNext: 'my-next-button',
            paginationButtonPrev: 'my-prev-button',
            paginationSummary: 'my-page-summary',
            paginationButtonCurrent: 'my-current-button',
          },
        }}
      >
        <Pagination plugin={plugin} enabled={true} limit={1} />
      </configContext.Provider>,
    );

    await config.pipeline.process();
    pagination.update();

    expect(
      pagination.find('.my-pagination-class').hasClass('gridjs-pagination'),
    ).toBeTrue();
    expect(pagination.find('.my-pagination-class').name()).toBe('div');

    expect(pagination.find('.my-button')).toHaveLength(5);
    expect(pagination.find('.my-next-button')).toHaveLength(1);
    expect(pagination.find('.my-next-button').prop('disabled')).toBeFalse();
    expect(pagination.find('.my-prev-button').prop('disabled')).toBeTrue();
    expect(pagination.find('.my-prev-button')).toHaveLength(1);
    expect(pagination.find('.my-current-button')).toHaveLength(1);
    expect(pagination.find('.my-current-button').text()).toBe('1');

    expect(pagination.find('.my-page-summary')).toHaveLength(1);
    expect(pagination.find('.my-page-summary').text()).toBe(
      'Showing 1 to 1 of 3 results',
    );
  });
});
Example #24
Source File: plugin.test.tsx    From gridjs with MIT License 4 votes vote down vote up
describe('Plugin', () => {
  interface DummyPluginProps extends PluginBaseProps<DummyPlugin> {
    text?: string;
  }

  class DummyPlugin extends PluginBaseComponent<DummyPluginProps> {
    render() {
      return h('b', {}, this.props.text || 'hello!');
    }
  }

  it('should add and remove plugins', () => {
    const manager = new PluginManager();

    expect(manager.list()).toHaveLength(0);

    manager.add({
      id: 'dummy',
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy2',
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    expect(manager.list()).toHaveLength(2);
    manager.remove('dummy');
    expect(manager.list()).toHaveLength(1);
    manager.remove('dummy2');
    expect(manager.list()).toHaveLength(0);
    manager.remove('doesntexist');
    expect(manager.list()).toHaveLength(0);
  });

  it('should return unordered plugins', () => {
    const manager = new PluginManager();

    expect(manager.list()).toHaveLength(0);

    manager.add({
      id: 'dummy',
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy2',
      order: 1,
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy3',
      order: 10,
      position: PluginPosition.Footer,
      component: DummyPlugin.prototype,
    });

    expect(manager.list().map((x) => x.id)).toStrictEqual([
      'dummy',
      'dummy2',
      'dummy3',
    ]);
  });

  it('should return plugins in the correct order', () => {
    const manager = new PluginManager();

    expect(manager.list()).toHaveLength(0);

    manager.add({
      id: 'dummy',
      order: 5,
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy2',
      order: 1,
      position: PluginPosition.Header,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy3',
      order: 10,
      position: PluginPosition.Footer,
      component: DummyPlugin.prototype,
    });

    manager.add({
      id: 'dummy4',
      position: PluginPosition.Footer,
      component: DummyPlugin.prototype,
    });

    expect(manager.list().map((x) => x.id)).toStrictEqual([
      'dummy2',
      'dummy',
      'dummy3',
      'dummy4',
    ]);
    expect(manager.list(PluginPosition.Header).map((x) => x.id)).toStrictEqual([
      'dummy2',
      'dummy',
    ]);
  });

  it('should return existing plugin by id', () => {
    const manager = new PluginManager();

    const component = DummyPlugin.prototype;
    manager.add({
      id: 'dummy',
      position: PluginPosition.Header,
      component: component,
    });

    const plugin = manager.get('dummy');

    expect(plugin.component).toBe(component);
    expect(plugin.position).toBe(PluginPosition.Header);

    expect(manager.get('doesnexist')).toBeNull();
  });

  it('should render the plugins', async () => {
    const configContext = createContext(null);
    const config = Config.fromUserConfig({
      data: [[1, 2, 3]],
    });

    config.plugin.add({
      id: 'dummyheader',
      position: PluginPosition.Header,
      component: DummyPlugin,
      props: { text: 'dummyheader' },
    });

    config.plugin.add({
      id: 'dummyfooter',
      position: PluginPosition.Footer,
      component: DummyPlugin,
      props: { text: 'dummyfooter' },
    });

    const renderer = mount(
      <configContext.Provider value={config}>
        <PluginRenderer position={PluginPosition.Header} />
        <PluginRenderer position={PluginPosition.Footer} />
      </configContext.Provider>,
    );

    expect(renderer.html()).toMatchSnapshot();
  });

  it('should create a userConfig with custom plugin', () => {
    const config = Config.fromUserConfig({
      data: [[1, 2, 3]],
      plugins: [
        {
          id: 'dummyheader',
          position: PluginPosition.Header,
          component: DummyPlugin,
          props: { text: 'dummyheader' },
        },
      ],
    });

    expect(config.plugin.get('dummyheader')).toMatchObject({
      id: 'dummyheader',
      position: PluginPosition.Header,
    });
  });
});