-
Notifications
You must be signed in to change notification settings - Fork 24
/
html_write.pl
1744 lines (1529 loc) · 47.6 KB
/
html_write.pl
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Part of SWI-Prolog
Author: Jan Wielemaker and Anjo Anjewierden
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2002-2023, University of Amsterdam
VU University Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(html_write,
[ reply_html_page/2, % :Head, :Body
reply_html_page/3, % +Style, :Head, :Body
reply_html_partial/1, % +HTML
% Basic output routines
page//1, % :Content
page//2, % :Head, :Body
page//3, % +Style, :Head, :Body
html//1, % :Content
% Option processing
html_set_options/1, % +OptionList
html_current_option/1, % ?Option
% repositioning HTML elements
html_post//2, % +Id, :Content
html_receive//1, % +Id
html_receive//2, % +Id, :Handler
xhtml_ns//2, % +Id, +Value
html_root_attribute//2, % +Name, +Value
html/4, % {|html||quasi quotations|}
% Useful primitives for expanding
html_begin//1, % +EnvName[(Attribute...)]
html_end//1, % +EnvName
html_quoted//1, % +Text
html_quoted_attribute//1, % +Attribute
% Emitting the HTML code
print_html/1, % +List
print_html/2, % +Stream, +List
html_print_length/2, % +List, -Length
% Extension support
(html_meta)/1, % +Spec
op(1150, fx, html_meta)
]).
:- use_module(html_quasiquotations, [html/4]).
:- autoload(library(apply),[maplist/3,maplist/4]).
:- use_module(library(debug),[debug/3]).
:- autoload(library(error),
[must_be/2,domain_error/2,instantiation_error/1]).
:- autoload(library(lists),
[permutation/2,selectchk/3,append/3,select/4,list_to_set/2]).
:- autoload(library(option),[option/2]).
:- autoload(library(pairs),[group_pairs_by_key/2]).
:- autoload(library(sgml),[xml_quote_cdata/3,xml_quote_attribute/3]).
:- autoload(library(uri),[uri_encoded/3]).
:- autoload(library(url),[www_form_encode/2]).
:- if(exists_source(library(http/http_dispatch))).
:- autoload(library(http/http_dispatch), [http_location_by_id/2]).
:- endif.
% Quote output
:- set_prolog_flag(generate_debug_info, false).
:- meta_predicate
reply_html_page(+, :, :),
reply_html_page(:, :),
html(:, -, +),
page(:, -, +),
page(:, :, -, +),
pagehead(+, :, -, +),
pagebody(+, :, -, +),
html_receive(+, 3, -, +),
html_post(+, :, -, +).
:- multifile
expand//1, % +HTMLElement
expand_attribute_value//1, % +HTMLAttributeValue
html_header_hook/1. % +Style
/** <module> Write HTML text
Most code doesn't need to use this directly; instead use
library(http/http_server), which combines this library with the
typical HTTP libraries that most servers need.
The purpose of this library is to simplify writing HTML pages. Of
course, it is possible to use format/3 to write to the HTML stream
directly, but this is generally not very satisfactory:
* It is a lot of typing
* It does not guarantee proper HTML syntax. You have to deal
with HTML quoting, proper nesting and reasonable layout.
* It is hard to use satisfactory abstraction
This module tries to remedy these problems. The idea is to translate a
Prolog term into an HTML document. We use DCG for most of the
generation.
---++ International documents
The library supports the generation of international documents, but this
is currently limited to using UTF-8 encoded HTML or XHTML documents. It
is strongly recommended to use the following mime-type.
==
Content-type: text/html; charset=UTF-8
==
When generating XHTML documents, the output stream must be in UTF-8
encoding.
*/
/*******************************
* SETTINGS *
*******************************/
%! html_set_options(+Options) is det.
%
% Set options for the HTML output. Options are stored in prolog
% flags to ensure proper multi-threaded behaviour where setting an
% option is local to the thread and new threads start with the
% options from the parent thread. Defined options are:
%
% * dialect(Dialect)
% One of =html4=, =xhtml= or =html5= (default). For
% compatibility reasons, =html= is accepted as an
% alias for =html4=.
%
% * doctype(+DocType)
% Set the =|<|DOCTYPE|= DocType =|>|= line for page//1 and
% page//2.
%
% * content_type(+ContentType)
% Set the =|Content-type|= for reply_html_page/3
%
% Note that the doctype and content_type flags are covered by
% distinct prolog flags: =html4_doctype=, =xhtml_doctype= and
% =html5_doctype= and similar for the content type. The Dialect
% must be switched before doctype and content type.
html_set_options(Options) :-
must_be(list, Options),
set_options(Options).
set_options([]).
set_options([H|T]) :-
html_set_option(H),
set_options(T).
html_set_option(dialect(Dialect0)) :-
!,
must_be(oneof([html,html4,xhtml,html5]), Dialect0),
( html_version_alias(Dialect0, Dialect)
-> true
; Dialect = Dialect0
),
set_prolog_flag(html_dialect, Dialect).
html_set_option(doctype(Atom)) :-
!,
must_be(atom, Atom),
current_prolog_flag(html_dialect, Dialect),
dialect_doctype_flag(Dialect, Flag),
set_prolog_flag(Flag, Atom).
html_set_option(content_type(Atom)) :-
!,
must_be(atom, Atom),
current_prolog_flag(html_dialect, Dialect),
dialect_content_type_flag(Dialect, Flag),
set_prolog_flag(Flag, Atom).
html_set_option(O) :-
domain_error(html_option, O).
html_version_alias(html, html4).
%! html_current_option(?Option) is nondet.
%
% True if Option is an active option for the HTML generator.
html_current_option(dialect(Dialect)) :-
current_prolog_flag(html_dialect, Dialect).
html_current_option(doctype(DocType)) :-
current_prolog_flag(html_dialect, Dialect),
dialect_doctype_flag(Dialect, Flag),
current_prolog_flag(Flag, DocType).
html_current_option(content_type(ContentType)) :-
current_prolog_flag(html_dialect, Dialect),
dialect_content_type_flag(Dialect, Flag),
current_prolog_flag(Flag, ContentType).
dialect_doctype_flag(html4, html4_doctype).
dialect_doctype_flag(html5, html5_doctype).
dialect_doctype_flag(xhtml, xhtml_doctype).
dialect_content_type_flag(html4, html4_content_type).
dialect_content_type_flag(html5, html5_content_type).
dialect_content_type_flag(xhtml, xhtml_content_type).
option_default(html_dialect, html5).
option_default(html4_doctype,
'HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" \c
"http://www.w3.org/TR/html4/loose.dtd"').
option_default(html5_doctype,
'html').
option_default(xhtml_doctype,
'html PUBLIC "-//W3C//DTD XHTML 1.0 \c
Transitional//EN" \c
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"').
option_default(html4_content_type, 'text/html; charset=UTF-8').
option_default(html5_content_type, 'text/html; charset=UTF-8').
option_default(xhtml_content_type, 'application/xhtml+xml; charset=UTF-8').
%! init_options is det.
%
% Initialise the HTML processing options.
init_options :-
( option_default(Name, Value),
( current_prolog_flag(Name, _)
-> true
; create_prolog_flag(Name, Value, [])
),
fail
; true
).
:- init_options.
%! xml_header(-Header)
%
% First line of XHTML document. Added by print_html/1.
xml_header('<?xml version=\'1.0\' encoding=\'UTF-8\'?>').
%! ns(?Which, ?Atom)
%
% Namespace declarations
ns(xhtml, 'http://www.w3.org/1999/xhtml').
/*******************************
* PAGE *
*******************************/
%! page(+Content:dom)// is det.
%! page(+Head:dom, +Body:dom)// is det.
%
% Generate a page including the HTML =|<!DOCTYPE>|= header. The
% actual doctype is read from the option =doctype= as defined by
% html_set_options/1.
page(Content) -->
doctype,
html(html(Content)).
page(Head, Body) -->
page(default, Head, Body).
page(Style, Head, Body) -->
doctype,
content_type,
html_begin(html),
pagehead(Style, Head),
pagebody(Style, Body),
html_end(html).
%! doctype//
%
% Emit the =|<DOCTYPE ...|= header. The doctype comes from the
% option doctype(DOCTYPE) (see html_set_options/1). Setting the
% doctype to '' (empty atom) suppresses the header completely.
% This is to avoid a IE bug in processing AJAX output ...
doctype -->
{ html_current_option(doctype(DocType)),
DocType \== ''
},
!,
[ '<!DOCTYPE ', DocType, '>' ].
doctype -->
[].
content_type -->
{ html_current_option(content_type(Type))
},
!,
html_post(head, meta([ 'http-equiv'('content-type'),
content(Type)
], [])).
content_type -->
{ html_current_option(dialect(html5)) },
!,
html_post(head, meta('charset=UTF-8')).
content_type -->
[].
pagehead(_, Head) -->
{ functor(Head, head, _)
},
!,
html(Head).
pagehead(Style, Head) -->
{ strip_module(Head, M, _),
hook_module(M, HM, head//2)
},
HM:head(Style, Head),
!.
pagehead(_, Head) -->
{ strip_module(Head, M, _),
hook_module(M, HM, head//1)
},
HM:head(Head),
!.
pagehead(_, Head) -->
html(head(Head)).
pagebody(_, Body) -->
{ functor(Body, body, _)
},
!,
html(Body).
pagebody(Style, Body) -->
{ strip_module(Body, M, _),
hook_module(M, HM, body//2)
},
HM:body(Style, Body),
!.
pagebody(_, Body) -->
{ strip_module(Body, M, _),
hook_module(M, HM, body//1)
},
HM:body(Body),
!.
pagebody(_, Body) -->
html(body(Body)).
hook_module(M, M, PI) :-
current_predicate(M:PI),
!.
hook_module(_, user, PI) :-
current_predicate(user:PI).
%! html(+Content:dom)// is det
%
% Generate HTML from Content. Generates a token sequence for
% print_html/2.
html(Spec) -->
{ strip_module(Spec, M, T) },
qhtml(T, M).
qhtml(Var, _) -->
{ var(Var),
!,
instantiation_error(Var)
}.
qhtml([], _) -->
!,
[].
qhtml([H|T], M) -->
!,
html_expand(H, M),
qhtml(T, M).
qhtml(X, M) -->
html_expand(X, M).
html_expand(Var, _) -->
{ var(Var),
!,
instantiation_error(Var)
}.
html_expand(Term, Module) -->
do_expand(Term, Module),
!.
html_expand(Term, _Module) -->
{ print_message(error, html(expand_failed(Term))) }.
do_expand(Token, _) --> % call user hooks
expand(Token),
!.
do_expand(Fmt-Args, _) -->
!,
{ format(string(String), Fmt, Args)
},
html_quoted(String).
do_expand(\List, Module) -->
{ is_list(List)
},
!,
raw(List, Module).
do_expand(\Term, Module, In, Rest) :-
!,
call(Module:Term, In, Rest).
do_expand(Module:Term, _) -->
!,
qhtml(Term, Module).
do_expand(&(Entity), _) -->
!,
{ integer(Entity)
-> format(string(String), '&#~d;', [Entity])
; format(string(String), '&~w;', [Entity])
},
[ String ].
do_expand(Token, _) -->
{ atomic(Token)
},
!,
html_quoted(Token).
do_expand(element(Env, Attributes, Contents), M) -->
!,
( { Contents == [],
html_current_option(dialect(xhtml))
}
-> xhtml_empty(Env, Attributes)
; html_begin(Env, Attributes),
qhtml(Env, Contents, M),
html_end(Env)
).
do_expand(Term, M) -->
{ Term =.. [Env, Contents]
},
!,
( { layout(Env, _, empty)
}
-> html_begin(Env, Contents)
; ( { Contents == [],
html_current_option(dialect(xhtml))
}
-> xhtml_empty(Env, [])
; html_begin(Env),
qhtml(Env, Contents, M),
html_end(Env)
)
).
do_expand(Term, M) -->
{ Term =.. [Env, Attributes, Contents],
check_non_empty(Contents, Env, Term)
},
!,
( { Contents == [],
html_current_option(dialect(xhtml))
}
-> xhtml_empty(Env, Attributes)
; html_begin(Env, Attributes),
qhtml(Env, Contents, M),
html_end(Env)
).
qhtml(Env, Contents, M) -->
{ cdata_element(Env),
phrase(cdata(Contents, M), Tokens)
},
!,
[ cdata(Env, Tokens) ].
qhtml(_, Contents, M) -->
qhtml(Contents, M).
check_non_empty([], _, _) :- !.
check_non_empty(_, Tag, Term) :-
layout(Tag, _, empty),
!,
print_message(warning,
format('Using empty element with content: ~p', [Term])).
check_non_empty(_, _, _).
cdata(List, M) -->
{ is_list(List) },
!,
raw(List, M).
cdata(One, M) -->
raw_element(One, M).
%! raw(+List, +Module)// is det.
%
% Emit unquoted (raw) output used for scripts, etc.
raw([], _) -->
[].
raw([H|T], Module) -->
raw_element(H, Module),
raw(T, Module).
raw_element(Var, _) -->
{ var(Var),
!,
instantiation_error(Var)
}.
raw_element(\List, Module) -->
{ is_list(List)
},
!,
raw(List, Module).
raw_element(\Term, Module, In, Rest) :-
!,
call(Module:Term, In, Rest).
raw_element(Module:Term, _) -->
!,
raw_element(Term, Module).
raw_element(Fmt-Args, _) -->
!,
{ format(string(S), Fmt, Args) },
[S].
raw_element(Value, _) -->
{ must_be(atomic, Value) },
[Value].
%! html_begin(+Env)// is det.
%! html_end(+End)// is det
%
% For html_begin//1, Env is a term Env(Attributes); for
% html_end//1 it is the plain environment name. Used for
% exceptional cases. Normal applications use html//1. The
% following two fragments are identical, where we prefer the first
% as it is more concise and less error-prone.
%
% ==
% html(table(border=1, \table_content))
% ==
% ==
% html_begin(table(border=1)
% table_content,
% html_end(table)
% ==
html_begin(Env) -->
{ Env =.. [Name|Attributes]
},
html_begin(Name, Attributes).
html_begin(Env, Attributes) -->
pre_open(Env),
[<],
[Env],
attributes(Env, Attributes),
( { layout(Env, _, empty),
html_current_option(dialect(xhtml))
}
-> ['/>']
; [>]
),
post_open(Env).
html_end(Env) --> % empty element or omited close
{ layout(Env, _, -),
html_current_option(dialect(html))
; layout(Env, _, empty)
},
!,
[].
html_end(Env) -->
pre_close(Env),
['</'],
[Env],
['>'],
post_close(Env).
%! xhtml_empty(+Env, +Attributes)// is det.
%
% Emit element in xhtml mode with empty content.
xhtml_empty(Env, Attributes) -->
pre_open(Env),
[<],
[Env],
attributes(Attributes),
['/>'].
%! xhtml_ns(+Id, +Value)//
%
% Demand an xmlns:id=Value in the outer html tag. This uses the
% html_post/2 mechanism to post to the =xmlns= channel. Rdfa
% (http://www.w3.org/2006/07/SWD/RDFa/syntax/), embedding RDF in
% (x)html provides a typical usage scenario where we want to
% publish the required namespaces in the header. We can define:
%
% ==
% rdf_ns(Id) -->
% { rdf_global_id(Id:'', Value) },
% xhtml_ns(Id, Value).
% ==
%
% After which we can use rdf_ns//1 as a normal rule in html//1 to
% publish namespaces from library(semweb/rdf_db). Note that this
% macro only has effect if the dialect is set to =xhtml=. In
% =html= mode it is silently ignored.
%
% The required =xmlns= receiver is installed by html_begin//1
% using the =html= tag and thus is present in any document that
% opens the outer =html= environment through this library.
xhtml_ns(Id, Value) -->
{ html_current_option(dialect(xhtml)) },
!,
html_post(xmlns, \attribute(xmlns:Id=Value)).
xhtml_ns(_, _) -->
[].
%! html_root_attribute(+Name, +Value)//
%
% Add an attribute to the HTML root element of the page. For
% example:
%
% ==
% html(div(...)),
% html_root_attribute(lang, en),
% ...
% ==
html_root_attribute(Name, Value) -->
html_post(html_begin, \attribute(Name=Value)).
%! attributes(+Env, +Attributes)// is det.
%
% Emit attributes for Env. Adds XHTML namespace declaration to the
% html tag if not provided by the caller.
attributes(html, L) -->
!,
( { html_current_option(dialect(xhtml)) }
-> ( { option(xmlns(_), L) }
-> attributes(L)
; { ns(xhtml, NS) },
attributes([xmlns(NS)|L])
),
html_receive(xmlns)
; attributes(L),
html_noreceive(xmlns)
),
html_receive(html_begin).
attributes(_, L) -->
attributes(L).
attributes([]) -->
!,
[].
attributes([H|T]) -->
!,
attribute(H),
attributes(T).
attributes(One) -->
attribute(One).
attribute(Name=Value) -->
!,
[' '], name(Name), [ '="' ],
attribute_value(Value),
['"'].
attribute(NS:Term) -->
!,
{ Term =.. [Name, Value]
},
!,
attribute((NS:Name)=Value).
attribute(Term) -->
{ Term =.. [Name, Value]
},
!,
attribute(Name=Value).
attribute(Atom) --> % Value-abbreviated attribute
{ atom(Atom)
},
[ ' ', Atom ].
name(NS:Name) -->
!,
[NS, :, Name].
name(Name) -->
[ Name ].
%! attribute_value(+Value) is det.
%
% Print an attribute value. Value is either atomic or one of the
% following terms:
%
% * A+B
% Concatenation of A and B
% * encode(V)
% Emit URL-encoded version of V. See www_form_encode/2.
% * An option list
% Emit ?Name1=encode(Value1)&Name2=encode(Value2) ...
% * A term Format-Arguments
% Use format/3 and emit the result as quoted value.
%
% The hook html_write:expand_attribute_value//1 can be defined to
% provide additional `function like' translations. For example,
% http_dispatch.pl defines location_by_id(ID) to refer to a
% location on the current server based on the handler id. See
% http_location_by_id/2.
attribute_value(List) -->
{ is_list(List) },
!,
attribute_value_m(List).
attribute_value(Value) -->
attribute_value_s(Value).
% emit a single attribute value
attribute_value_s(Var) -->
{ var(Var),
!,
instantiation_error(Var)
}.
attribute_value_s(A+B) -->
!,
attribute_value(A),
( { is_list(B) }
-> ( { B == [] }
-> []
; [?], search_parameters(B)
)
; attribute_value(B)
).
attribute_value_s(encode(Value)) -->
!,
{ uri_encoded(query_value, Value, Encoded) },
[ Encoded ].
attribute_value_s(Value) -->
expand_attribute_value(Value),
!.
attribute_value_s(Fmt-Args) -->
!,
{ format(string(Value), Fmt, Args) },
html_quoted_attribute(Value).
attribute_value_s(Value) -->
html_quoted_attribute(Value).
search_parameters([H|T]) -->
search_parameter(H),
( {T == []}
-> []
; ['&'],
search_parameters(T)
).
search_parameter(Var) -->
{ var(Var),
!,
instantiation_error(Var)
}.
search_parameter(Name=Value) -->
{ www_form_encode(Value, Encoded) },
[Name, =, Encoded].
search_parameter(Term) -->
{ Term =.. [Name, Value],
!,
www_form_encode(Value, Encoded)
},
[Name, =, Encoded].
search_parameter(Term) -->
{ domain_error(search_parameter, Term)
}.
%! attribute_value_m(+List)//
%
% Used for multi-valued attributes, such as class-lists. E.g.,
%
% ==
% body(class([c1, c2]), Body)
% ==
%
% Emits =|<body class="c1 c2"> ...|=
attribute_value_m([]) -->
[].
attribute_value_m([H|T]) -->
attribute_value_s(H),
( { T == [] }
-> []
; [' '],
attribute_value_m(T)
).
/*******************************
* QUOTING RULES *
*******************************/
%! html_quoted(Text)// is det.
%
% Quote the value for normal (CDATA) text. Note that text
% appearing in the document structure is normally quoted using
% these rules. I.e. the following emits properly quoted bold text
% regardless of the content of Text:
%
% ==
% html(b(Text))
% ==
%
% @tbd Assumes UTF-8 encoding of the output.
html_quoted(Text) -->
{ xml_quote_cdata(Text, Quoted, utf8) },
[ Quoted ].
%! html_quoted_attribute(+Text)// is det.
%
% Quote the value according to the rules for tag-attributes
% included in double-quotes. Note that -like html_quoted//1-,
% attributed values printed through html//1 are quoted
% atomatically.
%
% @tbd Assumes UTF-8 encoding of the output.
html_quoted_attribute(Text) -->
{ xml_quote_attribute(Text, Quoted, utf8) },
[ Quoted ].
%! cdata_element(?Element)
%
% True when Element contains declared CDATA and thus only =|</|=
% needs to be escaped.
cdata_element(script).
cdata_element(style).
/*******************************
* REPOSITIONING HTML *
*******************************/
%! html_post(+Id, :HTML)// is det.
%
% Reposition HTML to the receiving Id. The html_post//2 call
% processes HTML using html//1. Embedded \-commands are executed
% by mailman/1 from print_html/1 or html_print_length/2. These
% commands are called in the calling context of the html_post//2
% call.
%
% A typical usage scenario is to get required CSS links in the
% document head in a reusable fashion. First, we define css//1 as:
%
% ==
% css(URL) -->
% html_post(css,
% link([ type('text/css'),
% rel('stylesheet'),
% href(URL)
% ])).
% ==
%
% Next we insert the _unique_ CSS links, in the pagehead using the
% following call to reply_html_page/2:
%
% ==
% reply_html_page([ title(...),
% \html_receive(css)
% ],
% ...)
% ==
html_post(Id, Content) -->
{ strip_module(Content, M, C) },
[ mailbox(Id, post(M, C)) ].
%! html_receive(+Id)// is det.
%
% Receive posted HTML tokens. Unique sequences of tokens posted
% with html_post//2 are inserted at the location where
% html_receive//1 appears.
%
% @see The local predicate sorted_html//1 handles the output of
% html_receive//1.
% @see html_receive//2 allows for post-processing the posted
% material.
html_receive(Id) -->
html_receive(Id, sorted_html).
%! html_receive(+Id, :Handler)// is det.
%
% This extended version of html_receive//1 causes Handler to be
% called to process all messages posted to the channal at the time
% output is generated. Handler is called as below, where
% `PostedTerms` is a list of Module:Term created from calls to
% html_post//2. Module is the context module of html_post and Term
% is the unmodified term. Members in `PostedTerms` are in the
% order posted and may contain duplicates.
%
% ==
% phrase(Handler, PostedTerms, HtmlTerms, Rest)
% ==
%
% Typically, Handler collects the posted terms, creating a term
% suitable for html//1 and finally calls html//1.
html_receive(Id, Handler) -->
{ strip_module(Handler, M, P) },
[ mailbox(Id, accept(M:P, _)) ].
%! html_noreceive(+Id)// is det.
%
% As html_receive//1, but discard posted messages.
html_noreceive(Id) -->
[ mailbox(Id, ignore(_,_)) ].
%! mailman(+Tokens) is det.
%
% Collect posted tokens and copy them into the receiving
% mailboxes. Mailboxes may produce output for each other, but not
% cyclic. The current scheme to resolve this is rather naive: It
% simply permutates the mailbox resolution order until it found a
% working one. Before that, it puts =head= and =script= boxes at
% the end.
mailman(Tokens) :-
( html_token(mailbox(_, accept(_, Accepted)), Tokens)
-> true
),
var(Accepted), % not yet executed
!,
mailboxes(Tokens, Boxes),
keysort(Boxes, Keyed),
group_pairs_by_key(Keyed, PerKey),
move_last(PerKey, script, PerKey1),
move_last(PerKey1, head, PerKey2),
( permutation(PerKey2, PerKeyPerm),
( mail_ids(PerKeyPerm)
-> !
; debug(html(mailman),
'Failed mail delivery order; retrying', []),
fail
)
-> true
; print_message(error, html(cyclic_mailboxes))
).
mailman(_).
move_last(Box0, Id, Box) :-
selectchk(Id-List, Box0, Box1),
!,
append(Box1, [Id-List], Box).
move_last(Box, _, Box).
%! html_token(?Token, +Tokens) is nondet.
%
% True if Token is a token in the token set. This is like member,
% but the toplevel list may contain cdata(Elem, Tokens).
html_token(Token, [H|T]) :-
html_token_(T, H, Token).
html_token_(_, Token, Token) :- !.
html_token_(_, cdata(_,Tokens), Token) :-
html_token(Token, Tokens).
html_token_([H|T], _, Token) :-
html_token_(T, H, Token).
%! mailboxes(+Tokens, -MailBoxes) is det.
%
% Get all mailboxes from the token set.
mailboxes(Tokens, MailBoxes) :-
mailboxes(Tokens, MailBoxes, []).
mailboxes([], List, List).
mailboxes([mailbox(Id, Value)|T0], [Id-Value|T], Tail) :-
!,
mailboxes(T0, T, Tail).
mailboxes([cdata(_Type, Tokens)|T0], Boxes, Tail) :-
!,