Skip to content

Instantly share code, notes, and snippets.

@DylanPiercey
Last active August 18, 2020 18:00
Show Gist options
  • Save DylanPiercey/620497aaa687a31ddf006a1a3c94c58a to your computer and use it in GitHub Desktop.
Save DylanPiercey/620497aaa687a31ddf006a1a3c94c58a to your computer and use it in GitHub Desktop.
Marko gif keyboard component
static const API_KEY = "ENTER YOUR API KEY";
static const GIF_LIMIT = 7;
class {
onCreate() {
this.state = {
page: 0,
search: "",
images: [],
totalPages: 0
};
}
handleSearchChange(ev) {
this.state.page = 0;
this.state.search = ev.target.value;
if (this.state.search) {
this.getGifs();
} else {
this.state.images = [];
this.state.totalPages = 0;
}
}
handlePageChange(direction) {
this.state.page += direction;
this.getGifs();
}
async getGifs() {
const { search, page } = this.state;
const res = await fetch(
`https://api.giphy.com/v1/gifs/search?rating=g&api_key=${API_KEY}&limit=${GIF_LIMIT}&offset=${page}&q=${search}`
);
const { data, pagination } = await res.json();
this.state.images = data;
this.state.totalPages = Math.ceil(pagination.total_count / GIF_LIMIT);
}
}
style {
.gif-keyboard {
display: flex;
flex-direction: column;
align-items: center;
}
.gif-keyboard__search {
width: 500px;
font: system-ui;
font-size: 1.5em;
padding: 0.25em;
margin: 1em;
}
.gif-keyboard__message {
color: #fff;
text-align: center;
font-size: 2em;
margin: 0;
}
.gif-keyboard__images {
display: flex;
margin: 1em;
justify-content: space-between;
align-items: center;
}
.gif-keyboard__image {
margin: 0.25em;
transition: transform 0.3s ease;
}
.gif-keyboard__pagination {
border-radius: 50%;
margin: 1em;
height: 2em;
width: 2em;
background: #fff;
border: none;
font-size: 1.5em;
font-weight: bold;
color: #3088cb;
transition: transform 0.15s ease-in;
}
.gif-keyboard__pagination:not(:disabled):hover,
.gif-keyboard__image:hover {
transform: translateY(-3px);
cursor: pointer;
}
.gif-keyboard__pagination:disabled {
opacity: 0.5;
}
}
<div.gif-keyboard>
<input.gif-keyboard__search
value=state.search
placeholder="Enter a search..."
on-input("handleSearchChange")/>
<if(state.images.length)>
<div.gif-keyboard__images>
<button.gif-keyboard__pagination
disabled=(state.page === 0)
on-click("handlePageChange", -1)>
<
</button>
<for|image| of=state.images>
<a.gif-keyboard__image href=image.bitly_url key=image.id>
<img.gif-gallery__gifGalley__image__link src=image.images.fixed_width_small.url/>
</a>
</for>
<button.gif-keyboard__pagination
disabled=(state.page === state.totalPages - 1)
on-click("handlePageChange", 1)>
>
</button>
</div>
</if>
<else>
<p.gif-keyboard__message>
<if(state.search)>Unable to find GIFs relating to ${state.search}</if>
<else>Search for GIFs as you type!</else>
</p>
</else>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment