components#Code TypeScript Examples

The following examples show how to use components#Code. 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: index.test.tsx    From geist-ui with MIT License 6 votes vote down vote up
describe('Code', () => {
  it('should render correctly', () => {
    const wrapper = mount(<Code>code</Code>)
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('should support block mode', () => {
    const wrapper = render(<Code block>code</Code>)
    expect(wrapper).toMatchSnapshot()
  })

  it('should repspond to changed by width', () => {
    const wrapper = render(
      <Code block width="50%">
        code
      </Code>,
    )
    expect(wrapper).toMatchSnapshot()
  })

  it('should render pre element only in block mode', () => {
    const wrapper = mount(<Code>code</Code>)
    expect(wrapper.find('pre').length).toBe(0)
    wrapper.setProps({ block: true })
    expect(wrapper.find('pre').length).not.toBe(0)
  })

  it('should work correctly with title', () => {
    const wrapper = render(
      <Code block name="name" classic>
        code
      </Code>,
    )
    expect(wrapper).toMatchSnapshot()
  })
})
Example #2
Source File: attributes-title.tsx    From geist-ui with MIT License 6 votes vote down vote up
getAlias = (isChinese: boolean, alias?: string) => {
  if (!alias) return null
  return (
    <small>
      <span>[</span>
      {isChinese ? '别名' : 'alias'}: <Code>{alias}</Code>
      <span>]</span>
    </small>
  )
}
Example #3
Source File: hybrid-code.tsx    From geist-ui with MIT License 6 votes vote down vote up
HybridCode: React.FC<HybridCodeProps> = ({ children }) => {
  const { children: withoutNameChildren, name } = useMemo<HybridCodeChildrenAndName>(
    () => extractFileName(children),
    [children],
  )
  const withoutPrefixName = useMemo(() => {
    if (!name) return name
    return name.replace(FILE_NAME_PREFIX, '')
  }, [name])

  return (
    <Code block name={withoutPrefixName}>
      {withoutNameChildren}
    </Code>
  )
}
Example #4
Source File: attributes-title.tsx    From geist-ui with MIT License 5 votes vote down vote up
AttributesTitle: React.FC<React.PropsWithChildren<AttributesTitleProps>> =
  React.memo(({ children, alias }) => {
    const theme = useTheme()
    const { isChinese } = useConfigs()

    return (
      <>
        <h4 className="title">
          <Code>
            <VirtualAnchor pure>{children}</VirtualAnchor>
          </Code>
          {getAlias(!!isChinese, alias)}
        </h4>

        <style jsx>{`
          h4 {
            display: inline-flex;
            align-items: center;
            height: 2rem;
            padding-left: ${theme.layout.gapQuarter};
            padding-right: ${theme.layout.gapHalf};
            background-color: ${theme.palette.accents_1};
            border-radius: ${theme.layout.radius};
            margin-bottom: 0;
          }

          h4 :global(small) {
            font-size: 0.65em;
            padding-left: 0.65rem;
            color: ${theme.palette.accents_4};
            align-self: flex-end;
            line-height: 1.6rem;
          }

          h4 :global(span) {
            color: ${theme.palette.accents_6};
          }
        `}</style>
      </>
    )
  })
Example #5
Source File: index.tsx    From geist-ui with MIT License 5 votes vote down vote up
Colors: React.FC<Props> = ({ type }) => {
  const theme = useTheme()
  const { copy } = useClipboard()
  const { setToast } = useToasts()
  const copyText = (text: string) => {
    copy(text)
    setToast({
      text: (
        <span>
          Copied <Code>{text}</Code>
        </span>
      ),
    })
  }
  const colorItems = useMemo(
    () => getColorItem(type, theme.palette, copyText),
    [type, theme.palette],
  )

  return (
    <div className="colors">
      {colorItems}
      <style jsx>{`
        .colors {
          display: flex;
          flex-direction: column;
          width: 100%;
        }
        .colors :global(.color) {
          padding: ${theme.layout.gap};
          position: relative;
          user-select: none;
        }
        .colors :global(.color:first-child) {
          border-top-left-radius: ${theme.layout.radius};
          border-top-right-radius: ${theme.layout.radius};
        }
        .colors :global(.color:last-child) {
          border-bottom-left-radius: ${theme.layout.radius};
          border-bottom-right-radius: ${theme.layout.radius};
        }
        .colors :global(.color h4) {
          margin: 0;
        }
        .colors :global(.usage) {
          font-size: 1rem;
          padding: 1rem;
          cursor: pointer;
        }
        .colors :global(.value) {
          font-size: 0.875rem;
          text-transform: uppercase;
          padding: 1rem;
          cursor: pointer;
        }
      `}</style>
    </div>
  )
}
Example #6
Source File: index.test.tsx    From geist-ui with MIT License 4 votes vote down vote up
describe('Table', () => {
  it('should render correctly', () => {
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('should work correctly with multiple identical props', () => {
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="property" label="property2" />
        <Table.Column prop="property" label="property3" />
        <Table.Column prop="description" label="description2" />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('should re-render when data changed', async () => {
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" />
      </Table>,
    )
    expect(wrapper.find('tbody').find('tr').length).toBe(data.length)
    wrapper.setProps({ data: [] })
    await updateWrapper(wrapper, 350)
    expect(wrapper.find('tbody').find('tr').length).toBe(0)
  })

  it('should set width automatically', () => {
    window.getComputedStyle = jest.fn().mockImplementation(() => ({
      width: '100px',
    }))
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" width={50} />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(() => wrapper.unmount()).not.toThrow()
    ;(window.getComputedStyle as jest.Mock).mockClear()
  })

  it('should be no erros when width is too large', () => {
    window.getComputedStyle = jest.fn().mockImplementation(() => ({
      width: '10px',
    }))
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" width={50} />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(() => wrapper.unmount()).not.toThrow()
    ;(window.getComputedStyle as jest.Mock).mockClear()
  })

  it('should work with other components', () => {
    const dataWithNodes = [
      ...data,
      { property: 'bold', description: <Code>boolean</Code>, default: 'true' },
    ]
    const wrapper = mount(
      <Table data={dataWithNodes}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(wrapper.find('code').length).not.toBe(0)
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('should work without hover effect', () => {
    const wrapper = mount(
      <Table data={data} hover={false}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="default" label="default" />
      </Table>,
    )
    expect(wrapper.html()).toMatchSnapshot()
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('should be render specified elements', async () => {
    type Item = {
      property: string
      description: string
      operation: string
    }
    const renderAction: TableColumnRender<Item> = (value, rowData, index) => {
      return (
        <div>
          <button id="test-btn">Remove</button>
          <div id="value">{value}</div>
          <div id="row-data">{rowData.description}</div>
          <div id="row-index">{index}</div>
        </div>
      )
    }
    const operation = Math.random().toString(16).slice(-10)
    const data = [{ property: 'bold', description: 'boolean', operation }]
    const wrapper = mount(
      <Table<Item> data={data}>
        <Table.Column<Item> prop="property" label="property" />
        <Table.Column<Item> prop="description" label="description" />
        <Table.Column<Item> prop="operation" label="operation" render={renderAction} />
      </Table>,
    )
    const buttons = wrapper.find('tbody').find('#test-btn')
    expect(buttons.length).not.toEqual(0)
    const value = wrapper.find('tbody').find('#value').html()
    expect(value).toMatch(operation)
    const rowData = wrapper.find('tbody').find('#row-data').html()
    expect(rowData).toMatch(`${data[0].description}`)
    const rowIndex = wrapper.find('tbody').find('#row-index').html()
    expect(rowIndex).toMatch(`0`)
  })

  it('should render emptyText when data missing', () => {
    const data = [{ property: 'bold', description: 'boolean' }]
    const wrapper = mount(
      <Table data={data} emptyText="test-not-found">
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
        <Table.Column prop="operation" label="operation" />
      </Table>,
    )
    expect(wrapper.find('tbody').text()).toContain('test-not-found')
  })

  it('should trigger events when cell clicked', () => {
    const rowHandler = jest.fn()
    const cellHandler = jest.fn()
    const data = [{ property: 'bold', description: 'boolean' }]
    const wrapper = mount(
      <Table
        data={data}
        emptyText="test-not-found"
        onRow={rowHandler}
        onCell={cellHandler}>
        <Table.Column prop="property" label="property" />
        <Table.Column prop="description" label="description" />
      </Table>,
    )
    wrapper.find('tbody').find('tr').find('td').at(0).simulate('click', nativeEvent)
    expect(rowHandler).toHaveBeenCalled()
    expect(cellHandler).toHaveBeenCalled()
  })

  it('should wraning when prop missing', () => {
    const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
    mount(
      <Table data={data}>
        <Table.Column prop="" label="property" />
        <Table.Column prop="description" label="description" />
      </Table>,
    )
    expect(errorSpy).toHaveBeenCalled()
    errorSpy.mockRestore()
  })

  it('should render children for table head', () => {
    const wrapper = mount(
      <Table data={data}>
        <Table.Column prop="property">
          <Code>property</Code>
        </Table.Column>
      </Table>,
    )
    expect(wrapper.find('thead').find('code').length).not.toBe(0)
    expect(wrapper.html()).toMatchSnapshot()
  })

  it('the changes of column should be tracked', () => {
    const Mock = ({ label }: { label: string }) => {
      return (
        <Table data={data}>
          <Table.Column prop="description" label={label} />
        </Table>
      )
    }
    const wrapper = mount(<Mock label="test1" />)
    expect(wrapper.find('thead').find('tr').at(0).text()).toBe('test1')

    act(() => {
      wrapper.setProps({ label: 'test2' })
    })
    expect(wrapper.find('thead').find('tr').at(0).text()).toBe('test2')
    expect(() => wrapper.unmount()).not.toThrow()
  })

  it('the changes of children should be tracked', () => {
    const Mock = ({ label }: { label: string }) => {
      return (
        <Table data={data}>
          <Table.Column prop="description">{label}</Table.Column>
        </Table>
      )
    }
    const wrapper = mount(<Mock label="test1" />)
    expect(wrapper.find('thead').find('tr').at(0).text()).toBe('test1')

    act(() => {
      wrapper.setProps({ label: 'test2' })
    })
    expect(wrapper.find('thead').find('tr').at(0).text()).toBe('test2')
    expect(() => wrapper.unmount()).not.toThrow()
  })
})
Example #7
Source File: codes.tsx    From geist-ui with MIT License 4 votes vote down vote up
CustomizationCodes: React.FC<unknown> = () => {
  const DefaultTheme = Themes.getPresetStaticTheme()
  const theme = useTheme()
  const { isChinese } = useConfigs()
  const codeTheme = makeCodeTheme(theme)
  const { copy } = useClipboard()
  const { setToast } = useToasts()

  const deepDifferents = useMemo(
    () => ({
      ...getDeepDifferents(DefaultTheme, theme),
      type: CUSTOM_THEME_TYPE,
    }),
    [DefaultTheme, theme],
  )
  const userCodes = useMemo(() => {
    return `const myTheme = ${JSON.stringify(deepDifferents, null, 2)}

/***
 *  Usage::
 *
 *  export const App = () => {
 *    return (
 *      <GeistProvider themes={[myTheme]} themeType="${CUSTOM_THEME_TYPE}">
 *        <CssBaseline />
 *        <YourComponent />
 *      </GeistProvider>
 *    )
 *  }
 **/`
  }, [deepDifferents])

  const copyCode = () => {
    copy(userCodes)
    setToast({ text: 'Theme code copied.' })
  }

  return (
    <div className="custom-codes">
      <h3 className="title">{isChinese ? '主题代码' : 'Theme Codes'}</h3>
      <Spacer h={1} />
      {isChinese ? (
        <Text>
          这里是你所有的变更,点击 <Code>copy</Code> 按钮即可使用在你自己的项目中。
        </Text>
      ) : (
        <Text>
          This is all your changes, click <Code>copy</Code> to use it in your own project.
        </Text>
      )}
      <Spacer h={2} />
      <div className="codes">
        <div className="copy" onClick={copyCode}>
          <CopyIcon />
        </div>
        <LiveProvider code={userCodes} disabled theme={codeTheme}>
          <LiveEditor />
        </LiveProvider>
      </div>
      <Spacer h={5} />
      <style jsx>{`
        .custom-codes {
          display: flex;
          flex-direction: column;
          flex: 1;
          margin: 3rem auto 2.5rem;
          text-align: center;
        }

        .title {
          text-align: center;
          width: 80%;
          margin: 0 auto;
          display: inline-block;
          background: ${theme.palette.foreground};
          color: ${theme.palette.background};
          font-size: 1rem;
          line-height: 1rem;
          padding: ${theme.layout.gap} 0;
          text-transform: uppercase;
          letter-spacing: 1.5px;
        }

        .codes {
          width: 80%;
          margin: 0 auto;
          border: 1px solid ${theme.palette.border};
          border-radius: ${theme.layout.radius};
          overflow: hidden;
          padding: calc(0.6 * ${theme.layout.gap}) ${theme.layout.gap};
          position: relative;
        }

        .copy {
          position: absolute;
          right: 1rem;
          top: 1rem;
          z-index: 2000;
          color: ${theme.palette.accents_3};
          cursor: pointer;
          user-select: none;
          transition: color 200ms ease;
          --snippet-font-size: 16px;
        }

        .copy:hover {
          color: ${theme.palette.accents_6};
        }

        @media only screen and (max-width: ${theme.layout.breakpointMobile}) {
          .title,
          .codes {
            width: 90vw;
          }
        }
      `}</style>
    </div>
  )
}
Example #8
Source File: demo.tsx    From geist-ui with MIT License 4 votes vote down vote up
Demo: React.FC<React.PropsWithChildren<unknown>> = () => {
  const theme = useTheme()
  const { isChinese } = useConfigs()

  return (
    <div className="demo">
      <div className="content">
        {isChinese ? (
          <>
            <Text h2 mb={0} font="13px" type="secondary">
              预览
            </Text>
            <Text>
              这里是你变更主题后的即时预览。此外,当你每次更新主题变量时,整个文档站点也会随之变化。
            </Text>
          </>
        ) : (
          <>
            <Text h2 mb={0} font="13px">
              PREVIEWS
            </Text>
            <Text>
              Here&#39;s a preview of your changes to the Theme. When you set the changes,
              the entire document site will change with the theme.
            </Text>
          </>
        )}

        <Spacer h={1.7} />
        <Text h3 font="13px" type="secondary">
          {isChinese ? '色彩' : 'COLORS'}
        </Text>
        <Colors />

        <Spacer h={1.7} />
        <Text h3 font="13px" type="secondary">
          {isChinese ? '排版' : 'Typography'}
        </Text>
        <Text>
          <Link rel="nofollow" href="https://en.wikipedia.org/wiki/HTTP/2" color>
            HTTP/2
          </Link>{' '}
          allows the server to <Code>push</Code> content, that is, to respond with data
          for more queries than the client requested. This allows the server to supply
          data it knows a web browser will need to render a web page, without waiting for
          the browser to examine the first response, and without the overhead of an
          additional request cycle.
        </Text>
        <Text h6>Heading</Text>
        <Text h5>Heading</Text>
        <Text h4>Heading</Text>
        <Text h3>Heading</Text>

        <Spacer h={1.7} />
        <Text h3 font="13px" type="secondary">
          {isChinese ? '基础组件' : 'Basic Components'}
        </Text>
        <Select width="90%" placeholder="Choose one" initialValue="1">
          <Select.Option value="1">Option 1</Select.Option>
          <Select.Option value="2">Option 2</Select.Option>
        </Select>
        <Spacer h={1} />
        <Grid.Container width="100%">
          <Grid xs={8}>
            <Button disabled auto>
              Action
            </Button>
          </Grid>
          <Grid xs={8}>
            <Button auto>Action</Button>
          </Grid>
          <Grid xs={8}>
            <Button auto type="secondary">
              Action
            </Button>
          </Grid>
        </Grid.Container>
      </div>
      <style jsx>{`
        .demo {
          width: 34%;
          margin-top: calc(${theme.layout.gap} * 2);
          margin-right: ${theme.layout.gap};
          padding-right: ${theme.layout.gapQuarter};
          position: relative;
          border-right: 1px solid ${theme.palette.border};
          height: auto;
          transition: width 200ms ease;
        }

        .content {
          width: 100%;
        }

        @media only screen and (max-width: ${theme.layout.breakpointMobile}) {
          .demo {
            display: none;
          }
        }
      `}</style>
    </div>
  )
}