Skip to content
This repository has been archived by the owner on Sep 15, 2022. It is now read-only.

Commit

Permalink
Add linting & more code refactoring
Browse files Browse the repository at this point in the history
- Remove getNetwork method as it was redundant
- Add tslint rules for import destructure whitespacing
- Remove name as it was redundant (was the same as trait_type)
- Add error state for asset not found
- Update name of compiled js
- Split out template render code for readability
- Remove forbidden non null assertions
  • Loading branch information
taylorjdawson committed Feb 26, 2020
1 parent 32c4b05 commit 6353395
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 86 deletions.
28 changes: 14 additions & 14 deletions example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<script src="/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
<script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<script defer src="/dist/opensea-nft-card.min.js"></script>
<script defer src="/dist/nft-card.min.js"></script>

<title>OpenSea Embeddable NFT example</title>
<style media="screen">
Expand Down Expand Up @@ -49,22 +49,22 @@ <h3>Show users any crypto collectible and let them buy it straight from your sit
<!-- >-->
<!-- </nft-card>-->

<nft-card
contractAddress="0x2fb5d7dda4f1f20f974a0fdd547c38674e8d940c"
tokenId="20014"
>
</nft-card>
<!-- <nft-card-->
<!-- contractAddress="0x2fb5d7dda4f1f20f974a0fdd547c38674e8d940c"-->
<!-- tokenId="20014"-->
<!-- >-->
<!-- </nft-card>-->

<div style="padding-top: 5vh;"></div>

<!-- <nft-card-->
<!-- contractAddress="0x5caebd3b32e210e85ce3e9d51638b9c445481567"-->
<!-- height="250px"-->
<!-- horizontal-->
<!-- network="mainnet"-->
<!-- tokenId="2242579050293992223"-->
<!-- width="100%"-->
<!-- >-->
<nft-card
contractAddress="0x5caebd3b32e210e85ce3e9d51638b9c445481567"
height="250px"
horizontal
network="main"
tokenId="2242579050293992223"
width="100%"
>
</nft-card>
<div style="padding-top: 5vh;"></div>
</div>
Expand Down
3 changes: 1 addition & 2 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {css, customElement, html, LitElement} from 'lit-element'

import { css, customElement, html, LitElement } from 'lit-element'

@customElement('loader-element')
export class Loader extends LitElement {
Expand Down
25 changes: 13 additions & 12 deletions src/nft-card-back.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { LitElement, html, customElement, property, css } from 'lit-element'
import { styleMap } from 'lit-html/directives/style-map'
import { classMap } from 'lit-html/directives/class-map'
import {OpenSeaTraitStats} from 'opensea-js/lib/types'
import { OpenSeaTraitStats } from 'opensea-js/lib/types'

enum TraitType {
Property = 'prop',
Expand All @@ -19,7 +19,6 @@ interface Traits {
}

interface Trait {
name: string
value: string | number
max?: string | number
display_type: string
Expand Down Expand Up @@ -235,9 +234,12 @@ export class NftCardBackTemplate extends LitElement {
await this.requestUpdate()
}
})
const el: HTMLElement = this.shadowRoot!.firstElementChild as HTMLElement
this.cardHeight = el.offsetHeight
this.cardWidth = el.offsetWidth

if (this.shadowRoot) {
const el: HTMLElement = this.shadowRoot.firstElementChild as HTMLElement
this.cardHeight = el.offsetHeight
this.cardWidth = el.offsetWidth
}
}

public getBoostsTemplate(boosts: any[]) {
Expand Down Expand Up @@ -302,7 +304,7 @@ export class NftCardBackTemplate extends LitElement {
<div class="stat">
<div class="stat-value">${stat.value}</div>
<div class="stat-name">
${NftCardBackTemplate.formatTrait(stat.name)}
${NftCardBackTemplate.formatTrait(stat.trait_type)}
</div>
</div>
`
Expand Down Expand Up @@ -333,18 +335,18 @@ export class NftCardBackTemplate extends LitElement {
<p class="attribute-title">Rankings</p>
</div>
${rankings.slice(0, numRanksRender).map(
({name, value, max}) => html`
({trait_type, value, max}) => html`
<div class="trait_ranking" style="${styleMap(rankStyle)}">
<div class="trait_ranking-header">
<div class="trait_ranking-header-name">
${NftCardBackTemplate.formatTrait(name)}
${NftCardBackTemplate.formatTrait(trait_type)}
</div>
<div class="trait_ranking-header-value">${value} of ${max}</div>
</div>
<div class="trait_ranking-bar">
<div
class="trait_ranking-bar-fill"
style=${styleMap({width: `${(+value / +max!) * 100}%`})}
style=${styleMap({width: `${(+value / +(max || 1 /* If no max then just render full bar */)) * 100}%`})}
></div>
</div>
</div>
Expand All @@ -362,7 +364,7 @@ export class NftCardBackTemplate extends LitElement {
for (let i = 0; i < props.length && i < DISPLAY_MAX; i++) {
propsTemplate.push(html`
<div class="trait_property">
<p class="trait_property-type">${NftCardBackTemplate.formatTrait(props[i].name)}</p>
<p class="trait_property-type">${NftCardBackTemplate.formatTrait(props[i].trait_type)}</p>
<p class="trait_property-value">${props[i].value}</p>
</div>
`)
Expand Down Expand Up @@ -431,10 +433,9 @@ export class NftCardBackTemplate extends LitElement {
const name = trait.trait_type

this.traits[type + 's'].push({
name,
value: trait.value,
...(type === TraitType.Ranking ? { max: collectionTraits[name].max as unknown as number } : {}),
trait_type: '',
trait_type: trait.trait_type,
display_type: ''
})
}
Expand Down
24 changes: 13 additions & 11 deletions src/nft-card-front.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import {
TemplateResult
} from 'lit-element'

import {classMap} from 'lit-html/directives/class-map'
import {styleMap} from 'lit-html/directives/style-map'
import { classMap } from 'lit-html/directives/class-map'
import { styleMap } from 'lit-html/directives/style-map'

import {OpenSeaAsset, OpenSeaFungibleToken, Order, Network} from 'opensea-js/lib/types'
import { OpenSeaAsset, OpenSeaFungibleToken, Order, Network } from 'opensea-js/lib/types'

enum ButtonType {
Manage = 'manage',
Expand All @@ -24,7 +24,7 @@ enum ButtonType {
Unlock = 'unlock'
}

const BTN_TEXT: {[index: string]: string} = {
const BTN_TEXT: { [index: string]: string } = {
[ButtonType.Manage]: 'manage this item ❯',
[ButtonType.Buy]: 'buy this item ❯',
[ButtonType.View]: 'view on openSea ❯',
Expand Down Expand Up @@ -162,7 +162,7 @@ export class NftCardFrontTemplate extends LitElement {
}
`
}
@property({type: Object}) public asset!: OpenSeaAsset
@property({type: Object}) public asset?: OpenSeaAsset
@property({type: Boolean}) public isOwnedByAccount!: boolean
@property({type: String}) public account!: string
@property({type: Boolean}) public horizontal!: boolean
Expand All @@ -182,10 +182,11 @@ export class NftCardFrontTemplate extends LitElement {

// Check for a sell order to populate the UI with the sell information
// TODO: We will be using lastSale here once added to SDK
if (this.asset.sellOrders!.length > 0) {
const order: Order = this.asset.sellOrders![0]
if (this.asset && this.asset.sellOrders && this.asset.sellOrders.length > 0) {
const order: Order = this.asset.sellOrders[0]
const paymentToken = order.paymentTokenContract
const currentPrice = +order.currentPrice!.toFixed() / Math.pow(10, paymentToken!.decimals)
const decimals = paymentToken ? paymentToken.decimals : 18 // Default decimals to 18
const currentPrice = order.currentPrice ? +order.currentPrice.toFixed() / Math.pow(10, decimals) : 0
const expires = new Date(order.expirationTime.toFixed())

this.lastSaleData = {
Expand Down Expand Up @@ -215,12 +216,12 @@ export class NftCardFrontTemplate extends LitElement {
let prevPriceTemplate: TemplateResult = html``
let currentPriceTemplate: TemplateResult = html``

if (this.lastSaleData) {
const currentPriceSymbol = this.lastSaleData.paymentToken!.symbol === 'ETH' ? 'Ξ ' : ''
if (this.lastSaleData && this.lastSaleData.paymentToken) {
const currentPriceSymbol = this.lastSaleData.paymentToken.symbol === 'ETH' ? 'Ξ ' : ''
currentPriceTemplate = html`<div class="asset-detail-price-current">${currentPriceSymbol} ${this.lastSaleData.currentPrice}</div>`
}

if (this.asset.lastSale) {
if (this.asset && this.asset.lastSale) {
// @ts-ignore ignore until LastSale type gets added to SDK
const formattedPrevPrice = this.asset.lastSale.total_price / Math.pow(10, this.asset.lastSale.payment_token.decimals)
// @ts-ignore ignore until LastSale type gets added to SDK
Expand All @@ -240,6 +241,7 @@ export class NftCardFrontTemplate extends LitElement {
* Implement `render` to define a template for your element.
*/
public render() {
if (!this.asset) { return undefined } // If there is no asset then we can't render
return html`
<div class="card-front ${classMap({'is-vertical': !this.horizontal})}">
<div class="asset-action-info">
Expand Down
99 changes: 61 additions & 38 deletions src/nft-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ export class NftCard extends LitElement {
.flipped-card .card-inner {
transform: rotateY(180deg);
}
.card .error {
height: 100%;
display: flex;
flex-flow: column;
justify-content: center;
}
.card .error-moji {
font-size: 50px;
}
.card .error-message {
font-size: 16px;
}
`
}

Expand All @@ -86,6 +98,7 @@ export class NftCard extends LitElement {

// Card state variables
@property({type: Boolean}) private loading = true
@property({type: Boolean}) private error = false
@property({type: Boolean}) private isOwnedByAccount = false
@property({type: Boolean}) private isUnlocked: boolean = false
@property({type: Boolean}) private hasWeb3: boolean = false
Expand Down Expand Up @@ -113,16 +126,21 @@ export class NftCard extends LitElement {
// Get the web3 provider
this.provider = NftCard.getProvider()

this.seaport = new OpenSeaPort(this.provider, {networkName: this.getNetwork()})
this.seaport = new OpenSeaPort(this.provider, {networkName: this.network})

this.asset = await this.seaport.api.getAsset(this.contractAddress, this.tokenId)
try {
this.asset = await this.seaport.api.getAsset(this.contractAddress, this.tokenId)
this.traitData = {
traits: this.asset.traits,
collectionTraits: this.asset.collection.traitStats
}

this.traitData = {
traits: this.asset.traits,
collectionTraits: this.asset.collection.traitStats
} catch (e) {
this.error = true
// Probably could not find the asset
console.error(e)
}

// We got the data so we are done loading
this.loading = false

// Tell the component to update with new state
Expand All @@ -146,6 +164,40 @@ export class NftCard extends LitElement {
}
}

public renderErrorTemplate() {
return html`
<div class="error">
<div class="error-moji">¯\\_(ツ)_/¯</div>
<div class="error-message">Problem loading asset.</div>
</div>`
}

public renderLoaderTemplate() {
return html`<loader-element></loader-element>`
}

public renderInnerCardTemplate() {
return html`
<nft-card-front
.horizontal=${this.horizontal}
@button-event="${this.eventHandler}"
.asset=${this.asset}
.state=${({
isOwnedByAccount: this.isOwnedByAccount,
isMatchingNetwork: this.isMatchingNetwork,
isUnlocked: this.isUnlocked,
hasWeb3: this.hasWeb3,
network: this.network
})}
.account=${this.account}
></nft-card-front>
<nft-card-back
.horizontal=${this.horizontal}
.traitData=${this.traitData}
></nft-card-back>
`
}

/**
* Implement `render` to define a template for your element.
*/
Expand All @@ -164,28 +216,9 @@ export class NftCard extends LitElement {
style=${styleMap({width: this.width, height: this.height})}
>
<div class="card-inner">
${this.loading ?
html`<loader-element></loader-element>`
:
html`
<nft-card-front
.horizontal=${this.horizontal}
@button-event="${this.eventHandler}"
.asset=${this.asset}
.state=${({
isOwnedByAccount: this.isOwnedByAccount,
isMatchingNetwork: this.isMatchingNetwork,
isUnlocked: this.isUnlocked,
hasWeb3: this.hasWeb3,
network: this.network
})}
.account=${this.account}
></nft-card-front>
<nft-card-back
.horizontal=${this.horizontal}
.traitData=${this.traitData}
></nft-card-back>
`
${this.loading ? this.renderLoaderTemplate() :
this.error ? this.renderErrorTemplate() :
this.renderInnerCardTemplate()
}
</div>
`
Expand Down Expand Up @@ -218,16 +251,6 @@ export class NftCard extends LitElement {
window.open(this.asset.openseaLink, '_blank')
}

private getNetwork() {
switch (this.network) {
case 'main':
return Network.Main
case 'rinkeby':
return Network.Rinkeby
default: return Network.Main
}
}

/**
* async connectWallet - Initializes connection to the injected web3 account
* Pre-Conditions: this.provider has been defined - this method should only
Expand Down
7 changes: 0 additions & 7 deletions src/pill.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
/**
* Import LitElement base class, html helper function,
* and TypeScript decorators
**/
import { LitElement, html, customElement, property, css } from 'lit-element'

import { styleMap } from 'lit-html/directives/style-map'
Expand All @@ -26,9 +22,6 @@ export class PillTemplate extends LitElement {
border: this.border
}

// @TODO: Add dynamic styles using styleMap directive
// @TODO: Add dynamic style text color
// @TODO: Add dynamic style border & border color
static get styles() {
return css`
.pill {
Expand Down
1 change: 1 addition & 0 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
true,
"check-branch",
"check-decl",
"check-module",
"check-operator",
"check-separator",
"check-rest-spread",
Expand Down
2 changes: 1 addition & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module.exports = {
devtool: 'source-map',
entry: './src/nft-card.ts',
output: {
filename: 'opensea-nft-card.min.js',
filename: 'nft-card.min.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
Expand Down
2 changes: 1 addition & 1 deletion webpack.dev.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module.exports = {
},
entry: './src/nft-card.ts',
output: {
filename: 'opensea-nft-card.min.js',
filename: 'nft-card.min.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
Expand Down

0 comments on commit 6353395

Please sign in to comment.