1 ! Copyright (C) 2008, 2009 Slava Pestov.
\r
2 ! See http://factorcode.org/license.txt for BSD license.
\r
3 USING: accessors sequences kernel assocs combinators
\r
4 validators http hashtables namespaces fry continuations locals
\r
5 io arrays math boxes splitting urls
\r
8 http.server.responses
\r
11 furnace.conversations
\r
15 html.templates.chloe
\r
16 html.templates.chloe.syntax
\r
17 html.templates.chloe.compiler ;
\r
24 TUPLE: action rest init authorize display validate submit ;
\r
26 : new-action ( class -- action )
\r
27 new [ ] >>init [ ] >>validate [ ] >>authorize ; inline
\r
29 : <action> ( -- action )
\r
32 : merge-forms ( form -- )
\r
34 [ [ errors>> ] bi@ push-all ]
\r
35 [ [ values>> ] bi@ swap update ]
\r
36 [ swap validation-failed>> >>validation-failed drop ]
\r
39 : set-nested-form ( form name -- )
\r
43 unclip [ set-nested-form ] nest-form
\r
46 : restore-validation-errors ( -- )
\r
48 nested-forms cget set-nested-form
\r
51 : handle-get ( action -- response )
\r
55 [ init>> call( -- ) ]
\r
56 [ authorize>> call( -- ) ]
\r
57 [ drop restore-validation-errors ]
\r
58 [ display>> call( -- response ) ]
\r
61 ] with-exit-continuation ;
\r
63 : param ( name -- value )
\r
66 CONSTANT: revalidate-url-key "__u"
\r
68 : revalidate-url ( -- url/f )
\r
69 revalidate-url-key param
\r
70 dup [ >url ensure-port [ same-host? ] keep and ] when ;
\r
72 : validation-failed ( -- * )
\r
73 post-request? revalidate-url and [
\r
75 nested-forms-key param " " split harvest nested-forms cset
\r
77 <continue-conversation>
\r
81 : handle-post ( action -- response )
\r
84 [ validate>> call( -- ) ]
\r
85 [ authorize>> call( -- ) ]
\r
86 [ submit>> call( -- response ) ]
\r
89 ] with-exit-continuation ;
\r
91 : handle-rest ( path action -- assoc )
\r
92 rest>> dup [ [ "/" join ] dip associate ] [ 2drop f ] if ;
\r
94 : init-action ( path action -- )
\r
97 request get request-params assoc-union params set ;
\r
99 M: action call-responder* ( path action -- response )
\r
100 [ init-action ] keep
\r
101 request get method>> {
\r
102 { "GET" [ handle-get ] }
\r
103 { "HEAD" [ handle-get ] }
\r
104 { "POST" [ handle-post ] }
\r
107 M: action modify-form
\r
108 drop url get revalidate-url-key hidden-form-field ;
\r
110 : check-validation ( -- )
\r
111 validation-failed? [ validation-failed ] when ;
\r
113 : validate-params ( validators -- )
\r
114 params get swap validate-values check-validation ;
\r
116 : validate-integer-id ( -- )
\r
117 { { "id" [ v-number ] } } validate-params ;
\r
119 TUPLE: page-action < action template ;
\r
121 : <chloe-content> ( path -- response )
\r
122 resolve-template-path <chloe> "text/html" <content> ;
\r
124 : <page-action> ( -- page )
\r
125 page-action new-action
\r
126 dup '[ _ template>> <chloe-content> ] >>display ;
\r