summaryrefslogtreecommitdiff
path: root/forum/forum.ur
blob: 23bbbd5e45c0f0f981bf10db76bb8071ce2f64ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
(* Forum -- forum subapp
Copyright (C) 2013  Benjamin Barenblat <bbaren@mit.edu>

This file is a part of 6.947.

6.947 is is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

6.947 is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License along
with 6.947.  If not, see <http://www.gnu.org/licenses/>. *)

functor Make(Template : sig
    val generic : option string -> xbody -> page
end) = struct

open Styles

style entryList
style entryMetadata
style entryTitle
style entryBody
style voting

table entry : { Id : int,
		References : option int,
		Class : EntryClass.entryClass,
		Title : option string,
		Body : string,
		Author : Author.usernameOrAnonymous
	      } PRIMARY KEY Id
sequence entryIdS

table vote : { QuestionId : int,
	       Author : Author.username,
	       Value : Score.score
	     }
    CONSTRAINT OneVotePerEntry UNIQUE (QuestionId, Author),
    CONSTRAINT RefersToEntry FOREIGN KEY QuestionId REFERENCES entry(Id)

(* Like query1', but automatically dereferences the field *)
fun queryColumn [tab ::: Name] [field ::: Name] [state ::: Type]
		(q : sql_query [] [] [tab = [field = state]] [])
		(f : state -> state -> state)
		(initial : state)
    : transaction state =
    query q (fn row state => return (f row.tab.field state)) initial

fun unless [m ::: Type -> Type] (_ : monad m) (cond : bool) (computation : m {}) =
    if cond
    then return ()
    else computation

(* Sum all the votes on a single question. *)
fun getScore (questionId : int) : transaction Score.score =
    queryColumn (SELECT Vote.Value FROM vote
				   WHERE Vote.QuestionId = {[questionId]})
		Score.update
		Score.undecided

fun recordVote (value : Score.score) (entryId : int) _formData : transaction page =
    authorOpt <- Author.current;
    (* If the user didn't exist, the user should not have been allowed to vote
    in the first place. *)
    let val author = Author.nameError authorOpt
    in
	existingVote <- oneOrNoRows1 (SELECT Vote.Value FROM vote
							WHERE Vote.QuestionId = {[entryId]}
							  AND Vote.Author = {[author]});
	(* This mimics Reddit's upvote/downvote behavior, which is a bizarrely
	complex state machine that is nonetheless totally intuitive, especially
	when you're using an AJAXy interface.  TODO: Write an AJAXy
	interface. *)
	(case existingVote of
	     None => dml (INSERT INTO vote (QuestionId, Author, Value)
			  VALUES ({[entryId]}, {[author]}, {[value]}))
	   | Some v =>
	     if v.Value = value
	     then dml (DELETE FROM vote
		       WHERE QuestionId = {[entryId]}
			 AND Author = {[author]})
	     else dml (UPDATE vote
		       SET Value = {[value]}
		       WHERE QuestionId = {[entryId]}
			 AND Author = {[author]}));
	detail entryId
    end

and upvote entryId _formData = recordVote Score.insightful entryId _formData

and downvote entryId _formData = recordVote Score.inane entryId _formData



(***************************** Single questions ******************************)

and detail (id : int) : transaction page =
    authorOpt <- Author.current;
    question <- oneRow1 (SELECT * FROM entry
				  WHERE Entry.Class = {[EntryClass.question]}
				    AND Entry.Id = {[id]});
    score <- getScore id;
    answerBlock <- queryX1' (SELECT * FROM entry
				     WHERE Entry.Class = {[EntryClass.answer]}
				       AND Entry.References = {[Some id]})
			   (fn answer =>
	score <- getScore answer.Id;
	return (
            <xml><p>
	      {[answer.Body]}
	      <span class={entryMetadata}>&mdash;{[answer.Author]} ({[Score.withUnits score "point"]})</span>
	    </p></xml>));
    return (
        Template.generic (Some "Forum") <xml>
         <div class={content}>
           <h2>{[question.Title]}</h2>
           <p>{[question.Body]}</p>
           <p class={entryMetadata}>
	     Asked by {[question.Author]} ({[Score.withUnits score "point"]})
	   </p>
	   {Author.whenIdentified authorOpt
		<xml>
		  <form class={voting}><submit action={upvote id} value="⬆" /></form>
		  <form class={voting}><submit action={downvote id} value="⬇" /></form>
		</xml>}

	   <div>{answerBlock}</div>

           <h3>Your answer</h3>
           <form>
             <textarea {#Body} class={entryBody} /><br />
             Answering as:
             <select {#Author}>
	       {Author.whenIdentified' authorOpt (fn u => <xml><option>{[u]}</option></xml>)}
               <option>Anonymous</option>
             </select>
             <submit action={reply id} value="Answer" />
           </form>
         </div>
       </xml>)

and reply qId submission =
    id <- nextval entryIdS;
    dml (INSERT INTO entry (Id, References, Class, Title, Body, Author)
	 VALUES ({[id]},
	         {[Some qId]},
	         {[EntryClass.answer]},
	         {[None]},
	         {[submission.Body]},
                 {[readError submission.Author]}));
    detail qId


(**************************** Lists of questions *****************************)

fun prettyPrintQuestion entry : transaction xbody =
    score <- getScore entry.Id;
    return (
        <xml><li>
	  <h3><a link={detail entry.Id}>{[entry.Title]}</a></h3>
	  {[entry.Body]}
	  <span class={entryMetadata}>Asked by {[entry.Author]} ({[Score.withUnits score "point"]})</span>
	</li></xml>)

val allQuestions : transaction page =
    questionsList <- queryX1' (SELECT * FROM entry
					WHERE Entry.Class = {[EntryClass.question]}
					ORDER BY Entry.Id DESC)
			      prettyPrintQuestion;
    return (
        Template.generic (Some "Forum – All questions") <xml>
	  <div class={content}>
	    <h2>All questions</h2>
	    <ul class={entryList}>
	      {questionsList}
	    </ul>
	  </div>
	</xml>)

fun main () : transaction page =
    newestQuestions <- queryX1' (SELECT * FROM entry
					  WHERE Entry.Class = {[EntryClass.question]}
					  ORDER BY Entry.Id DESC
					  LIMIT 5)
				prettyPrintQuestion;
    askerOpt <- Author.current;
    return (
        Template.generic (Some "Forum") <xml>
	  <div class={content}>
	    <h2>Latest questions</h2>
	    <ul class={entryList}>
	      {newestQuestions}
	    </ul>
	    <a link={allQuestions}>View all questions</a>

	    <h2>Ask a new question</h2>
	    <form>
	      <textbox {#Title} placeholder="Title" class={entryTitle} /><br />
	      <textarea {#Body} class={entryBody} /><br />
	      Asking as:
	      <select {#Author}>
		{Author.whenIdentified' askerOpt (fn u =>
		     <xml><option>{[u]}</option></xml>)}
		<option>Anonymous</option>
	      </select>
	      <submit action={ask} value="Ask" />
	    </form>
	  </div>
	</xml>)

and ask submission =
    id <- nextval entryIdS;
    dml (INSERT INTO entry (Id, References, Class, Title, Body, Author)
	 VALUES ({[id]},
	         {[None]},
	         {[EntryClass.question]},
	         {[Some submission.Title]},
	         {[submission.Body]},
                 {[readError submission.Author]}));
    main ()

end