presentation front end from scratch event i a ls

199
Criando uma arquitetura de front-end do zero @shiota 2013

Upload: jhonleandres-barbosa-da-silva

Post on 13-May-2017

234 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Presentation Front End From Scratch Event i a Ls

Criando uma arquitetura de front-end do zero 

@shiota 2013

Page 2: Presentation Front End From Scratch Event i a Ls

olá!slideshare.net/eshiota

github.com/eshiota @shiota

Page 3: Presentation Front End From Scratch Event i a Ls
Page 4: Presentation Front End From Scratch Event i a Ls
Page 5: Presentation Front End From Scratch Event i a Ls

como a Baby (re)nasceu

Page 6: Presentation Front End From Scratch Event i a Ls

* reprodução pelo WaybackMachine, não é 100% precisa

Page 7: Presentation Front End From Scratch Event i a Ls

* reprodução do dia 27/08/2013

Page 8: Presentation Front End From Scratch Event i a Ls

projeto greenfield (a.k.a. o sonho de todo desenvolvedor)

Page 9: Presentation Front End From Scratch Event i a Ls

como estruturar o front-end do zero?

Page 10: Presentation Front End From Scratch Event i a Ls

filosofia de um front-end de larga escala

Page 11: Presentation Front End From Scratch Event i a Ls

Alta performance client-side.

Page 12: Presentation Front End From Scratch Event i a Ls

Interface facilmente modificável.

Page 13: Presentation Front End From Scratch Event i a Ls

Componentes portáveis entre diferentes aplicações.

Page 14: Presentation Front End From Scratch Event i a Ls

Bulletproof web design.

* veja http://simplebits.com/publications/bulletproof/

Page 15: Presentation Front End From Scratch Event i a Ls

Tipografia e grids flexíveis, responsive-ready.

Page 16: Presentation Front End From Scratch Event i a Ls

Baixa barreira de entrada para outros desenvolvedores.

Page 17: Presentation Front End From Scratch Event i a Ls

definição de suporte aos navegadores

Page 18: Presentation Front End From Scratch Event i a Ls
Page 19: Presentation Front End From Scratch Event i a Ls
Page 20: Presentation Front End From Scratch Event i a Ls

latest latest 5+ iOS 6+

8+

Page 21: Presentation Front End From Scratch Event i a Ls

latest latest 5+ iOS 6+

8+

u mad?

Page 22: Presentation Front End From Scratch Event i a Ls

O meu website precisa ter o visual exatamente igual em todos os navegadores?

Page 23: Presentation Front End From Scratch Event i a Ls
Page 24: Presentation Front End From Scratch Event i a Ls

O meu website precisa ter exatamente a mesma experiência em todos os navegadores?

Page 25: Presentation Front End From Scratch Event i a Ls
Page 26: Presentation Front End From Scratch Event i a Ls

A escolha dos navegadores e o nível de suporte influencia escolhas e tempo de desenvolvimento.

Page 27: Presentation Front End From Scratch Event i a Ls
Page 28: Presentation Front End From Scratch Event i a Ls

CSS

Page 29: Presentation Front End From Scratch Event i a Ls

pre-processors: sass

Page 30: Presentation Front End From Scratch Event i a Ls

O uso de partials ajuda a organizar os módulos.

Page 31: Presentation Front End From Scratch Event i a Ls

@import "compass/css3";!@import "base/variables";@import "base/functions";@import "base/mixins";@import "base/helpers";!@import "core/reset";@import "core/basic";@import "core/forms";@import "core/tables";@import "core/typography";@import "core/icons";@import "core/buttons";!@import "layout/main";@import "layout/header";@import "layout/footer";!@import "ui/loader";@import "ui/loaderBar";@import "ui/flashMessage";@import "ui/breadcrumb";

Page 32: Presentation Front End From Scratch Event i a Ls

app/ assets/ stylesheets/ base/ _functions.scss _mixins.scss _variables.scss ui/ _breadcrumb.scss _carousel.scss _dentedBox.scss _flashMessage.scss

Page 33: Presentation Front End From Scratch Event i a Ls

Variáveis ajudam a manter os mesmos padrões de interface.

Page 34: Presentation Front End From Scratch Event i a Ls

/*********************************************************************** Variables Module** All constants that will be used through the styles must be* defined here.**********************************************************************/!/********************************************************************** =Dimensions*********************************************************************/!$SITE_WIDTH: 978px;$FOOTER_HEIGHT : 812px;$DEFAULT_FONT_SIZE : 16px;!/********************************************************************** =Colors*********************************************************************/!$TEXT_COLOR: #555;$LINK_COLOR: #447f87;!$PURPLE: #905194;$LIGHT: #fefefa;$ORANGE: #fbb100;$YELLOW: #fffd7d;

Page 35: Presentation Front End From Scratch Event i a Ls

Mixins e placeholders padronizam repetições de código.

Page 36: Presentation Front End From Scratch Event i a Ls

/********************************************************************** =Image replacement** `display` property may be overridden by the element.*********************************************************************/!%image_replacement { text-indent: 101%; overflow: hidden; white-space: nowrap; display: block;}

Page 37: Presentation Front End From Scratch Event i a Ls

.my-logo { text-indent: 100%; overflow: hidden; white-space: nowrap; display: block; width: 200px; height: 280px; background: url("mylogo.png");}!.my-other-logo { text-indent: 100%; overflow: hidden; white-space: nowrap; display: block; width: 100px; height: 150px; background: url("myotherlogo.png");}

Page 38: Presentation Front End From Scratch Event i a Ls

.my-logo { @extend %image_replacement; width: 200px; height: 280px; background: url("mylogo.png");}!.my-other-logo { @extend %image_replacement; width: 100px; height: 150px; background: url("myotherlogo.png");}

Page 39: Presentation Front End From Scratch Event i a Ls

Mixins permitem a criação de temas.

Page 40: Presentation Front End From Scratch Event i a Ls

/* <div class="section-header my-theme1"> ... </div>*/!.section-header { width: 100%; height: 15em; color: #fff; background-color: #905194; background-position: center center; background-repeat: no-repeat; background-image: url("themes/default_bg.jpg"); text-align: center;}!.my-theme1 { background-color: #fbb100; color: #fff; background-image: url("themes/theme1_bg.jpg");}!.my-theme2 { background-color: #fefefa; color: #333; background-image: url("themes/theme2_bg.jpg");}

Page 41: Presentation Front End From Scratch Event i a Ls

/* <div class="section-header my-theme1"> ... </div>*/!@mixin header_theme($background_color: #905194, $text_color: #fff, $image: "default_bg.jpg") { background-color: $background_color; color: $text_color; background-image: url("themes/#{$image}");}

Page 42: Presentation Front End From Scratch Event i a Ls

/* <div class="section-header my-theme1"> ... </div>*/!.section-header { @include header_theme; width: 100%; height: 15em; background-position: center center; background-repeat: no-repeat; text-align: center;}!.my-theme1 { @include header_theme(#fefefa, #333, "theme2_bg.jpg");}!.my-theme2 { @include header_theme(#fefefa, #333, "theme2_bg.jpg");}

Page 43: Presentation Front End From Scratch Event i a Ls

(use com moderação)

Page 44: Presentation Front End From Scratch Event i a Ls

Funções aceleram o processo de desenvolvimento.

Page 45: Presentation Front End From Scratch Event i a Ls

// Returns unitless number@function remove-unit($number) { $unit: unit($number); $one: 1;! @if $unit == "px" { $one: 1px; } @if $unit == "em" { $one: 1em; } @if $unit == "%" { $one: 1%; }! @return $number / $one;}!// Returns flexible value using `target ÷ context` formula.// Returns `em` by default, accepts `%` as format.@function flex($target, $context, $unit: "em") { $size: remove-unit($target) / remove-unit($context);! @if $unit == "em" { @return #{$size}em; } @if $unit == "%" { @return percentage($size); }}!// Alias to `flex` function, using `%` as format.@function perc($target, $context: $DEFAULT_FONT_SIZE) { @return flex($target, $context, "%");}!// Alias to `flex` function, using `em` as format.@function em($target, $context: $DEFAULT_FONT_SIZE) { @return flex($target, $context, "em");}

Page 46: Presentation Front End From Scratch Event i a Ls

.product-title { font-size: 1.5625em; /* 25px / 16px */}

Page 47: Presentation Front End From Scratch Event i a Ls

.product-title { font-size: em(25px, 16px);}

Page 48: Presentation Front End From Scratch Event i a Ls

.product-title { font-size: em(25px);}

Page 49: Presentation Front End From Scratch Event i a Ls

Sintaxe SCSS: quase não há curva de adaptação para quem já escreve CSS.

Page 50: Presentation Front End From Scratch Event i a Ls

Extensões podem auxiliar de jeitos inimagináveis. (mais sobre isso daqui a pouco)

Page 51: Presentation Front End From Scratch Event i a Ls

modularização

Page 52: Presentation Front End From Scratch Event i a Ls

Front-end deve saber de programação?

Page 53: Presentation Front End From Scratch Event i a Ls

CSS possui muitas similaridades com princípios de programação.

Page 54: Presentation Front End From Scratch Event i a Ls

estrutura base (reset, base styles)

grid

padrões

módulos

módulos contextualizados

Page 55: Presentation Front End From Scratch Event i a Ls

Single Responsability Principle Módulos de CSS possuem comportamentos contidos e isolados.

Page 56: Presentation Front End From Scratch Event i a Ls

/******************************************************************************* UI » Flyout** Flyouts are those UI components that look like tooltip, and* are activated when the user clicks on a link. The flyout window* opens text to the link, like those present on the iPad.** **Usage**** <div class="flyout-container">* <div class="flyout [vertical-position]-[horizontal-position]-flyout">* Flyout content* </div>* </div>******************************************************************************/!.flyout-container { position: relative; z-index: 100; // may be adjusted as needed through a context}!.flyout { @include box-sizing(border-box); background: #f9f9f9; border-radius: 2px; border: 1px solid #d5d5d5; box-shadow: 0 2px 0 rgba(0, 0, 0, .1); display: none; position: absolute;! // tip &:after { content: ""; display: block; width: 40px; height: 22px; background: sprite($icon-sprite, tooltip_top_large_gray) no-repeat; position: absolute; }}!...

Page 57: Presentation Front End From Scratch Event i a Ls

Open/close Principle Módulos de CSS devem poder ser extendidos sem modificar sua definição core.

Page 58: Presentation Front End From Scratch Event i a Ls

/********************************************************************************* UI > Loader** Animated loader for AJAX requests********************************************************************************/!@mixin loader_sprite_position($xoffset, $yoffset) { background-position: sprite-position($icon-sprite, loader_sprite, $xoffset, $yoffset);}!.loader { width: 25px; height: 25px; display: none;}!.loader b { display: block; width: 25px; height: 25px; background-image: sprite-url($icon-sprite);}!.loader b,.loader .f1 { @include loader_sprite_position(-10px, -10px); }.loader .f2 { @include loader_sprite_position(-45px, -10px); }.loader .f3 { @include loader_sprite_position(-80px, -10px); }.loader .f4 { @include loader_sprite_position(-115px, -10px); }.loader .f5 { @include loader_sprite_position(-150px, -10px); }.loader .f6 { @include loader_sprite_position(-185px, -10px); }.loader .f7 { @include loader_sprite_position(-220px, -10px); }.loader .f8 { @include loader_sprite_position(-255px, -10px); }

Page 59: Presentation Front End From Scratch Event i a Ls
Page 60: Presentation Front End From Scratch Event i a Ls
Page 61: Presentation Front End From Scratch Event i a Ls
Page 62: Presentation Front End From Scratch Event i a Ls

// On ui/_buttons.scss!.bt-wrapper .loader { position: absolute; z-index: 4; right: 20px; top: 50%; margin-top: -9px;}!// On modules/_checkoutAddressForm.scss!.address-form .cep-input .loader { position: absolute; right: -33px; top: em(29px);}

Page 63: Presentation Front End From Scratch Event i a Ls

Dependency Inversion Principle Módulos macro não devem ter seus layouts alterados por módulos micro.

Page 64: Presentation Front End From Scratch Event i a Ls

.flyout

Page 65: Presentation Front End From Scratch Event i a Ls

guias de estilo

Page 66: Presentation Front End From Scratch Event i a Ls

#cheat #wip

Page 67: Presentation Front End From Scratch Event i a Ls
Page 68: Presentation Front End From Scratch Event i a Ls

JavaScript

Page 69: Presentation Front End From Scratch Event i a Ls

qual framework usar?

Page 70: Presentation Front End From Scratch Event i a Ls
Page 71: Presentation Front End From Scratch Event i a Ls

Analise qual (ou se) vale a pena.

Page 72: Presentation Front End From Scratch Event i a Ls

Você precisa de rotas client-side?

Page 73: Presentation Front End From Scratch Event i a Ls

Você precisa de sincronização e persistência de modelos client-side?

Page 74: Presentation Front End From Scratch Event i a Ls

Você precisa de uma solução pronta pra fazer bind entre view e dados?

Page 75: Presentation Front End From Scratch Event i a Ls

Você precisa de uma estrutura pronta e fechada para manter a consistência do código?

Page 76: Presentation Front End From Scratch Event i a Ls

Às vezes você não precisa de um framework terceiro. =)

Page 77: Presentation Front End From Scratch Event i a Ls

Talvez tudo o que você precise seja um código consistente e organizado.

Page 78: Presentation Front End From Scratch Event i a Ls

decisões de arquitetura

Page 79: Presentation Front End From Scratch Event i a Ls
Page 80: Presentation Front End From Scratch Event i a Ls

"Mas Shiota, todo mundo falou pra eu abandonar o jQuery!"

Page 81: Presentation Front End From Scratch Event i a Ls

O jQuery diminui bastante a barreira de entrada e dá agilidade.

Page 82: Presentation Front End From Scratch Event i a Ls

Analise a necessidade. Pese os benefícios. Pesquise outras soluções.

Page 83: Presentation Front End From Scratch Event i a Ls

single entry points

Page 84: Presentation Front End From Scratch Event i a Ls

(function(){ window.app = jQuery.extend({ init: function(){ tab = $('.tabs li > a.tab-toggle'); tabs = $('.tabs').find('> div');! if (tabs.length > 1){ tab.each(function (i){$(this).attr('href', '#content-' + ++i)}); tabs.each(function(i){$(this).attr('id', 'content-' + ++i)}); tabs.addClass('tab-inactive'); $('.tabs li:first-child a').addClass('state-active'); }! $('#initial-cash, #financing_value_vehicles, #tax, #bid-initial-cash, #bid-product-value').maskMoney({ thousands: '.', decimal: ',', allowZero: true, allowNegative: false, defaultZero: true });! /** FINANCING CALCULATOR **/ $("#financing_value_vehicles").on("blur", function(){ var price = (accounting.unformat($(this).val(), ",")) || 0;! var suggestedInitialPayment = price * 0.2;! var formattedResult = accounting.formatMoney(suggestedInitialPayment, "", "2", ".", ","); $("#initial-cash").val(formattedResult); });!! $("#calculate-financing").click(function(event){ var price = (accounting.unformat($("#financing_value_vehicles").val(), ",")) || 0;! var rate = (accounting.unformat($("#tax").val(), ",") / 100) || 0;! var initialCash = (accounting.unformat($("#initial-cash").val(), ",")) || 0;! var value = (accounting.unformat($("#amount-finance").val(), ",")) || 0; var finance = price - initialCash;! var months = (accounting.unformat($("#prize_parcela").val(), ",")) || 0; var tax = parseFloat(rate);!

Page 85: Presentation Front End From Scratch Event i a Ls

Page load

jQuery load

jQuery plugins

application.js

Page 86: Presentation Front End From Scratch Event i a Ls

Pontos únicos de entrada controlam o flow da aplicação.

Page 87: Presentation Front End From Scratch Event i a Ls

Page load

Vendor code

Application modules

application.js

dispatcher.js

beforeCommand controllerCommand actionCommand afterCommand

Page 88: Presentation Front End From Scratch Event i a Ls

Page load

Vendor code

Application modules

application.js

dispatcher.js

beforeCommand controllerCommand actionCommand afterCommand

Page 89: Presentation Front End From Scratch Event i a Ls

<body data-dispatcher="<%= dispatcher_label %>">

Page 90: Presentation Front End From Scratch Event i a Ls

<body data-dispatcher="products#show">

Page 91: Presentation Front End From Scratch Event i a Ls

dispatcher.js

beforeCommand()

productsControllerCommand()

productsShowCommand()

afterCommand()

products#show

Page 92: Presentation Front End From Scratch Event i a Ls

Os commands não contêm lógica, apenas inicializam outros módulos.

Page 93: Presentation Front End From Scratch Event i a Ls

namespaces

Page 94: Presentation Front End From Scratch Event i a Ls

"JavaScript é zoado! Não tem nem namespaces!"

Page 95: Presentation Front End From Scratch Event i a Ls

window.MYAPP = { commands : { productsShowCommand : function () { console.log("Execute code from products#show page"); } }};!MYAPP.commands.productsShowCommand();

Page 96: Presentation Front End From Scratch Event i a Ls

"Mas ficar declarando objetos é um saco, e você pode acabar sobrescrevendo..."

Page 97: Presentation Front End From Scratch Event i a Ls

;(function (root) { root.ns = function (name, obj, scope) { var parts = name.split(".") , curScope = scope || root , curPart , curObj ;! obj = obj || {};! while (typeof (curPart = parts.shift()) !== "undefined") { curObj = (parts.length > 0) ? ((typeof curScope[curPart] !== "undefined") ? curScope[curPart] : {}) : obj;! curScope[curPart] = curObj;! curScope = curScope[curPart]; }! return curScope; };})(this);

Page 98: Presentation Front End From Scratch Event i a Ls

ns("MYAPP.commands.productsShowCommand", function () { console.log("Execute code from products#show page");});!// Same as:!window.MYAPP = { commands : { productsShowCommand : function () { console.log("Execute code from products#show page"); } }};

Page 99: Presentation Front End From Scratch Event i a Ls

module.js

Page 100: Presentation Front End From Scratch Event i a Ls
Page 101: Presentation Front End From Scratch Event i a Ls

Define namespaces e coloca açúcar sintático na definição de funções construtoras.

Page 102: Presentation Front End From Scratch Event i a Ls

window.EDEN = window.EDEN || {};EDEN.forms = EDEN.forms || {};!EDEN.forms.AddressForm = function (el) { this.element = $(el); this.init();}!$.extend(EDEN.forms.AddressForm.prototype, {! // Public methods // --------------! // Inits the instance init : function () { // Do something }!});!var shippingAddressForm = new EDEN.forms.AddressForm($("#shipping-address"));

Page 103: Presentation Front End From Scratch Event i a Ls

Module("EDEN.forms.AddressForm", function (AddressForm) {! AddressForm.fn.initialize = function (el) { this.element = $(el);! // Do form stuff }!});!var shippingAddressForm = Module.run("EDEN.forms.AddressForm", $("#shipping-address"));!// or!var shippingAddressForm = new EDEN.forms.AddressForm($("#shipping-address"));

Page 104: Presentation Front End From Scratch Event i a Ls

Padroniza a criação de novos módulos.

Page 105: Presentation Front End From Scratch Event i a Ls

desacoplamento via eventos

Page 106: Presentation Front End From Scratch Event i a Ls
Page 107: Presentation Front End From Scratch Event i a Ls
Page 108: Presentation Front End From Scratch Event i a Ls

MEDIATOR

Page 109: Presentation Front End From Scratch Event i a Ls

MEDIATOR

Mediator, me avisa quando sair o novo do Game of

Thrones?

Blz

Page 110: Presentation Front End From Scratch Event i a Ls

MEDIATOR

Mediator, me avisa quando sair o novo do Mythbusters?

É nóish.

Page 111: Presentation Front End From Scratch Event i a Ls

MEDIATOR

Mediator, saiu um eppy novo de Game of Thrones.

Subscribers, saiu um eppy novo de Game of Thrones!

Ae, vou baixar, acho que vai ser feliz e tal

=D

Page 112: Presentation Front End From Scratch Event i a Ls

MEDIATOR

Mediator, saiu um eppy novo de Mythbusters.

Subscribers, saiu um eppy novo de Mythbusters!

Ae, vou baixar!

Page 113: Presentation Front End From Scratch Event i a Ls

Os módulos só conhecem o mediator.

Page 114: Presentation Front End From Scratch Event i a Ls
Page 115: Presentation Front End From Scratch Event i a Ls
Page 116: Presentation Front End From Scratch Event i a Ls
Page 117: Presentation Front End From Scratch Event i a Ls
Page 118: Presentation Front End From Scratch Event i a Ls
Page 119: Presentation Front End From Scratch Event i a Ls
Page 120: Presentation Front End From Scratch Event i a Ls
Page 121: Presentation Front End From Scratch Event i a Ls
Page 122: Presentation Front End From Scratch Event i a Ls
Page 123: Presentation Front End From Scratch Event i a Ls
Page 124: Presentation Front End From Scratch Event i a Ls

módulos desacoplados, com comportamentos específicos e isolados

Page 125: Presentation Front End From Scratch Event i a Ls
Page 126: Presentation Front End From Scratch Event i a Ls

// Code inside ShippingAddressForm!_registerInterests : function () { this.element.find(".cep-input") .on("keyup paste cut", this._onCepModification.bind(this)); },!_onCepModification : function (event) { if (this.isCepFilled()) { EDEN.mediator.trigger("shipping-cep-change", event.target.value); } else { EDEN.mediator.trigger("shipping-cep-incomplete", event.target.value); }}

Page 127: Presentation Front End From Scratch Event i a Ls
Page 128: Presentation Front End From Scratch Event i a Ls

// Code inside checkoutModule!_registerInterests : function () { EDEN.mediator.on("shipping-cep-change", this._onShippingCepChange, this); this.shippingService.on("get-success", this._onShippingGetSuccess, this);},!_onShippingCepChange : function (cep) { this.shippingService.get(cep);}!_onShippingGetSuccess : function (data) { EDEN.mediator.trigger("shipping-rate-change", data.rate); EDEN.mediator.trigger("delivery-estimate-change", data.estimate);}

Page 129: Presentation Front End From Scratch Event i a Ls
Page 130: Presentation Front End From Scratch Event i a Ls

// Code inside purchseInfo!_registerInterests : function () { EDEN.mediator.on("shipping-rate-change", this._onShippingRateChange, this); EDEN.mediator.on("delivery-estimate-change", this._onDeliveryEstimateChange, this);},!_onShippingRateChange : function (rate) { this.updateShippingRate(rate);},!_onDeliveryEstimateChange : function (days) { this.updateDeliveryEstimate(days);},!updateShippingRate : function (rate) { var formatter = EDEN.currency.formatter;! this.element.find(".shipping-rate").text(formatter(rate)); this.shippingRate = rate;! this.updateTotal();},!updateTotal : function () { var total = this.subtotal + this.shippingRate, formatter = EDEN.currency.formatter;! this.element.find(".total").text(formatter(total));! EDEN.mediator.trigger("cart-total-change", total);}

Page 131: Presentation Front End From Scratch Event i a Ls
Page 132: Presentation Front End From Scratch Event i a Ls

// Code inside installmentSelector!_registerInterests : function () { EDEN.mediator.on("cart-total-change", this._onCartTotalChange, this);},!_onCartTotalChange : function (total) { this.updateInstallments(total);},!updateInstallments : function (total) { // Updates the values}

Page 133: Presentation Front End From Scratch Event i a Ls

testes

Page 134: Presentation Front End From Scratch Event i a Ls
Page 135: Presentation Front End From Scratch Event i a Ls

describe("EDEN.ui.Loader", function () { var Loader = EDEN.ui.Loader;! beforeEach(function () { loadFixtures("loader.html"); });! afterEach(function () { $("body").find(".loader").remove(); });! it("accepts instance creation without new operator", function () { var newLoader = Loader();! expect(newLoader).toBeInstanceOf(Loader); });! it("appends the loader to body as a default", function () { var loader = new Loader();! expect($("body").find(".loader").length).toEqual(1); });! it("appends the loader through an argument function", function () { var loader = new Loader(function ($loader) { $("#loader-placeholder").append($loader); });! expect($("#loader-placeholder").find(".loader").length).toEqual(1); });});

Page 136: Presentation Front End From Scratch Event i a Ls

"Mas se eu escrever teste de JavaScript, eu não entrego o projeto!"

Page 137: Presentation Front End From Scratch Event i a Ls
Page 138: Presentation Front End From Scratch Event i a Ls

(e os testes de JavaScript quebram o build do CI.)

Page 139: Presentation Front End From Scratch Event i a Ls

"Mas pra que teste de JavaScript?"

Page 140: Presentation Front End From Scratch Event i a Ls

— "Precisamos atualizar o jQuery de 1.4 para 1.10"

Page 141: Presentation Front End From Scratch Event i a Ls
Page 142: Presentation Front End From Scratch Event i a Ls
Page 143: Presentation Front End From Scratch Event i a Ls
Page 144: Presentation Front End From Scratch Event i a Ls

Testes dão a segurança para atualizações, modificações e substituições.

Page 145: Presentation Front End From Scratch Event i a Ls

HTML

Page 146: Presentation Front End From Scratch Event i a Ls

sintaxe: erb

Page 147: Presentation Front End From Scratch Event i a Ls

<% product.foreach_variant(current_cart) do |variant, size, i| %> <label class="variant"> <input value="<%= size.value %>" name="product_size" type="radio" data-price="<%= variant.price.to_f %>" data-variant-sku="<%= variant.sku %>" class="<%= "disabled" unless variant.has_stock? %>" /> <span class="variant-name"><%= size.value %></span> </label><% end %>

Page 148: Presentation Front End From Scratch Event i a Ls

Próximo do HTML puro.

Page 149: Presentation Front End From Scratch Event i a Ls

Todos sabem (ou deveriam saber) escrever HTML puro.

Page 150: Presentation Front End From Scratch Event i a Ls

Menos uma dependência no projeto.

Page 151: Presentation Front End From Scratch Event i a Ls

classes semânticas

Page 152: Presentation Front End From Scratch Event i a Ls

Usem classes que descrevem o conteúdo e não o estilo.

Page 153: Presentation Front End From Scratch Event i a Ls
Page 154: Presentation Front End From Scratch Event i a Ls

<div class="column-left"> <!-- Dropdown Categoria --> <!-- Dropdown Marca --></div>!<div class="column-right"> <!-- Product Navigation --> <!-- Products List --></div>

Page 155: Presentation Front End From Scratch Event i a Ls
Page 156: Presentation Front End From Scratch Event i a Ls
Page 157: Presentation Front End From Scratch Event i a Ls

column-left?

column-right?

Page 158: Presentation Front End From Scratch Event i a Ls

Classes semânticas desacoplam o documento do estilo.

Page 159: Presentation Front End From Scratch Event i a Ls

<div class="products-search-filters"> <!-- Dropdown Categoria --> <!-- Dropdown Marca --></div>!<div class="products-search-filtered-results"> <!-- Product Navigation --> <!-- Products List --></div>

Page 160: Presentation Front End From Scratch Event i a Ls

products-search-filters

products-search-filtered-results

Page 161: Presentation Front End From Scratch Event i a Ls

Maior portabilidade do markup entre diferentes projetos.

Page 162: Presentation Front End From Scratch Event i a Ls
Page 163: Presentation Front End From Scratch Event i a Ls

data-attributes

Page 164: Presentation Front End From Scratch Event i a Ls
Page 165: Presentation Front End From Scratch Event i a Ls

contentDropdown.js

Page 166: Presentation Front End From Scratch Event i a Ls

Componentes com mesmo comportamento podem ter estilos diferentes.

Page 167: Presentation Front End From Scratch Event i a Ls

<div class="size-selector"> <div class="size-selector-header" data-dropdown-header> <!-- some title, could be anything --> </div>! <div class="size-selector-content" data-dropdown-content> <!-- content here --> </div></div>!<div class="filter-selector"> <div class="filter-selector-header" data-dropdown-header> <!-- some title, could be anything --> </div>! <div class="filter-selector-content" data-dropdown-content> <!-- content here --> </div></div>

Page 168: Presentation Front End From Scratch Event i a Ls

Classes diferentes, estilos diferentes.

Page 169: Presentation Front End From Scratch Event i a Ls

data-attributes iguais, comportamento igual.

Page 170: Presentation Front End From Scratch Event i a Ls

// Inits the `ContentDropdown` instance//// * `el`: jQuery selectorinit : function (el) { this.element = $(el); this.content = this.element.byData("dropdown-content"); this.selection = this.element.byData("dropdown-selection");}

Page 171: Presentation Front End From Scratch Event i a Ls

$.fn.byData = function (dataAttr) { return $(this).find("[data-" + dataAttr + "]");};

Page 172: Presentation Front End From Scratch Event i a Ls

Comportamento é adicionado através dos data-attributes.

Page 173: Presentation Front End From Scratch Event i a Ls

dicas adicionais

Page 174: Presentation Front End From Scratch Event i a Ls

performance client-side

Page 175: Presentation Front End From Scratch Event i a Ls

Faça sprites. De preferência, de maneira automágica.

Page 176: Presentation Front End From Scratch Event i a Ls
Page 177: Presentation Front End From Scratch Event i a Ls

$icon-sprite: sprite-map("icon/*.png", $spacing: 16px, $repeat: no-repeat, $layout: vertical);

Page 178: Presentation Front End From Scratch Event i a Ls

$icon-sprite: sprite-map("icon/*.png", $spacing: 16px, $repeat: no-repeat, $layout: vertical);

Page 179: Presentation Front End From Scratch Event i a Ls

/* Compass sprite function receives the map variable and image as arguments */!background: sprite($icon-sprite, arrow_dropdown) no-repeat;

/* Compiled CSS */!background: url(/assets/icon-s5dab8c2901.png) -40px -158px no-repeat;

Page 180: Presentation Front End From Scratch Event i a Ls

Use inline images para imagens < 1KB que estarão apenas em um lugar do CSS.

Page 181: Presentation Front End From Scratch Event i a Ls
Page 182: Presentation Front End From Scratch Event i a Ls

/* Compiled CSS */!background: #f5f3fb url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAQCAMAAAAcVM5PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAlQTFRF5+TW////////4qZUpQAAAAN0Uk5T//8A18oNQQAAACBJREFUeNpiYGBgAgMGBkYog4mJXAbILAiDkVxzAAIMAEMOAPMId2OWAAAAAElFTkSuQmCC') repeat;

/* Generates a base64 image */!background: #f5f3eb inline-image("bg_dots.png") repeat;

Page 183: Presentation Front End From Scratch Event i a Ls

Use lazy-load onde fizer sentido.

Page 184: Presentation Front End From Scratch Event i a Ls
Page 185: Presentation Front End From Scratch Event i a Ls
Page 186: Presentation Front End From Scratch Event i a Ls

code standards

Page 187: Presentation Front End From Scratch Event i a Ls
Page 188: Presentation Front End From Scratch Event i a Ls

"O código deve parecer que foi escrito pela mesma pessoa, independente de quem o escreveu."

Page 189: Presentation Front End From Scratch Event i a Ls

Código consistente: maior legibilidade, manutenção mais fácil, evita bikeshedding.

Page 190: Presentation Front End From Scratch Event i a Ls

build para o deploy

Page 191: Presentation Front End From Scratch Event i a Ls

Ruby on Rails » Asset Pipeline » ♥

Page 192: Presentation Front End From Scratch Event i a Ls
Page 193: Presentation Front End From Scratch Event i a Ls
Page 194: Presentation Front End From Scratch Event i a Ls

TL;DR

Page 195: Presentation Front End From Scratch Event i a Ls

Alta performance client-side Interface facilmente modificável Componentes portáveis entre diferentes aplicações Bulletproof web design Tipografia e grids flexíveis, responsive-ready Baixa barreira de entrada para outros desenvolvedores

Page 196: Presentation Front End From Scratch Event i a Ls

Não saia adicionando códigos de terceiros sem pensar.

Page 197: Presentation Front End From Scratch Event i a Ls

Front-end deixou de ser coisa de agência e sobrinho.

Page 198: Presentation Front End From Scratch Event i a Ls
Page 199: Presentation Front End From Scratch Event i a Ls

obrigado!slideshare.net/eshiota

github.com/eshiota @shiota