niedziela, 27 listopada 2011

Notatki o Windows 8 - odc.4

W tym wpisie pierwsza część o kontrolkach HTML5 dla aplikacji Metro.

There are two types of controls: intrinsic HTML controls and Windows Library for JavaScript controls.

Kontrolki HTML

When you use an HTML control in your Metro style app using JavaScript you automatically get enhanced touch interaction and feedback. You also get additional state information that you can use to create a customized touch experience. When you use the Windows Library for JavaScript style sheets, your HTML controls also get the enhanced Windows Developer Preview look and feel (which you can override with your own Cascading Style Sheets (CSS) styles, if you want).

<label for="list1">Select an option:</label>

There are two ways to register an event handler:

  • To add an event handler in markup (declaratively)
  • To add an event handler in code-behind (programmaticall, the preferred approach)

function button1Click(mouseEventInfo)

{

    var button1Output = document.getElementById("button1Output");

    button1Output.innerHTML =

        mouseEventInfo.type

        + ": (" + mouseEventInfo.clientX + "," + mouseEventInfo.clientY + ")"; 

} 

 

document.addEventListener("DOMContentLoaded", function(e) {

  

    var button1 = document.getElementById("button1");

    button1.addEventListener("click", button1Click, false);  

});

You can add event handlers in your markup, but in some ways it can be more complicated that adding them with the addEventListener method because of scoping issues.

<button id="button1" onclick="button1Click(event)">An HTML Button</button>

When you run the app and click the button, nothing happens. That's because the button1Click function is wrapped in an anonymous function and isn't directly accessible to your markup. For your code to work, you'd need to move button1Click outside the anonymous function.

But now button1Click is global. Also, the event information passed to the handler isn't as useful: when you use addEventListener to attach the event, the mouseEventInfo.target property would return a reference to the button. When you set the event handler in markup, the target is the window object. For these reasons (and more), it's better to use addEventListener to attach event handlers.

You can't use JavaScript URIs in your event handler. For example, you can't do this:

<button id="button1" onclick="javascript: 2 + 2;">An HTML Button</button>

This restriction applies to code in the app's local context (code included in your app package), but does not apply to code on external web pages accessed by your app.

In a traditional HTML website, controls and other input elements are usually contained in a form element. form elements are used to pass data to the server. Because most Metro style app using JavaScript programming is client based, you don't usually need to use a form element.

Kontrolki WinJS

The Windows Library for JavaScript provides useful controls that aren't a part of HTML5. It also includes two style sheets (one with a dark color scheme and one with a light) that give your app the look and feel of Windows Developer Preview.

AppBar, DatePicker, FlipView, Flyout (displays a message that requires user interaction, does not create a separate window, unlike a dialog box), ListView (grid or list layout), Rating, SemanticZoom, SettingsPane, TimePicker, Toggle, Tooltip (support rich content), ViewBox,

CSS: ui-light.css, ui-dark.css

JS: base.js, ui.js, binding.js, controls.js, res.js, animations.js, uicollections.js, wwaapp.js

To add a Windows Library for JavaScript control, you create a div element and use the data-win-control attribute to specify the type of control you want.

<div id="ratingControlHost" data-win-control="WinJS.UI.Rating" />

You must also call the WinJS.UI.processAll function in your JavaScript code. WinJS.UI.processAll parses your markup and instantiates any Windows Library for JavaScript controls it finds. It's best to call WinJS.UI.processAll in your DOMContentLoaded event handler or by using the WinJS.Utilities.ready function.

document.addEventListener("DOMContentLoaded", function (e) {

        WinJS.UI.processAll();

    });

Properties

Unlike HTML controls, Windows Library for JavaScript controls don't have dedicated element or attribute tags. Instead, you use the data-win-options attribute to set a property in markup. It takes a string that contains one or more property value pairs: data-win-options="{propertyName: propertyValue}"

data-win-options="{maxRating: 10, averageRating: 6}"

data-win-options="{current: '10:29 am', disabled:true}"

You can also set the properties of a Windows Library for JavaScript control programmatically. To access the control in code, call the WinJS.UI.getControl function to retrieve the control from its host element.

var control = WinJS.UI.getControl(document.getElementById("ratingControlHost"));

You might want to retrieve and manipulate the control as soon as it's available. Be aware that the WinJS.UI.processAll method is asynchronous.

WinJS.UI.processAll()

    .then(function () {

 

        var control = WinJS.UI.getControl(document.getElementById("ratingControlHost"));

        control.averageRating = 3;

    });

 

Just like with HTML controls, the preferred way to attach event listeners for a Windows Library for JavaScript control is to use the addEventListener function.

 

var control = WinJS.UI.getControl(document.getElementById("ratingControlHost"));

control.addEventListener("change", ratingChanged, false);

Creating WinJS control in code

var hostElement = document.getElementById("hostElement");

var ratingControl = new WinJS.UI.Rating(hostElement);

There's no need to call WinJS.UI.processAll—you only need to call WinJS.UI.processAll when you create a Windows Library for JavaScript control in markup.

Base styles, intrinsic HTML control styles, additional intrinsic HTML control classes, Windows Library for JS control styles (represent stylable parts), typography styles (f.e h1, dd, p), additional typography classes (don't correspond to any one HTML element).

Including the light or dark style sheet. Always include only one of these style sheets, because including both will just cause the last one that you include to override the first one. For apps that mostly display images or video, use the dark style sheet, and for apps that contain a lot of text, use the light style sheet. You can override any style in the default style sheet by creating your own style sheet and including it after the Windows Library for JavaScript style sheet.

You can style intrinsic controls (those controls that are part of the HTML5 standard, such as button, textarea, and select) just as you style them in a typical HTML page by using CSS.

input[type=text]

{

    width: 400px;

}

A typical control has several components, or sub-parts. For example, the text input control in the previous example has two parts: the text value and the clear button. Metro style apps using JavaScript provides CSS pseudo-elements that let you style the individual parts of many controls. The pseudo-element for the text input's value is -ms-value and the pseudo-element for the Clear button is -ms-clear.

image

To style a control part, use the syntax:  element selector::part name { /* Your styles here */ }

input[type=text]::-ms-clear {

    border: 2px solid orange

}

You can combine pseudo-element selectors with other selectors so that you target a control with a specific class name or ID. For example, to style the Clear button of a text input control that uses the "orangeButton" class , you create this style:

input[type=text].orangeButton::-ms-clear {

     border: 2px solid orange

}

The style sheet includes CSS classes that you can assign to intrinsic HTML controls to give them a different look and feel. For example, you can use the win-backbutton class to make a standard button look like a Back button.

<button class="win-backbutton"></button>

To style a Windows Library for JavaScript control, you override the Windows Library for JavaScript CSS classes for that control. The following example creates a style that hides the progress indicator of a ListView.

.win-listView .win-progress {

    display: none;

}

Some controls, such as ListView and FlipView, also support item templates.

The style sheet also contains CSS classes for typography that you can apply to any element that contains text.

<h1 class="win-title">win-title</h1>

Windows Library for JavaScript provides these typography classes: win-title, win-contentTitle, and win-contentSubtitle.

Kontrolki pod HTML5/JS:

Images

function loadImage(eventInfo) {

 

    var picker = new Windows.Storage.Pickers.FileOpenPicker();

    picker.fileTypeFilter.replaceAll([".jpg", ".bmp", ".gif", ".png"]);

    picker.pickSingleFileAsync().then(processResults, displayError);

}

Use the URL.createObjectURL method to create a Blob from the StorageFile.

function processResults(file) {

    var imageBlob = URL.createObjectURL(file);

    document.getElementById("imageControl").src = imageBlob;

    document.getElementById("imageInformation").innerText =

        "The src of the first image has been set to " + file.fileName;

}

Text

Single-line text input controls let users enter one line of text into your application. They include a clear button so users can quickly remove the contents they've typed, and a password reveal button if it's a password input control.

Single-line text input control has a type attribute that defines the nature of information that the user is expected to provide, and affects the layout of the touch keyboard’s keys as well as the validation. The following specialized input types are supported by the single-line text boxes provided by Windows Developer Preview: "Password", "Email", "URL", "Number", "Telephone Number". There is also a "Text" type for capturing generic text.

There are two kinds of multi-line text boxes: plain and rich.

image

When you use the "email " type, you get the following for free:

  • When users navigate to the text box, the touch keyboard appears with an email-specific key layout.
  • When users enter an invalid email format, a dialog appears to let them know.

By default, the Clear button only shows up when:

  1. Users set focus on the input control.
  2. At least one character is in the control. Placeholder text is not counted.
  3. The Clear button doesn't restrict the text entry area to less than 5em.

If you have special scenario where you want to completely hide it, you can add the following Cascading Style Sheets (CSS):

input[type="text"]::-ms-clear{

    display: none;

}

<input type="text" placeholder="Please use MM/DD/YYYY format">

If your backend doesn't allow a long input string, limit the input with a "maxlength" and let users know when they reach the limit with a validation popup.

DON'T use a <textarea> with a row height of 1 to create a single-line text box.

DON'T use a text box as a search box. You create a much better and more consistent experience when you use the Search charm instead. The Search charm provides a consistent searching experience that your app can plug into.

Text input with length restrictions. When capturing long spans of text where users are expected to keep their word count or character count below some maximum, you should use a plain text box.

When capturing text that will only be consumed, and not re-displayed at a later time to users, use a plaintext box. For example, a survey that will be sent to some server.

When capturing text that will eventually be re-displayed, you may use either plaintext or rich text boxes.

If the text is expected to be highly expressive, such as conveying the users’ opinion, and you want to allow users to express that partly by styling their text, then you should use a rich text box. Any time you use a rich text box, you should provide styling buttons. Example: forum posts, rich dokcuments editing (a blogging app or a word processor)

Buttons

Submit button. The submit button submits a form that the user has filled out to the server, or trigger an action. It is activated when the user presses the Enter key while the focus is on another control on the same form, except when that control is a button.

Reset button. The reset button clears all the fields of a form so that the user can start over again.

Normal button. The normal button triggers an action that is defined by the developer. It has the same default style as the reset button.

<input type="submit" value="Submit">

<button type="submit">Submit</button>

<button>Button Text</button>

Use Submit to send a user input to a server or perform an action (default), like a "next" button that saves the form data and goes to the next app page.

The <button> tag without any attribute acts as submit button if it is the first button inside a form. You should put <button type="button"> if you want a normal button.

Customize the Normal and Submit button with text or an image to make it clear to users what happens when they tap or click the button.

To do an AJAX submit of a form, use <input type="submit"> and override the form submit function so users can commit with by pressing the enter key regardless of where the focus is in the form.

Don’t change the Reset button text. The default text for reset button is "Reset", which is appropriate.

Don’t  swap the default styles of submit button and other buttons.

Don’t put too much stuff inside a button. Although between <button></button> technically developers can put any HTML inside, like a table or a checkbox, that will confuse end users. The content inside a button should be concise and easy to understand. It should not have anything more than a picture and a text string.

DatePicker

The DatePicker displays three controls for month, date, and year. These controls are easy to use with touch support, and they can be styled and configured in several different ways.

<div id="date></div>

     <script type="text/javascript">

           var dateDiv = document.getElementById("date");

           var datePicker = new WinJS.UI.DatePicker(dateDiv, {current: '2/20/2011'});

     </script>

</div>

You can format the date string in all the ways the JavaScript Date object allows.

You can use only the standard American English calendar in this release.

By default, the earliest year the user can select is the current year minus 100, and the latest year the user can select is the current year plus 100.

data-win-options="{minyear:'1900', maxYear: '2300'}"

You can modify behavior in your application by handling the the change event. This event is raised when the user changes a date, not when the date is changed programmatically.

datePicker.onchange = dateChangeHandler;

CSS classes:  win-datepicker, win-datepicker-date, win-datepicker-month, win-datepicker-year

<style id="text/css">

    [class="win-datepicker-year"] {background-color:LightBlue};

<style>

You can specify all three DatePicker controls by using CSS attribute selector prefix syntax (^=), which finds every attribute whose name starts with the specified string:

[class^="win-datepicker"] {color:red};

.win-datepicker-year { display:none; }

#date *.win-datepicker-date { display: none; }

If you want to display the month, day, and year controls vertically instead of horizontally, you can set the CSS attributes display and float on the controls:

[class^="win-datepicker"] {display: block; float: none};

You can conditionally display controls vertically, for example when the width of the screen falls below a specified limit.

@media all and (max-width:320px) {

        *[class^="win-datepicker"] {display: block;float:none;}

        }

};

You can use different styles for a specific DatePicker instance by specifying the <div> element associated with that instance. For example, if you have one DatePicker in a <div> that has an ID of "start-date" and another in a <div> that has an ID of "end-date," you can set different font colors for the start date and end date DatePickers as follows:

#start-date [class^="win-datepicker"] {color:red};

#end-date [class^="win-datepicker"] {color:blue};

TimePicker

The TimePicker displays three controls: one for the hour, one for the minute, and one to choose between AM and PM.

data-win-options="{current='11:00:00'}"

You can format the time string in all the ways the JavaScript Date object allows, except for UTC values.

data-win-options="{minuteIncrement:5}"

Select controls are similar to drop-downs or combo boxes. Users can select one or more options from a set of items with text labels. The Select control has two different modes of operations: flyout mode and inline mode.

Use flyout mode when you need to conserve on-screen space and when users select only one option at a time. Flyout mode Select controls show only the currently selected item.

Use inline mode when you want the options to be visible all the time or when users can select more than one option at a time. Inline mode Select controls are "always open"

To create a flyout mode Select control, add the <select> element without a size and multiple attribute. The following example creates a flyout Select control that contains two groups, each with three items to select from. Users can't select the group names.

<select>

    <optgroup label="Fruits">

        <option>Apples</option>

        <option>Bananas</option>

        <option>Grapes</option>

    </optgroup>

    <optgroup label="Vegetables">

        <option>Broccoli</option>

        <option>Carrots</option>

        <option>Eggplant</option>

    </optgroup>

</select>

To put the select control into inline mode, set the size attribute, or set the multiple attribute to enable multi-selection for inline mode. You should never use the multiple attribute without having first set the size attribute.

<select size="8" multiple>

    <optgroup label="Fruits">

        <option>Apples</option>

        <option>Bananas</option>

        <option>Grapes</option>

    </optgroup>

    <optgroup label="Vegetables">

        <option>Broccoli</option>

        <option>Carrots</option>

        <option>Eggplant</option>

    </optgroup>

</select>

Selection of simple items, and/or items of secondary importance: The select control should contain items that can be adequately represented using only text labels.

DON’T use the select control’s inline mode to display mode than 200 items. This will require users to tediously pan long distances. Instead, use the ListView.

Use the select control’s inline mode when the set of items is simple, but also of primary importance.

  • You should set the control’s height to display all of the items (rows) in the box at once. Avoid panning when using the inline mode.
  • If there are more than 10 items, you should use the select control in flyout mode.

If inline mode isn’t appropriate, but you have multi-selection needs, use a multi-selectable collection control such as the ListView.

Don't use the Select control for selection amongst visually rich items. The select control cannot support multiple lines of text, or images. If the set of selectable items are visually rich abstractions, you should use a ListView to display them more richly.

Slider

When users tap the thumb, the value is shown in a tooltip.

Tick marks show when the slider is not set to allow continuous, float-point granular input. Tick marks are always snap points that the thumb snaps to, but they may not represent all of the snap points. If the distance between two tick marks is less than 19px, one of them should be skipped for rendering. The default position is above the track in horizontal style and to the left of the track in vertical style. You can override the "display:none" CSS property to make them show up on the other side or both sides.

Use the horizontal style if the control is used to seek within media, like in a video app.

If the slider is put in a one-direction pannable page, you should try to avoid putting the slider in the same direction as panning, otherwise users may swipe along the slider and change its value when they are attempting to pan the page.

For vertical styles, the lower value should always be at the bottom of the slider, regardless of locale or page layout.

For horizontal styles, the lower value should be on the left side of the slider for left-to-right page layout, and on the right for right-to-left page layout. Horizontal volume sliders: the lower value should always be on the left side of the slider.

Don’t use a slider for binary settings. Use a toggle switch instead.

Toggle

Once users toggle the switch on, you should perform the action immediately, without further explicit user consent.

Use a checkbox in longer forms or pages when you expect the user to submit with a button. For example, if you need users to complete a registration form, use a checkbox.

Do not replace the words "ON" or "OFF" when it is not necessary to do so. Do not use a toggle switch with a long statement that doesn’t fit well with the switch metaphor.

Rating

You can specify the average rating, the maximum rating to allow, which icons are displayed for each rating, and the tool tip text for each rating.

data-win-options="{averageRating : 3.4, maxRating : 7}"

When the user picks a rating, it triggers the change event. You can obtain the user's rating by getting the value of the userRating property.

The control accepts floating point values and can show partial stars.

tentative - Preview the user rating as users interact with the control, by mouse hover, keyboard focus, mouse down, mouse drag, touch down, or touch drag

With the disabled style, the star color is the same as non-disabled style to let users know that they can enable the control for input, for example, after logging in. If you want to show a rating control that cannot be enabled, you can use class="win-small" to display a smaller style that saves you space and subtly discourages user interaction.

clear - Let users clear their ratings. By default, the control lets users clear their previous ratings by sliding their fingers from the right to the left side of the control and lifting (a tooltip explains this to users). You are responsible for deleting the rating value. You should not disable this capability.

Allow only whole star user ratings. While you can show fractional stars for average rating (2.5, 3.75), user ratings should be whole stars (1, 2, 3, 4, 5).

You can customize the tooltip to show more meaningful words for each star, like "excellent, "very good," or "not bad."

Show average rating and user rating at the same time. Whenever it's meaningful to your users, you should show them the average user rating as well as their rating.

  • Use an accompanying text string ("average: 3.5") for a ratings control set to show user rating.
  • Put two rating controls together, one set to show user rating, and one set to show average rating and no user input.

Don't change the default number of stars. The default is five stars, with 1 being the lowest or worst rating and 5 being the highest or best.

c.d.n

Brak komentarzy: