CSS

Showing posts with label front-end. Show all posts
Showing posts with label front-end. Show all posts

Termkit - Graphical Terminal

Termkit is an interesting project that focus on the improvement of terminal.

The UNIX terminal we use right now is established in the time of mainframe.

It is still powerful because it's simplicity and ability to script. The terminal output can be pipelined as input to other programs, and the command can be easily scripted and recognized by programs. Unlike GUI, it's hard to script the simple action like: click this red button and open this file. However, because the command is used by both human and machine. It is pretty unfriendly for beginner and unfriendly in terms of today's UI design. The target of termkit is adding a visual layer for terminal. like we can output the command in different color, the folder and files type with icon, autocomplete with commands and tooltip of command switches.

The structure is like this:

input => process => output for program
||
termkit => output for human

and termkit is using webkit for visual presentation, and node.js for glue the process with webkit.

Install:

install node.js , npm

npm install mime (for webkit to distinguish content type)

git clone https://github.com/unconed/TermKit.git --recursive

run the termkit demean

cd TermKit/Node; node nodekit.js

run client

cd Termkit/Build; unzip Termkit.zip; open Termkit.app


This project is still on an early stage. But it show an different aspect of GUI improvement. Like an different approach of sikuli.
https://github.com/unconed/TermKit

Introduction of SCSS and Compass

Recently, the CSS tool like SCSS,SASS and less have become more popular.
Those framework provide several extra functionality to CSS, also with build in compress option.
take SCSS as example:

install scss using ruby gem:


gem install sass
    sass style.scss style.css 
    sass [INPUT] [OUTPUT]

functions


1. Nesting class

#css{
     padding:5px;
     .tool{
          padding-top:10px;
     }
     //parent reference
     &:hover{
          background-color:#FFF;
     }
}


2.Variables
you can use dollar sign as variable mark in SCSS:
$mid-padding : 5px;

#css{
     padding : $mid-padding;
}

3. Mixins
Mixins means module inheritance in Ruby. It's just like inheritance from abstract class in SCSS. Use @ sign for declare maxin and include in css class.

@mixin block-base($margin){
     margin:$margin;
     padding:$padding;
}

#block{
     @include block-base(10px);
}

4. Inheritance
Also you can use @extend to inheritance from other CSS class.
.error{
     color:#F43;
}

.big-error{
     @extend .error
     font-size: 22px;
}

5. import
Import can let you include library and mixins into current css file, like compass will have lots of library to import.
@import "compass/css3/border-radius";
@import "compass/utilities/general/clearfix";

Compass


Compass is another framework that integrate SCSS and CSS grid framework like blueprint,
that provide you build in CSS layout, ie hack and other support. Compass is well integrated with rails.

using compass:

gem install compass
    compass init (under rails directory)

will create directory in app/stylesheets

compass compile

can compile into public/stylesheets directory

more reference for compass library

Backbone.js - MVC framework for front-end javascript

What is Backbone.js?


Backbone is a framework for front-end JavaScript, unlike jQuery focus on easier DOM manipulation and event binding, backbone provide a structure for separating data model and DOM, just like a MVC framework separate model, view and controller. Make heavy JavaScript application easier to develop and maintain.

Why Backbone?


In jQuery, we will write a sequence of chain selector for assign data model to DOM element like:

var article = {
  author:"Joe",
  content: "testing"
};
$('#article').click(function(event){
  $(this).find('.content').text(article.content);
});
For backbone, it provide the Model class and View class, which is the main two element of backbone.
var Article = Backbone.Model;

var article = new Article({
  author:"Joe",
  content: "testing"
});

var ArticleView = Backbone.View.extend({
  el: $('#article'),
  initialize: function(){
    _.bindAll(this,'updateContent');
    this.model.bind('change',this.updateContent);
  },
  events: {
    "click .content" : "updateContent"
  },
  updateContent: function(){
    this.$('.content').text(this.model.get("content"));
  }
});

var articleView = new ArticleView({model:article});
OK, it's seen like a completely overwork, that's my first thought when I see a clientside MVC framework too, but we have to dig further to understand why people create it.

Event Binding


First, it separate the data model and view - which include event handle and DOM element, we can easily bind data model in view like:
this.model.bind('change',this.updateContent);
It means when the data model change, the view will be automatically updated to DOM element.

Also, backbone provide literal event binding:
events:{
  "click .content": "updateContent"
}
which bind the "click" event to ".content" class, trigger "updateContent" function in current view.
It's useful when binding multiple events.

Restful synchronization


Furthermore, the backbone provide a RESTful format API for synchronize data model with server.
every model class in backbone have a corresponding url for synchronize, and when the "model.save" or "model.fetch" method is called, the model will make an Ajax request to update data with server.
For example:
article.save({author:"John"});
will first find article.sync method, if undefined, call Backbone.sync.
The sync method will make an ajax request to server, and update model, trigger event and update to view.

the url of model is defined by RESTful API:

  • create -> POST /model
  • read -> GET /model[/id]
  • update -> PUT /model/id
  • delete -> DELETE /model/id

and we can also change it by overwrite url parameter

Dependency


backbone.js depend on underscore.js and jQuery/Zepto library, since it is only a 3.9k framework focus on the structure of JavaScript application.

Collection and Controller

backbone provide Collection, which is the collection of Backbone.Model,
the Controller in backbone is more like the route map in MVC framework, it provide clientside fragment url routing, eg. "/#article/12" match "article(id)". So the url can be recorded and bookmarked by browser.

Template

In Backbone, we can create template in view.
In that way we can add and remove multiple view and render with template.
The underscore.js provide template engine or we can use other engine too.

In view:
render:function(){
    var template = "
<%=content %>
"; $(this.el).html( this.template(this.model.toJSON()) ); return this; }

Conclusion


JavaScript MVC framework is good for rich client application and also can keep your javascript cleaner.
But whether to use it depend on how much script in your application, for small page, the MVC is total overhead, but it is good for large scale page like Mail or Desktop like application.

More

Backbone
Sample todo application
Annotated source

mini BDD Framework in CoffeeScript

Rails 3.1 is default supporting Coffee-Script,

This might be controversial, but basically I think it is a right move,
since rails development philosophy is always simplify developer's life.
And coffee script sure is.


compare the following code with javascript and coffee script:
describe('spec in javascript', function(){
  it('should return true in javascript',function(){
    return 1===1;
  });
});

//in coffee script
describe 'spec in coffeescript', ->
  it 'should return true in coffeescript',->
    1 is 1

You can see how the syntax has been simplified and easy to read.

Inspired by A unit test framework in 44 lines of ruby, I want to write a test framework in coffeescript to show the good of it.

Here's the work:
dsl =
  tests : {}
  it : (description,test) ->
    @tests[description] = test
  parse:(block)->
    block.call(dsl)
    @tests

class Executor
  constructor: (@description,@tests) ->
  tests : {}
  success : 0
  fail : 0
  count : 0
  run:()->
    console.log(@description + " ::")
    @execute desc,test for desc,test of @tests
    console.log("Executed #{@count} tests: #{@success} success, #{@fail} fail")

  execute : (desc,test) ->
    test_result = test()
    if test_result is yes than @success += 1 else @fail += 1
    @count += 1
    console.log(" --"+ desc + " is "+ test_result)

exports.describe = (description,block) ->
  executor = new Executor(description,dsl.parse(block))
  executor.run()

with the following testcase

spec = require './nspec'

spec.describe 'hello coffee test', ->

  @it 'should be true', ->
    1 is 1

  @it 'should fail', ->
    1 is 2

Basically the describe function contains all tests in callback,
and will parse all the testcase by
block.call(dsl)
which inject the dsl functions as the "this" object in block, and the "it" syntax will collect the test functions to a map object.
afterward, Executor will execute all tests and print out results.

During the implementation, I can't find the way to remove that nasty @ before test function 'it'
without declaring global. I am still working on it, there's a solution that you can execute test
by calling node.js child_process "coffee spec.coffee"(from coffee-spec), but that will be too complex for this. Jasmine didn't have this problem, let me know if anyone got the answer, or I will figure it out later :p.

F2E Interview Questions

Here are some interview questions from a front-end engineering job, through I didn't get that position , these questions are pretty interesting and might help the others who want to get a Front-end job. So here are the questions:

1.Weird Width:

I create this <div/> to have my article inside. However, my nit picking product manager finds the width of this block is a little different between Internet Explorer 6 and Firefox. Can you help me to fix this weird bug?
In Internet Explorer, the width is 500px.
In Firefox 3, the width is 522px.
Can you help to correct my attached file so that the page is identical in different browsers? It would be great if you can tell me why so that I won't do that stupid thing again. And if you have spare time, please style the page for me since I am so lazy. ^^』』


Ans:

First of all, the problem of weird width is because older IE browser has different explanation in CSS box model.

The IE explained CSS width attribute as the width of content + padding + border. As the result, we get the width of 500px in IE browser that includes padding and border, in contrast of 522px in other modern browser.

Internet explorer 6+ has two mode of CSS interpretation:
Quirk mode – the interpretation of IE's own standard
standard-compliant mode – according the W3C standard (almost)
By define the <!DOCTYPE> tag we can switch the IE to standard-compliant mode. So here's the solution:
<!DOCTYPE>
By attach this before <html> tag, we can get correct width


2.Horizontal Toolbar

Product manager asks me to make a horizontal toolbar for our website.
Even if user scrolls, toolbar will always stay at the bottom of page. Another requirement is that all modern browsers are compatible with this new feature. (Internet Explorer 6 - 8, Firefox, Opera, Google Chrome, and Safari) After making a prototype I find it's really difficult. Please teach me how to do that.


Ans:

The CSS { position: fixed } attribute can build the toolbar in same position whenever scrolling. So the solution is:
#toolbar { position: fixed ; bottom:0; width:100%; }
Unfortunately, our old IE6 friend doesn't support it.
Again, search for some hack at web, we found 2 approaches:
1. JavaScript approach: which auto re-assigns position when event called.
2. CSS approach:
Using CSS expression or, Using wrapper
I use wrapper method because it's the simplest to me.



Normally, the { position:absolute } attribute will anchor the element according root element. Therefore we can set another element outside to be the root and have height equal to the screen. So the { position:absolute } attribute can place toolbar in right position. And by set the {overflow:hidden} attribute, we can hide the content outside the root element.
When assign css attribute, IE will active the element. So we can active the <html> element to be the wrapper, <body> to be the content,
CSS example:

#toolbar {position: fixed; bottom: 0; width: 100%;}
//css for ie6
* html{ overflow-y: hidden; } //hide the wrapper scroll
* html body{
  padding:0px;margin:0px; // reset
  overflow-y: auto; //set scroll
  height: 100%;
}
* html div#toolbar
{
  position: absolute;
  width:98%; //fix the problem that toolbar over scroll
}


Show me the Browser

Dear Candidate,
We front-end engineers are always busy at switching between browsers. Each engineer has three browsers installed on their notebook. They are Internet Explorer 6, Internet Explorer 7, and Firefox 3. It's really confusing to identify which browser is using. As an engineer with some repute, you want facilitate others by showing icon.

Ans:


1. we need to set CSS sprite for browser picture
I try to build CSS class with background-position attribute:
.firefox{ background-position:0 0 }
.ie7{ background-position:0 -75px }
.ie6{ background-position:0 -150px}
2. JavaScript to detect browser and parse userAgent string and replace picture for right browser.
using library from here: http://www.quirksmode.org/js/detect.html

window.onload = function(){
  // get the DOM object by ID
  var browserPic = document.getElementById("browsers");
  //detect browser and set correct class
  if(BrowserDetect.browser == "Firefox"){
    browserPic.className = "firefox";
  }
  if(BrowserDetect.browser == "Explorer"){
    if(BrowserDetect.version == "6")
      browserPic.className = "ie6";
    if(BrowserDetect.version == "7")
      browserPic.className = "ie7";
  }
};
(but it turn outs that using css hack * for ie6, _ for firefox is a far more simpler solution)

[.Note]jquery動態調整欄寬&限制checkbox選取

幾個專案上遇到的小需求,
皆用JQuery來解決,在這裡記錄一下解法

1.動態調整欄寬 :


有一個table,他的第一個欄位長度是固定的,後面的欄位要有相等的寬度,
但是後面的欄位數目是動態產生,欄位的名稱長度也不固定,如果欄位過長則必須要換行

一開始是用%數的方法來指定欄寬長度,但是這個方法並不能夠有效的在所有瀏覽器上運行
後來使用jquery來動態調整欄寬 : 先等table產生,再計算出後面欄位的平均寬度,並將儲存格寬度調整為平均寬度:

$('.sort').each(function() {
    var sum = 0;
    //取得所有要調整的欄寬
    var cells = $(this).find('.sort-item');
    //統計總寬度
    cells.each(function() {
        sum += $(this).width();
    });
    //設定平均欄寬 
    var cellWidth = sum / cells.length;
    cells.each(function() {
        $(this).width(cellWidth);
    });
});

2.限制checkbox選取


有一個多選的CheckboxList,需要限制最大的選取數量
如果超過則不能選擇:

//傳入CheckboxList Container的ID
bindMultiSelectLimit = function(id,limit) {
    $('#' + id + ' input:checkbox').click(function() {
        //使用Jquery selector直接找出所有已選之Checkbox
        if ($('#' + id + ' input:checked').length > limit) {
            return false;
        }
    });
};

3.限制排序問題重覆選取


有一個問卷題型叫排序題,結構上是由許多RadioButtonGroup所構成,
讓使用者能排列喜好選項的順序 : (ex, 有三個選項, 可以選擇 3,2,1 或 1,2,3的排序 )
但使用者希望能夠有防呆機制,讓已經於其他選項選過的排序不能再選第二次
(ex:三個選項的排序可為 1,2,3. 3,2,1 . 但不可為 2,2,1 )
後來選擇了一個比較簡單的作法:當排序被選取時,清空其他有同樣排序值的RadioButton

//傳入ContainerID
bindSortRules = function(id) {
    $('#' + id + ' input').click(function() {
    //設定每個排序RadioButton有同樣的value,將其他有相同value的值都設為false
    $('#' + id + ' input[value=' + $(this).val() + ']').attr('checked', false);
        //設定目前選擇的值
        $(this).attr('checked', true);
    });
}

以上的需求如果使用Javascript不知道要做多久...
所以說JQuery真的是能夠有效增加前端生產力的一個好框架啊,
只要有用到Web的開發者真的都需要接觸一下

[Html5Rocks!] 最好的Html5學習以及參考網頁



今天google code blog上釋出了一個html 5的推廣網頁

包含了互動式的slide show, 可以測試新功能的 html5 playground , 還有教學.

這可以說是接觸html5最好的網站了

它把html5定義為 html5 + new JSapi + CSS3 這一套完整的技術
看得出來google在推動新的網路技術上付出很多心血

原本html5預估要十年才能夠普及,但是由於新一代的瀏覽器以及mobile browser,ipad/phone對html5的支援,
越來越多的人開始注意到html5的可能性了

現在看來只有微軟還在拖慢Web技術的發展,
趕快想辦法解決一下你們的ie6...
弄個像chrome frame一樣的windows update啦

更多參考:
html5Demo
html5gallery
47-amazing-css3-animation-demo
7個簡單易學的特效範例