CL-HTTP Chapter 12: W3P Presentation System


Reference Manual | Prev: Chapter 11. Proxy Server | Next: Chapter 13. Dynamic Forms


Contents

  1. 12.1 Overview
  2. 12.2 Defining Presentation Types
  3. 12.3 Presenting Data
  4. 12.4 Accepting Input
  5. 12.5 Built-in Types
  6. 12.6 Custom Types
  7. 12.7 Form Presentation Type Library

12.1 Overview

W3P is an abstract, extensible Common Lisp system for manipulating input and output as CLOS objects, specifically tailored to the stateless model of interaction of the World Wide Web. It implements a subset of the LISP interface to the Common Lisp Interface Manager (CLIM), providing presentation types, presenters, and accepters that work over HTML views rather than window system views.

Once a CLOS class has been profiled with its essential parameters and visual attributes, input type-checking and output rendering can be performed automatically. Developers can use standard interface characteristics or define their own visual representations and input parsing routines. W3P facilitates simpler applications with less code duplication by providing a uniform abstraction for rendering and parsing objects.

The system was described in the paper A Presentation System for the World Wide Web (Mallery, Dynamic Objects Workshop, 1996).

W3P lives in the WWW-PRESENT package (nicknamed W3P) and uses only ANSI-COMMON-LISP. It exports presentation types, generic functions, views, macros, and conditions for comprehensive form-based interaction over HTTP.

The W3P documentation interface provides live interactive access to all functions, macros, presentation types, and conditions: W3P Overview | Functions & Macros | Presentation Functions | Presentation Types

12.2 Defining Presentation Types

A presentation type is a CLOS-based abstraction that describes how to present an object and how to accept input for it. Presentation types are defined with w3p:define-presentation-type, which establishes the type name, its parameters, options, and inheritance relationship to other types.

Syntax

(w3p:define-presentation-type name (parameters...)
  :inherit-from supertype
  :options ((option default) ...))

Type Specifiers

Presentation type specifiers follow the CLIM convention and take three forms:

name                              ; bare type name
(name parameters...)              ; parameterized type
((name parameters...) options...) ; type with options

Parameters constrain which objects satisfy the type (e.g., the low and high bounds of an integer type). Options control visual attributes and rendering preferences (e.g., whether to show a photo in a custom type).

Type Inheritance

Presentation types form a single-inheritance hierarchy rooted at t. The :inherit-from option specifies the supertype. Presentation methods are inherited: if no specific method is defined for a type, the method for the nearest ancestor is used. Use w3p:presentation-type-superior-p to test ancestry and w3p:presentation-subtypep to test subtype relationships.

Example

(w3p:define-presentation-type scientist ()
  :inherit-from t
  :options ((show-photo t)))

This defines a presentation type scientist that inherits from t, with an option show-photo that defaults to true.

12.3 Presenting Data

The w3p:present generic function renders a Lisp object according to its presentation type and the current view. The view determines the output format: w3p:+html-view+ generates HTML markup, while w3p:+textual-view+ generates plain text.

Key Functions

(w3p:present object type &key :stream :view)
Present object as type to stream using view. The presentation method for the type and view is invoked to perform the actual rendering.
(w3p:present-to-string object type &key :view)
Present object to a string and return it. Useful for generating markup fragments.

Defining Present Methods

Use w3p:define-presentation-method to define how a type is presented for a given view:

(w3p:define-presentation-method w3p:present
    (object (type scientist) stream (view w3p:html-view) &key)
  (when show-photo
    (html:image (scientist-photo-url object) "scientist photo"
                :stream stream)
    (html:break-line :stream stream))
  (html:with-rendition (:bold :stream stream)
    (write-string (scientist-name object) stream)))

Within the method body, presentation type options (like show-photo) are bound as lexical variables. The method body can use any HTML generation macros to produce its output.

Using Options to Control Rendering

;; Full rendering with photo
(w3p:present *frank* 'scientist :view w3p:+html-view+)

;; Suppress the photo via type option
(w3p:present *frank* '((scientist) :show-photo nil)
             :view w3p:+html-view+)

12.4 Accepting Input

The w3p:accept generic function serves two roles in the W3P system: parsing input values from strings and generating HTML form prompts. This dual role supports the stateless HTTP form model where form generation and form processing are separate request/response cycles.

Parsing Input

w3p:accept-from-string parses a string value according to a presentation type and returns the parsed object and the type. When the input does not satisfy the type, the condition w3p:input-not-of-required-type is signalled.

;; Parse an integer
(w3p:accept-from-string 'integer "27" :view w3p:+textual-view+)
=> 27
   INTEGER

;; Parse a bounded integer
(w3p:accept-from-string '(integer 0 10) "5" :view w3p:+textual-view+)
=> 5
   (INTEGER 0 10)

;; Input validation: 12 is out of range [0, 10]
(handler-case
    (w3p:accept-from-string '(integer 0 10) "12"
                            :view w3p:+textual-view+)
  (w3p:input-not-of-required-type ()
    (format nil "Value not in range 0-10")))
=> "Value not in range 0-10"

Generating Form Prompts

When w3p:accept is called with :present-p t, it generates an HTML form prompt instead of parsing input. This is used in response functions for url:http-computed-form URLs.

(w3p:accept '(integer 0 168)
            :present-p t
            :view w3p:+html-view+
            :default 50
            :prompt "Number of hours worked:"
            :prompt-mode :raw
            :display-default nil
            :query-identifier "HOURS-WORKED"
            :insert-default t
            :active-p t)

This produces an HTML text input field with the name HOURS-WORKED, a default value of 50, and a maximum length appropriate for the integer range. The :query-identifier is the form field name that appears in the submitted query alist.

Error Handling

Use w3p:handle-input-error to define specialized error handling for presentation types. The conditions w3p:input-not-of-required-type and w3p:parse-error are the primary error conditions signalled during input acceptance.

12.5 Built-in Types

W3P provides a comprehensive set of built-in presentation types that cover the common Lisp type hierarchy and web-specific data types. These types have built-in present methods for both HTML and textual views, and accept methods for parsing input.

Numeric Types

number
Any Common Lisp number.
integer — parameters: (low high)
An integer, optionally bounded. Generates a text field sized to the range.
fixnum — parameters: (low high)
A fixnum, optionally bounded.
float, short-float, double-float
Floating-point types with optional bounds.
rational, ratio
Rational and ratio types with optional bounds.
real — parameters: (low high)
Any real number, optionally bounded.
complex
Complex numbers.

String and Character Types

string
Any string. Accepts text input, presents as-is.
basic-string
A base string type.
bounded-string — parameters: (max-length)
A string with a maximum length constraint. Generates an appropriately sized text field.
character
A single character.

Symbol and Logical Types

boolean
True or false. Generates a checkbox in HTML view.
symbol
Any Lisp symbol.
keyword
A keyword symbol.
null
The null type.
expression, form
Arbitrary Lisp expressions, read from the input string.

Selection Types

member — parameters: (&rest elements)
One of a fixed set of elements. Generates a select menu or radio buttons.
member-alist
Member type backed by an association list of (label . value) pairs.
member-sequence
Member type backed by a sequence.
subset — parameters: (&rest elements)
A subset of a fixed set. Generates checkboxes in HTML view.
subset-alist, subset-completion, subset-sequences
Subset variants backed by different data structures.
completion
A string with completion against a set of possibilities.

Compound and Other Types

sequence, sequence-enumerated
Ordered sequences of a given element type.
or, and
Compound types combining other presentation types.
null-or-type
Either null or a value of the specified type.
token-or-type, type-or-string
Flexible types that accept either a token/string or a typed value.
pathname, existing-pathname
File pathnames, with the latter validating existence.

12.6 Custom Types

Defining a custom presentation type requires three steps:

  1. Define the type with w3p:define-presentation-type, specifying parameters, options, and inheritance.
  2. Define a present method for w3p:html-view (and optionally w3p:textual-view) to control how objects are rendered.
  3. Define presentation-typep and accept methods to control how input is validated and parsed.

Complete Example

;; 1. Define the class
(defclass scientist ()
  ((name :initarg :name :reader scientist-name)
   (photo-url :initarg :photo-url :reader scientist-photo-url)))

;; 2. Define the presentation type
(w3p:define-presentation-type scientist ()
  :inherit-from t
  :options ((show-photo t)))

;; 3. Define the presenter for HTML
(w3p:define-presentation-method w3p:present
    (object (type scientist) stream (view w3p:html-view) &key)
  (when show-photo
    (html:image (scientist-photo-url object)
                "scientist photo" :stream stream)
    (html:break-line :stream stream))
  (html:with-rendition (:bold :stream stream)
    (write-string (scientist-name object) stream)))

;; 4. Define the type predicate
(w3p:define-presentation-method w3p:presentation-typep
    (object (type scientist))
  (typep object 'scientist))

;; 5. Define the accepter
(w3p:define-presentation-method w3p:accept
    ((type scientist) stream (view w3p:textual-view) &key)
  (let ((name (w3p:read-token stream)))
    (or (find name *scientists* :key #'scientist-name
              :test #'string-equal)
        (w3p:input-not-of-required-type name type))))

Presentation Generic Functions

The following generic functions can be specialized by custom presentation types:

w3p:present
Render an object on a stream.
w3p:accept
Parse input from a stream (or generate an HTML prompt).
w3p:accept-present-default
Generate the default HTML form element for a type.
w3p:presentation-typep
Test whether an object satisfies the type.
w3p:presentation-subtypep
Test subtype relationships.
w3p:describe-presentation-type
Generate a human-readable description of the type.
w3p:handle-input-error
Handle errors during input acceptance.

Utility Macros

(w3p:with-presentation-type-decoded (name parameters options) type-spec &body body)
Destructure a presentation type specifier into its components.
(w3p:with-presentation-type-parameters (type-name type-spec) &body body)
Bind the parameters of a type specifier.
(w3p:with-presentation-type-options (type-name type-spec) &body body)
Bind the options of a type specifier.
(w3p:with-standard-html-prompt (type &key :stream :default :prompt) &body body)
Wrap body in a standard HTML prompt display.

12.7 Form Presentation Type Library

Beyond the built-in types of Section 12.5, W3P includes a library of form-oriented presentation types originally developed for Dynamic Forms and promoted into the foundational system. The library is defined in the WWW-PRESENT package (sources http:w3p;utils.lisp, geography.lisp, p-types.lisp, and p-methods.lisp) and loads with the server: applications can use these types without loading Dynamic Forms. Dynamic Forms re-exports every name, so df:-prefixed references continue to work.

This section documents each type's HTML-view behavior: the widget it renders through w3p:accept-present-default and how it parses the submitted value. The types also present and parse in the textual view; that behavior is documented with the Dynamic Forms text view (Section 13.9).

Strings and Text

string+, string-trim, string-trim-or-null
Text box. string-trim trims surrounding whitespace; the -or-null variant maps a blank answer to nil.
text-line, delimited-string
Text box; delimited-string takes an optional delimiter set (default (#\,)) and parses up to a delimiter.
text, multi-paragraph-text
Textarea accepting multi-line input.
keywords
Text box parsing a comma-separated list into a list of trimmed strings.
password, form-digest
Password input box (obscured entry), value handled as string-trim-or-null.
hidden
Hidden field carrying its default through the form round trip, armor-plated on the wire.

Numbers and Time

integer, integer+, float+
Sized text box; integer+ and float+ take optional low/high bounds enforced at parse time with range guidance on failure.
universal-time, iso-date, time-of-day
Pull-down composites (month/day/year, plus hour/minute/AM-PM for the time types), parsing to a universal time, a date universal time, or seconds after midnight. universal-time and iso-date take optional after/before bounds.
integer-universal-time, integer-date
Minute-granularity encodings; convert with w3p:integer-universal-time, w3p:ordinary-universal-time, and w3p:get-integer-universal-time.

Choices

one-of, multiple-choice, word
Exclusive choice from a set, built on completion: radio buttons or a pull-down menu.
some-of
Inclusive choice, built on subset-completion: checkboxes or a multi-select list; parses to a list of values.
multiple-choice-alist
Exclusive choice over an alist of (name value); presents the names, returns the value.
sequence-multiple-choice-alist, ranked-sequence-multiple-choice-alist and their alpha-char- variants
Inclusive and rank-ordered alist choices for surveys.
ranking-of
An ordered subset: each choice gets a row of rank radio buttons; parses to the chosen values sorted by rank, truncated to maximum-rankings.
multi-line-sequence
Textarea parsed line by line through an element presentation type.

Network and Location

email-address, server-email-address, host-name
Text boxes for addresses and host names.
state-keyword, state-abbreviation, country-iso-code and their -or-null variants; zipcode-or-null
Location types backed by the US state and ISO country tables in geography.lisp: pull-down menus of names that parse to canonical postal or ISO codes. country-iso-code takes a :format keyword (default :country).

Error Guidance

Parse failures explain themselves through w3p:describe-presentation-type: the library supplies per-type guidance (valid ranges, the available choices) and friendly pretty names (a failing one-of reports "not a valid choice", not "not a valid one-of"). Customize per type by specializing w3p:describe-presentation-type or the type's presentation-type-pretty-name.

One caveat inherited from CLIM: presentation-class inheritance does not thread type parameters. A method specialized on a supertype destructures the concrete type's parameters with the supertype's lambda list, so a subtype whose parameter defaults differ (for example, the alist types' value-key #'second) never receives them through inheritance. The library handles this with explicit-parameter delegation: a small method on the subtype that rebuilds the parent type specifier with the right parameters and delegates (see %alist-completion-type in http:w3p;p-methods.lisp). Follow the same idiom when a new type specializes a parameterized type's defaults.