Let’s get started with the first of those topics: textual web apps and the advanced functionality of Apple’s WebKit.. In this chapter we’ll explore a wide variety of WebKit options, star
Trang 1Advanced WebKit and textual web apps
In the previous chapter we covered the fundamentals of redeveloping an existing web page for use on iPhones In the process you learned about important concepts like the viewport, and we discussed a lot of what works—and what doesn’t—on Apple’s unique mobile platform We expect, though, that most of you aren’t just interested in touching up existing web pages but instead are looking to create totally new programs Further, after considering the advantages and disadvantages
of both web and native development, you’ve decided that writing a new program using a web language is the best way to go We’re now ready to enter the world of web apps, a topic that will consume the rest of part 2 of this book
We’ve identified three ways to create web apps for the iPhone Each will take advantage of all your existing web knowledge, but each will also connect you with a specific library or Apple browser add-on that will allow you to unlock additional functionality on the iPhone platform
This chapter covers
■ Learning about the WebKit
■ Recognizing touch gestures
■ Recognizing orientation
Trang 2First, you might choose to build a textual web app, which is an application that is largely built on the fundamentals of HTML itself You’ll be able to supplement it with the advanced features of Apple’s WebKit We’ll be discussing this programming method in this chapter.
Second, you might choose to build an iPhone-UI web app, which is an application with a user interface that looks like iPhone’s native apps That will be the topic of chap-ter 5, where we’ll also cover iUI, a programming library meant to make this task easier Third, you might choose to build a graphical web app, which is an application that pushes the boundaries of web graphics That will be the topic of chapter 6, where our discussion will center on Canvas, a graphical add-on introduced by Apple several years ago that is now widely available
Let’s get started with the first of those topics: textual web apps and the advanced functionality of Apple’s WebKit In this chapter we’ll explore a wide variety of WebKit options, starting with simple HTML and CSS, and then build on that with advanced functionality such as transformations and databases We’ll conclude with some code that’s iPhone only
We touched on the WebKit in the previous chapter when we talked about the iPhone’s viewport command As we noted there, the WebKit is a browser engine that underlies several existing browsers It was originally derived from the Linux browser Konquerer, and is now in wider use on Unix-derived systems
It’s Apple who has brought the WebKit to the greatest prominence to date, and thus it should be no surprise that it’s Apple who is pushing hardest on new features for the WebKit It’s those new features that should excite you as iPhone developers, because they represent totally new functionality that you can use on the iPhone and that isn’t yet available on Internet Explorer or Firefox You’ll innately be making your web apps incompatible with those browsers if you start depending heavily on WebKit tricks, but
we figure that’s the point: using all the tricks you can to produce the best possible web apps for use largely or exclusively by the iPhone
As you’ll recall from chapter 3, there’s some information on the WebKit at Apple’s Web Apps site As of this writing, it’s pretty rudimentary, but we suspect it’ll improve with time Even now it has somewhat greater breadth than this chapter, covering some special functions that we don’t get to here
WebKit compatibility note
Although we’re highlighting the WebKit for the advanced functionality it offers to the Apple iPhone, you can make greater use of the features in this chapter that are not iPhone specific This includes new tags, various sorts of animation, and the client-side database Most notably, these features should work on Apple’s desktop Safari, the brand-new Google Android and Google Chrome platforms, and GNOME’s Epiphany browser Many of these features will become more accessible when they’re accepted into new HTML and CSS standards
Trang 3Introducing the WebKit
We’ll offer the warning that all of this functionality is very new Since some of the
functions are being offered for future HTML and CSS standards, they could change entirely Even now they’re not entirely consistent Over the course of writing this chap-ter we discovered one minor function (a transitioning rotation) that worked on Safari but not mobile Safari and a whole category of functionality (explicit animation) that worked on mobile Safari, but nowhere else We expect that by the time this book is published, behavior will be more consistent across versions of Safari, but our prime goal has been to document how things will work on the iPhone
4.1.1 New HTML elements
The WebKit introduces several new HTML elements We’ve listed the ones most likely
to be useful for iPhone design in table 4.1
There are also some variants of <pre> and some alternate ways to do embeds and ers, most of which are being deprecated in HTML 4.01
lay-4.1.2 New CSS elements
The bulk of the WebKit’s new functionality comes from its large set of extensions to the CSS standards These include the full set of transforms, transitions, and anima-tions that we cover separately later in this chapter, as well as some simpler CSS ele-ments that are summarized in table 4.2
Table 4.1 WebKit HTML elements give some new basic features for your iPhone web design.
<canvas> WebKit/JavaScript drawing object; discussed in chapter 6
<marquee>content</marquee> Sets content (which could be text or other object) as a
horizontally scrolling marquee
<meta name="viewport"> Metatag for the iPhone; discussed in chapter 3
Table 4.2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone designs
Background -webkit-background-size Controls the size of the background image Box -webkit-border-radius
-webkit-border-bottom-left-radius -webkit-border-bottom-right-radius -webkit-border-top-left-radius -webkit-border-top-right-radius
Sets the rounded corner radiuses of the box, in length units, either one corner at a time or all using one property.
Box -webkit-border-image Allows you to set an image as a box border
using a somewhat complex syntax, which is explained in Apple’s reference pages.
Trang 4Table 4.2 is not a complete listing, nor does it give
you all the details you need to use the properties
There are not only other CSS properties, but also
new CSS constants that can be applied to existing
properties Our main purpose is to show you the
cooler elements that are available among the
WebKit’s basic CSS elements, and to encourage
you to find out more information at Apple’s
WebApps reference site
Figure 4.1 shows how some of the new WebKit
CSS properties could be applied to a simple <div>
to create an attractive box that features rounded
corners and a three-dimensional back shadow
The <div> is simply defined with a new class
name, as is typical for CSS:
<div class="roundedbox">
The definition of the roundedbox class then
includes several standard CSS properties (to set
Box -webkit-box-shadow Sets a drop shadow for a box by
designat-ing a horizontal offset, a vertical offset, a blur radius, and a color.
Link -webkit-tap-highlight-color Overrides the standard highlight when a
user taps on a link on an iPhone.
Link -webkit-touch-callout Disables the touch-and-hold info box if set
to none Marquee -webkit-marquee-direction Controls the direction of the marquee,
which can go forward, left, right, up, reverse, or several other directions Marquee -webkit-marquee-increment Controls the distance the marquee moves,
in length units.
Marquee -webkit-marquee-repetition Limits the number of marquee repetitions Marquee -webkit-marquee-speed Sets marquee speed to fast, normal, or slow Text -webkit-text-fill-color
-webkit-text-stroke-color -webkit-text-stroke-width
Together allows you to differentiate between the interior and exterior of text by setting colors for each and by defining the stroke width using a length unit.
Text -webkit-text-size-adjust Adds a percentage to increase size of text
on the iPhone.
Table 4.2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone designs (continued)
Figure 4.1 New WebKit properties on the iPhone make your pages more attractive.
Trang 5CSS transforms, transitions, and animations
the background-color and so forth), plus the new border-radius and box-shadowproperties, which appear for the first time in Apple’s WebKit
The code to create the roundedbox class is shown in listing 4.1
All of the other new CSS properties could be used in a similar way
THE IPHONE-SPECIFIC PROPERTIES
Before we finish our discussion of the simpler WebKit CSS properties, we’d like to point out the ones specifically intended for the iPhone –webkit-tap-highlight-color and –webkit-touch-callout each give you some control over how links work
on the iPhone It’s the last iPhone-specific property, –webkit-text-size-adjust, that
is of particular note, because it allows you to increase point size by a percentage only
on the iPhone
In chapter 3, we talked a bit about adjusting font sizes through multiple CSS files
However, if that’s all you need to do differently between iPhones and desktop
brows-ers, you can do it with a single line in your CSS file:
4.2 CSS transforms, transitions, and animations
One of the most innovative elements of the WebKit is its ability to manipulate existing
HTML objects in various ways, allowing you to accomplish some fancy-looking work entirely in CSS You have three options: transformation (or static changes), transitions (or implicit animations), and animations (or explicit animations)
4.2.1 The transform function
Transforms allow you to apply various geometric functions to objects in a web page when they’re created There’s no animation here (yet), but you have considerable control over exactly what your HTML objects look like
Each transform is applied using a –webkit-transform CSS property:
-webkit-transform: rotate(30deg);
Several transforms are available, as shown in table 4.3
Listing 4.1 Using the new CSS web properties to create an attractive box
Trang 6The properties in table 4.3 are applied to boxes within CSS Much like relative tioning, they don’t affect layout, so you have to be careful with them
The following definition could be added to our roundedbox class from listing 4.1, turning it into a wackybox class:
-webkit-transform: rotate(30deg) translate(5%,5%);
The result is that your news article appears at an angle, moved somewhat off the screen Figure 4.2 shows this change, which you can compare to the nontransformed news article that appears a few pages back as figure 4.1 This particular transform isn’t that useful if you want people to read it, but it could be
a nice background for a news site or
something similar There are many other
things that you can do with transforms,
such as setting up banners, printing text
at a variety of sizes, and making similar
changes on static web pages Some will be
gimmicks, but others can have
func-tional benefits
Before we leave transforms behind,
we’ll note that they support one other
property, –webkit-transform-origin,
which can be used to move the origin for
scales and skews away from the center of
the object
Although you can do quite a bit with
transforms all on their own, their real
power appears when you start working
with the implicit animation of
transi-tions, which are the next WebKit
func-tion that we’re going to talk about
Table 4.3 The WebKit transforms apply to output elements in a variety of ways.
scale
scaleX
scaleY
Figure 4.2 Our roundedbox transformed into
a wackybox, which is rotated 30 degrees and
Trang 7To define a transition, you place the new –webkit-transition properties in the
CSS element that marks the end of your animation You can define what properties to
transition (possibly including all of them), how long the transition should last, and how the transition should work Then, when the block of text changes to the end-point class, a smooth and animated transition will occur Table 4.4 lists the various transition properties
Unfortunately, not all CSS properties can be transitioned Apple states that “any CSS
property which accepts values that are numbers, lengths, percentages or colors can be animated.” This isn’t entirely true, because some percentage-based elements such as font-size don’t yet work If you want to know whether a CSS property can be transi-tioned, you can find a list on the Apple website And there’s no harm if you list some-thing that doesn’t transition in a property; it just does an abrupt change instead You can reduce a transition command to a single line of code using the –webkit-transition shorthand property:
-webkit-transition: property duration timing-function delay
Separate additional transitions after the first with commas
Traditional websites are already making good use of transitions to highlight page elements when a hover occurs However, hovers aren’t possible on the iPhone, so it’s more likely that you’ll be making transitions based on a click Listing 4.2 shows a sim-ple transition of a box to color in the text and background (making it more visible) when you click it
div {
-webkit-transition: all 2s;
Table 4.4 Transitions let you animate changes of CSS properties.
timing-function
ease , linear , ease-in , ease-out , ease-in-out , or cubic-bezier (user-defined)
Defines the curve for how the mation occurs; ease was auto in previous versions of the iPhone OS -webkit-transition-
Trang 8<div class="clearbox" onclick="this.className='visiblebox'">
This simple transition could easily be built into a more sophisticated interface where a user could make individual elements of your page more or less visible by clicking on those individual elements (or alternatively through some pagewide control panel)
Seeing this simple example highlights why transitions are called implicit animation
You don’t have to do a thing other than define your endpoint styles and say what you want to animate between them In this example, your pages enjoy a nice animation from gray to cyan, with increasing opacity, thanks just to your defining two styles (and
a transition for all <div>s)
However, transitioning between normal styles is just the tip of the iceberg The coolest thing about transitions is that they can be used with that other new WebKit fea-ture we just discussed: transforms
TRANSITIONING TRANSFORMS
By putting together transforms and transitions, you can create actual graphical tions of scales, rotates, skews, and translations In other words, you can make boxes revolve, move, and otherwise change, showing off sophisticated graphical animations, with nothing but CSS definitions (and perhaps a bit of JavaScript to change the styles) Listing 4.3 shows how to put a transition and a transform together to create an ani-mated thumbnail program
<title>Thumbnail Viewer in WebKit</title>
<link href="thumbnail.css" type= "text/css" rel="stylesheet">
<meta name="viewport" content = "width = 480">
<script type="application/x-javascript">
Listing 4.3 Scaling a picture to create thumbnails
B
C
Trang 9We’ll also offer a brief aside on that rotate: for the moment the rotate animationworks on Safari, but not on mobile Safari, which is why you don’t see the thumbnail twisting in figure 4.3 As we’ve already explained, we expect the platforms will eventu-ally sync, perhaps by the time this book sees print, but we offer this as a further caveat.
D
E F
G
Figure 4.3 A thumbnail (left) is animated by a tap (middle), turning it into a full-page picture (right).
Trang 10In any case, what’s the end result of our work? As long as you’re on a setup where you don’t mind loading larger pictures, you can thumbnail easily More importantly, you can see how easy it is to use attractive implicit animations to scale thumbnails on your iPhone by combining the transition and transform properties.
4.2.3 The animation function
Transitions support fully featured animations, within the constraints of the CSS erties and the transform abilities So, how can the WebKit’s “explicit” animation improve
prop-on that? The answer is by giving you better cprop-ontrol over how the animatiprop-on works Listing 4.4 shows an example of animation in use
is the name for the animation; -webkit-animation-duration D, which is the length
of the animation, and –webkit-animation-iteration-count E, which is the number
of times to repeat the animation
The animation itself is defined by a @-webkit-keyframes entry F, where the name matches the name you already set You can define as many frames as you want, setting whatever CSS properties you desire in each frame Then when the anima- tion occurs, the WebKit will automatically transition among all the individual points Unlike transitions, an animation will return to its start point when it’s done, possi- bly iterating
Listing 4.4 Using animation keyframes
B
C D E F
Trang 11The WebKit database
To apply an animation, you just set a box to use the class If you do this in your ular HTML code, the animation will begin the instant your web page loads Alterna-tively, you can change a class name to the animated class when a button click or some other event occurs For example, if a button in your application requires a double-click, you could start the button shivering when it’s clicked the first time to encourage
reg-a second click
Our simple example here just takes a box and shoves it down toward the bottom of the screen, making it disappear as it goes You could use similar functionality to delete items from a page as a user interacts with it
The transformations, transitions, and animations are all impressive when put into use However, there’s one more WebKit function that’s broadly available on WebKit browsers that we think is even more impressive—and more likely to be useful in your own web apps: the client-side database
WebKit includes a client-side database built on SQLite This means that you can save much larger amounts on information on your client’s machine—which could be an iPhone—than was possible using traditional cookies This is all done through a set of new JavaScript routines
4.3.1 Loading a database
A table is loaded into your JavaScript through the openDatabase command:
var mydb = openDatabase(databaseName,version,displayName,maxSize);
databaseName and displayName are both arbitrary names that you’ll select for an vidual database version should currently be set to 1.0, and maxSize is a maximum size for your database in bytes (such as 65536) Here’s a typical command for opening
indi-a dindi-atindi-abindi-ase:
var mydb = openDatabase(prefData,'1.0','Preference Data',65536);
If a database doesn’t exist, the open command will automatically create it However, this command won’t actually create tables in the database, which you must do by hand
4.3.2 Running a transaction
Activity is run through the database as transactions, which are atomic query units that succeed or fail as a unit Each transaction may contain one or more queries A com-plete transaction looks like this:
Trang 12The actual query is done in SQL You can find good information at www.sqlite.org on the SQL syntax currently supported Use this site as a reference if you’re unfamiliar with the language.
Each of the four handler arguments, marked with an *, is optional, meaning that the simplest call to a transaction just sends the SQL and any arguments The first two handlers are for individual queries, and the last two handlers are for the transaction as
a whole They each refer to a different function that accepts one or more arguments,
as shown in table 4.5
results and error are both fully featured JavaScript objects that give you access to a number of properties and let you know how your SQL query affected your database The most important ones are listed in table 4.6
The underlying functionality of the JavaScript database is quite simple—presuming you already know SQL Thus the question becomes: how can you use it?
4.3.3 A sample database
A client-side database will have any number of advantages, all of which you can make use of on the iPhone However, there’s one iPhone-specific trick you should consider: iPhones uniquely might be connected to either a fast network (wireless) or a slow net-work (EDGE or 3G) So why not give your users the ability to offload their networked
Table 4.5 Error and data handlers tell you what SQLite is doing.
dataHandler transaction , results Parses results of successful query
errorHandler transaction , error Shows query errors
transactionError error Runs if anything in transaction failed transactionSuccess N/A Runs if everything in transaction succeeded
Table 4.6 error and results give you access to SQL responses.
results.rows.length Number of rows of responses
results.rows.item(i)['name'] Result from column 'name' of row i of your response results.rowsAffected Number of rows affected by an UPDATE or DELETE results.insertId ID of last INSERT operation