Giter Club home page Giter Club logo

vscode-glean's Introduction

VSCode Glean

The extension provides refactoring tools for your React codebase

Build Status

The extension provides refactoring tools for your React codebase: extract JSX into a new component, convert Class Components to Functional Components, wrapping with Hooks and more!

Highlights

  • Allows extracting JSX into new component
  • Allows converting Class Components to Functional Components and vice-verse
  • Allows wrapping JSX with conditional
  • Allows renaming state variables and their setters simultaneously.
  • Allows wrapping code with useMemo, useCallback or useEffect
  • Moving code between files
  • Typescript support
  • ES2015 modules support
  • CommonJS modules support

Installation

Go to the link below and click Install.

Visual Studio Code Market Place: Glean

Features

Extracting JSX into a new Component

Glean allows easy extraction of JSX into new React components (in the same or other file). Just select the JSX to extract, and Glean will handle all the rest:

  • Generate Class or Functional Component, such that the extracted JSX will continue to function.
  • It will identify all inputs to the newly created component.
  • Replace extracted JSX with newly created component, while providing it with all the props.

Example of JSX extraction

Converting Class Component to Functional Component

Glean seamlesly automates convertion of class components to functional component, while take care of all the complexity:

  • Converts setState calls to useState
  • Converts componentDidMount and componentWillUnmount to useEffect
  • Converts class properties to useRef
  • Wraps call non-Lifecycle methods with useCallback

WARNING!!! If You are using React version older than 16.8.0, This refactoring will delete all Lifecycle methods and setState calls!

Example of Hooks Support

Converting Functional Component to Class Component

Example of Stateless to Stateful Component Conversion

Rename State Variable

Rename any state variable and let Glean rename its setter accordingly for You!

Example of Rename State

Wrap with Hook (useMemo, useCallback or useEffect)

Example of Rename State

Render Conditionally

Example of Render Conditionally

Extract to file

Select text and either VSCode's code suggestion (aka "Lightbulb") or Command Pallet ('Extract to File' command) to extract the text.

Example of Javascript Extraction

Configuration Options

glean.jsModuleSystem (Default: 'esm')

Determines how the selected code will be exported/imported. Valid options are 'esm' and 'commonjs'.

glean.jsFilesExtensions (Default: [ "js", "jsx", "ts", "tsx" ])

List of extensions of files that should be treated as javascript files. This determines whether or not the snippet will be exported and imported. The snippet will be treated as javascript only if the extension of both origin and target files appears in this list.

glean.switchToTarget (Default: false)

Determines whether VSCode should switch to target file after extracting.

glean.experiments (Default: [])

A list of enabled experimental features. Available experimental features:

glean.showConversionWarning (Default: true)

Determines whether VSCode should show conversion warning when converting Class Component to Functional Component.

Contribute

Feel free to open issues or PRs!

Getting started

In order to start working all you need to do is:

$ git clone [email protected]:wix/vscode-glean.git
$ cd vscode-glean
$ npm install
$ code .

Running Extension

  • Go to VSCode debug sidebar
  • Select Extension from the dropdown
  • Hit F5

Running Tests

  • Go to VSCode debug sidebar
  • Select Extension Tests from the dropdown
  • Hit F5

Commit messages

Please refer to to the following guide.

vscode-glean's People

Contributors

2012mjm avatar aeciorc avatar borislit avatar freddydumont avatar iychiang avatar jefoss avatar m-izadmehr avatar mattfwood avatar moshfeu avatar nickakey avatar ob1 avatar rbadapanda avatar ryuoryuo avatar semantic-release-bot avatar timcluyts avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vscode-glean's Issues

Cannot read property 'includes' of undefined

I have been unable to use the "Extract Component" functionality, because each time I tried it I got this error. Even after disabling all other extensions, I still see this error. Any ideas why this might be?

following excpetion is seen in developer tools when I navigate into a .js file in my nodejs project

ERR Cannot read property 'superClass' of undefined: TypeError: Cannot read property 'superClass' of undefined
at isSupportedComponent (/Users/badapr/.vscode/extensions/wix.glean-4.10.1/out/modules/stateful-to-stateless.js:303:28)
at Object.isStatefulComp (/Users/badapr/.vscode/extensions/wix.glean-4.10.1/out/modules/stateful-to-stateless.js:310:9)
at CompleteActionProvider.provideCodeActions (/Users/badapr/.vscode/extensions/wix.glean-4.10.1/out/extension.js:39:37)
at define.provideCodeActions.a.asPromise (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:587:847)
at t.asPromise.Promise (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:49:430)
at new Promise ()
at Object.t.asPromise (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:49:402)
at D.provideCodeActions (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:587:818)
at define.$provideCodeActions._withAdapter.e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:604:253)
at B._withAdapter (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:599:159)
at B.$provideCodeActions (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:604:231)
at d._doInvokeHandler (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:622:11)
at d._invokeHandler (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:621:716)
at d._receiveRequest (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:620:341)
at d._receiveOneMessage (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:619:141)
at define.constructor._protocol.onMessage.e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:617:400)
at u.fire (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:44:708)
at e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:40:460)
at u.fire (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:44:708)
at a (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:172:467)
at e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:172:513)
at u.fire (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:44:708)
at y._receiveMessage (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:181:276)
at define.constructor._socketDisposables.push._socketReader.onMessage.e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:178:415)
at u.fire (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:44:708)
at f.acceptChunk (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:175:35)
at define.constructor._register._socket.onData.e (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:174:410)
at Socket.t (/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/out/vs/workbench/services/extensions/node/extensionHostProcess.js:182:689)
at Socket.emit (events.js:182:13)
at Socket.EventEmitter.emit (domain.js:442:20)
at addChunk (_stream_readable.js:279:12)
at readableAddChunk (_stream_readable.js:264:11)
at Socket.Readable.push (_stream_readable.js:219:10)
at Pipe.onread (net.js:636:20)

TypeError: Cannot read property 'superClass' of undefined

https://github.com/wix/vscode-glean/blob/7d6791f9595bb9be4e5619f566c7c67276599d87/src/modules/jsx.ts#L166

I think that line needs another guard because I am seeing:

ERR Cannot read property 'superClass' of undefined: TypeError: Cannot read property 'superClass' of undefined
    at isSupportedComponent (/home/capaj/.vscode/extensions/wix.glean-4.2.3/out/modules/jsx.js:152:28)
    at Object.isStatefulComp (/home/capaj/.vscode/extensions/wix.glean-4.2.3/out/modules/jsx.js:158:9)
    at CompleteActionProvider.provideCodeActions (/home/capaj/.vscode/extensions/wix.glean-4.2.3/out/extension.js:33:19)
    at /usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:509:787
    at /usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:114:65
    at new Promise (<anonymous>)
    at Object.t.asThenable (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:114:33)
    at e.provideCodeActions (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:509:746)
    at /usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:524:308
    at e._withAdapter (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:520:234)
    at e.$provideCodeActions (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:524:270)
    at t._doInvokeHandler (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:609:757)
    at t._invokeHandler (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:609:423)
    at t._receiveRequest (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:607:973)
    at t._receiveOneMessage (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:606:957)
    at /usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:604:773
    at /usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:103:886
    at e.fire (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:105:344)
    at a (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:156:881)
    at Socket._socketDataListener (/usr/share/code/resources/app/out/vs/workbench/node/extensionHostProcess.js:157:95)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at Pipe.onread (net.js:594:20)

The code I am looking at is just a simple stateless component.

Version 4.2.3

Extension doesnt work on Windows 10

Does the extension not work on windows? I'm not sure why else it wouldn't recognise the syscall?

[2018-11-03 19:51:26.898] [renderer1] [error] [{"errno":-4094,"code":"UNKNOWN","syscall":"stat","path":"\\\\d:\\multivariate-hypergeo\\src\\PopulationInput.js"}]
[2018-11-03 19:51:26.913] [renderer1] [error] [{"fileOperationResult":1,"options":{"acceptTextOnly":true}}]
[2018-11-03 19:51:26.930] [renderer1] [error] [{"fileOperationResult":1,"options":{"acceptTextOnly":true}}]

Extact component to existing file with custom name

We want to allow extraction of jsx to a new component into an existing file, while being able to choose its name.
Keep in mind - this should also affect the the source file (the import name and the replacement with the component)

Quoted string literals as object keys break 'Extract Component to File'

Great plugin! Found an issue- when trying to use the 'Extract component to file' function, if the selected component has a property using an object property accessed via a quoted string literal, it fails with
Property name expected type of string but got null

Eg.
This works:

import { Card } from 'antd';
import React from 'react';

export default () => {
  const foo = {
    bar: 'foo',
  };
  return (
    <Card title={foo.bar}>
      <h1>foo</h1>
    </Card>
  );
};

But this fails:

import { Card } from 'antd';
import React from 'react';

export default () => {
  const foo = {
    bar: 'foo',
  };
  return (
    <Card title={foo['bar']}>
      <h1>foo</h1>
    </Card>
  );
};

Extract to component is broken

Hi Team

Extracting a piece of jsx takes forever to ask for the path then some more secs to ask for the file name and does it, does not do anything else, does not create the file

Using Hooks to replace setState calls

Today, when class components is refactored to the functional component, all setState calls are lost, as there was no equivalent concept. Today, after Hooks have been introduced, they seem to be just that.
It would be awesome to explore such a possibility.
This should be an opt-in feature (using configuration)

Extract to component bug in generated code

Given input

    <FlatList
        data={collapsedData}
        keyExtractor={item => `${item._eprId}_${item._eprValue}`}
        renderItem={this.makeRenderItem(data)}
        ListHeaderComponent={this.renderHeader}
        ListEmptyComponent={this.renderEmpty}
        onRefresh={this.props.onRefresh}
        refreshing={this.props.refreshing}
      />

Extracted generated (Table named) component

export function Table({
  collapsedData,
  item,
  data,
  _eprId,
  _eprValue,
  makeRenderItem,
  renderHeader,
  renderEmpty,
  onRefresh,
  refreshing
}) {
  return (
    <FlatList
      data={collapsedData}
      keyExtractor={item => `${_eprId}_${_eprValue}`}
      renderItem={makeRenderItem(data)}
      ListHeaderComponent={renderHeader}
      ListEmptyComponent={renderEmpty}
      onRefresh={onRefresh}
      refreshing={refreshing}
    />
  );
}

As you can see keyExtractor is generated incorrectly

Can't extract component in .tsx file

OS:

Windows 10 Pro 1809

glean:

4.2.3

VS Code:

1.30.1 (user setup)

Scaffolded via:

create-react-app with the new typescript option.

Code (inside class extends React.Component<any, IState>):

<button
  className={"search-button"}
  type="submit"
  disabled={submitting}
/>

Popup error:

Maximum call stack size exceeded

Console error:

ERR Cannot read property 'superClass' of undefined: TypeError: Cannot read property 'superClass' of undefined
    at isSupportedComponent (C:\Users\oO\.vscode\extensions\wix.glean-4.2.3\out\modules\jsx.js:152:28)
    at Object.isStatefulComp (C:\Users\oO\.vscode\extensions\wix.glean-4.2.3\out\modules\jsx.js:158:9)
    at CompleteActionProvider.provideCodeActions (C:\Users\oO\.vscode\extensions\wix.glean-4.2.3\out\extension.js:33:19)
    at c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:556:20
    at t.asThenable (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:141:941)
    at new Promise (<anonymous>)
    at Object.t.asThenable (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:141:909)
    at e.provideCodeActions (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:555:1003)
    at c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:572:308
    at e._withAdapter (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:567:513)
    at e.$provideCodeActions (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:572:270)
    at t._doInvokeHandler (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:658:837)
    at t._invokeHandler (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:658:509)
    at t._receiveRequest (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:657:60)
    at t._receiveOneMessage (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:656:59)
    at c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:653:895
    at c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:130:793
    at e.fire (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:133:218)
    at a (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:186:147)
    at Socket.n._socketDataListener (c:\Users\oO\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:186:368)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at Pipe.onread (net.js:594:20)

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No vsce personal access token specified. (set env "VSCE_TOKEN")

Unfortunatly this error doesn't have any additionnal information. Feel free to kindly ask the author of the semantic-release-vsce plugin to add more helpful informations.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Wrap new component code with fragment only if needed

Thank you for this extension, for a long time I wanted one like this (I started creating one, but didn't have the time to make it more production ready).
Now for the bug/feature-request:

Not always I will need a fragment (<>) wrapping my new component. It should wrap only when there's more than one element in the root

CPU usage spikes to 100%

Since I added the extension to VS Code it often increases it's CPU usage to 100%. I disabled it and it looks fine. Anyone experienced this before?

Error for simple component conversion

Property value expected type of string but got null

TS 3.1.6
VS Code 1.30.2
Extension version 4.2.3

import React, { Component } from 'react';

class App extends Component<{}> {
  render() {
    return (
      <div />
    );
  }
}

image

"Convert to Stateful Component" Error

When I try to do "Convert Stateless to Stateful Component" on this code:

const DepositRow = ({
  depositPercentage,
  gridInputStyle,
  gridItemStyle,
  handleUpdate,
  total
}) => {
  const depositAmount = (total * (depositPercentage / 100)).toFixed(2);
  return (
    <Fragment>
      <div className={gridItemStyle}>Deposit %:</div>
      <input
        type="text"
        name="depositPercentage"
        value={depositPercentage}
        onChange={e => handleUpdate(e)}
        className={gridInputStyle}
      />
      <div className={gridItemStyle}>Deposit:</div>
      <div className={gridItemStyle}>${depositAmount}</div>
      <div />
    </Fragment>
  );
};

I get this error:

Using 4.0.4

"You can only replace a Program root node with another Program node" error when trying to convert a convert a stateless component into a stateful one

import styled from 'styled-components';
import { Card, Button, Skeleton, Spin, Icon } from 'antd';

const { Meta } = Card;

const StyledCard = styled(Card)`
  border-radius: 7px;
  display: flex;
  flex-direction: column;
  text-align: center;
  margin: 8px 4px 0 4px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.12);
  flex-basis: 16rem;
  padding-bottom: 0;

  .ant-card-body {
    padding-top: 0;
    height: 100%;
  }

  & img {
    border-radius: 7px 7px 0 0;
    object-fit: cover;
    width: 100%;
    height: 16rem;
  }

  @media (max-width: 768px) {
    border-bottom: 1px solid;
    border-bottom-color: rgb(210, 210, 210);
    box-shadow: none;
    margin: 8px 0 0 0;
    flex-basis: 100%;
  }

  .ant-card-actions {
    background-color: #fff;
    border-top-color: rgb(210, 210, 210);
    border-radius: 0 0 7px 7px;
  }
`;

const StyledMeta = styled(Meta)`
  display: flex;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  height: 100%;
  & * {
    white-space: initial;
    overflow-wrap: normal;
  }
`;

interface Props {
  name: string;
  image: string;
  description: string;
  price: string;
}

const ViewMoreButton: any = styled(Button)`
  border: none;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.12);
`;

const addDots = (str: string, limit: number) => {
  if (str.length > limit) {
    return [str.substring(0, limit) + '...', true];
  }

  return [str, false];
};

export default (props: Props) => {
  const [shortName, readMoreName] = addDots(props.name, 50);
  const [shortDesc, readMoreDesc] = addDots(props.description, 150);

  return (
    <StyledCard
      bordered={false}
      cover={
        <div>
          {true ? (
            <div
              style={{
                height: '16rem',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Spin
                indicator={
                  <Icon
                    type="loading"
                    theme="outlined"
                    style={{ fontSize: '2.5rem', color: 'rgb(202, 202, 202)' }}
                    spin
                  />
                }
              />
            </div>
          ) : (
            <>
              <img alt="example" src={props.image} />
              <Button
                style={{
                  width: 44,
                  height: 44,
                  position: 'relative',
                  bottom: 22,
                  border: 'none',
                  boxShadow: '0 2px 2px rgba(0, 0, 0, 0.12)'
                }}
                icon="plus"
                shape="circle"
              />
            </>
          )}
        </div>
      }
      actions={
        /**
         * There is no need to render any buttons if the text can fit normally
         */
        (readMoreDesc || readMoreName) && !true
          ? [
              <ViewMoreButton size="small" icon="info">
                View more
              </ViewMoreButton>
            ]
          : []
      }
    >
      <Skeleton active loading={true} title={false}>
        <StyledMeta title={shortName} description={<p>{shortDesc}</p>} />
      </Skeleton>
    </StyledCard>
  );
};

Here's my code, whenever I try to select the component and try to convert it to a stateful one, I get the following message

You can only replace a Program root node with another Program node in an error, coming from VSCode:

image

Move type definitions for props and state to new file

I tried the "move to a new file" command on a component and while it moved the component, it didn't move the type definition for the component's props. Instead it imports the type definition. Unfortunately, the original file wasn't exporting the type definition so the new file needs a little cleanup. I think it'd be better to just move the prop type definition since it's no longer being used in the original file.

Error converting function to class

When I try to convert this function to a class:

const MyComponent: SFC<Props> = props =>
  true && <div />

I get error:

Property body of ClassMethod expected node to be of a type ["BlockStatement"] but instead got null

TSX Support?

I don't know if this is currently supported but I have tried exporting to a component from a tsx file and it was just blank. Any ideas? And great work its got lots of potential!!! 👍

Config option for "export default"

Many style guides (like Airbnb's) require single export files to use export default.

It would be nice if there was a configuration option to default extracted files to export default, and to set the relevant import without destructuring�.

Atom extension plans?

You have ever considered or had in mind Glean for atom? That would be great because I have what I love in Atom already and not looking to move to vscode(tried it though).

@labria ("cc-ing" just one of the team members to not spam all of them)

Suggestion: annotate function components with `SFC` type

Thanks for this amazing project!

When converting from class to function components, could we annotate (in TypeScript files) the function component using the SFC type?

For example:

const MyComponent: SFC<Props> = props => <div />;

Annotating the type allows the props to be defined outside of the function definition, similar to how classes work. It's also an extra precaution to ensure the function returns the correct types.

Flow type annotations interfere with Extract Component in normal JS files.

We are not using Typescript but are using Flow instead. It appears that Glean tries process Flow type annotations that are also valid Typescript. In these cases it displays an error like the following:

unknown node of type "TSTypeCastExpression" with constructor "Node"

For instance, trying to run glean on the following throws code from our web app causes Extract Component to fail:

<React.Fragment key={subcat}>
	<StyledNavLinkSubLevel1 className={classNames({'active': subcatActive})} 
		href="#" 
		onClick={() => this.handleSubCatClick(((subcat: any): UbBlogCitySubCategory))}
	>
		{subCategoriesObj[subcat]}
	</StyledNavLinkSubLevel1>
	<StyledNav tag="nav">
		{links}
	</StyledNav>
</React.Fragment>

However, when the Flow type annotation (inside the onClick binding, if you missed it 😄 ) is taken
out, it works as expected. So this code extracts with Glean correctly:

<React.Fragment key={subcat}>
	<StyledNavLinkSubLevel1 className={classNames({'active': subcatActive})} 
		href="#" 
		onClick={() => this.handleSubCatClick(subcat)}
	>
		{subCategoriesObj[subcat]}
	</StyledNavLinkSubLevel1>
	<StyledNav tag="nav">
		{links}
	</StyledNav>
</React.Fragment>

I'm pretty sure this isn't the expected behavior.

-- Zack Frost

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.