95 lines
2.2 KiB
Common Lisp
95 lines
2.2 KiB
Common Lisp
;;;; cl-scopes/web/dom - "Data Output Method" = simple and dedicated HTML generator
|
|
|
|
(defpackage :scopes/web/dom
|
|
(:use :common-lisp)
|
|
(:local-nicknames (:util :scopes/util)
|
|
(:alx :alexandria))
|
|
(:export #:elem #:element #:render
|
|
#:dlist))
|
|
|
|
(in-package :scopes/web/dom)
|
|
|
|
;;;; basic definitions
|
|
|
|
(defgeneric put (s)
|
|
(:method ((s string))
|
|
(put-string s)))
|
|
|
|
(defclass element ()
|
|
((tag :reader tag :initarg :tag)
|
|
(attrs :reader attrs :initarg :attrs)
|
|
(body :reader body :initarg :body)))
|
|
|
|
(defun elem (tag attrs body)
|
|
(make-instance 'element :tag (string-downcase tag)
|
|
:attrs attrs :body body))
|
|
|
|
(defun element (tag attrs &rest body)
|
|
(elem tag attrs body))
|
|
|
|
(defmethod print-object ((el element) stream)
|
|
(format stream "<~a ~s>~s" (tag el) (attrs el) (body el)))
|
|
|
|
(defmethod put ((el element))
|
|
(start (tag el) (attrs el))
|
|
(dolist (c (body el))
|
|
(put c))
|
|
(end (tag el)))
|
|
|
|
;;;; elements with specific functionality
|
|
|
|
(defun dlist (attrs plist)
|
|
(elem :dl attrs
|
|
(loop for (key val . r) on plist by #'cddr append
|
|
(cons (element :dt nil (string-downcase key)) (dds nil val)))))
|
|
|
|
(defun dds (attrs cont)
|
|
(if (atom cont)
|
|
(list (element :dd attrs cont))
|
|
(mapcar #'(lambda (x) (element :dd nil x)) cont)))
|
|
|
|
;;;; rendering
|
|
|
|
(defvar *output* (make-string-output-stream))
|
|
|
|
(defun render (&rest elems)
|
|
(let ((*output* (make-string-output-stream)))
|
|
(dolist (el elems)
|
|
(put el))
|
|
(get-output-stream-string *output*)))
|
|
|
|
(defun put-string (s)
|
|
(write-string s *output*))
|
|
|
|
(defun put-char (c)
|
|
(write-char c *output*))
|
|
|
|
(defun put-attrs (plist)
|
|
(loop for (key val . r) on plist by #'cddr do
|
|
(put-char #\Space)
|
|
(when val
|
|
(put-string (string-downcase key))
|
|
(when (not (eq val t))
|
|
(put-string "=\"")
|
|
(put-string (attr-str key val))
|
|
(put-char #\")))))
|
|
|
|
(defun attr-str (key val)
|
|
(case key
|
|
((:id :class) (util:to-string val :lower-case t))
|
|
(t (util:to-string val))))
|
|
|
|
(defun start (tag &optional attrs)
|
|
(put-char #\<)
|
|
(put-string tag)
|
|
(put-attrs attrs)
|
|
(put-char #\>))
|
|
|
|
(defun end (tag)
|
|
(put-string "</")
|
|
(put-string tag)
|
|
(put-char #\>))
|
|
|
|
(defun newline ()
|
|
(put-char #\Newline))
|
|
|