;;;; 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 #:render #:text #:rndr #:dl #:link)) (in-package :scopes/web/dom) ;;;; using classes... (defgeneric put (s) (:method ((s string)) (put-string s))) (defclass element () ((tag :reader tag :initarg :tag) (attrs :reader attrs :initarg :attrs) (content :reader content :initarg :content))) (defmethod print-object ((el element) stream) (format stream "<~a ~s>~s" (tag el) (attrs el) (content el))) (defmethod put ((el element)) (start (tag el) (attrs el)) (dolist (c (content el)) (put c)) (end (tag el))) (defun elem (tag attrs content) (make-instance 'element :tag tag :attrs attrs :content content)) ;;;; specific tags / elements (defun link (attrs &rest content) (elem "a" attrs content)) (defun dl (attrs plist) (elem "dl" attrs (loop for (key val . r) on plist by #'cddr append (cons (elem "dt" nil (list (string-downcase key))) (dds nil val))))) (defun dds (attrs body) (if (atom body) (list (dd nil body)) (mapcar #'(lambda (x) (dd nil x)) body ))) (defun dd (attrs &rest body) (elem "dd" attrs body)) ;;;; rendering (defvar *output* (make-string-output-stream)) (defun rndr (&rest elems) (let ((*output* (make-string-output-stream))) (dolist (el elems) (put el)) (get-output-stream-string *output*))) (defmacro render (&body body) `(let ((*output* (make-string-output-stream))) ,@body (get-output-stream-string *output*))) (defmacro element (tag attrs &body body) `(progn (start ,tag ,attrs) ,@body (end ,tag))) (defmacro text (s) `(put-string (string ,s))) (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)) (t (string val)))) (defun start (tag &optional attrs) (put-char #\<) (put-string tag) (put-attrs attrs) (put-char #\>)) (defun end (tag) (put-string ")) (defun newline () (put-char #\Newline)) ;;;; tag-specific renderers (defmacro xlink (attrs &rest body) `(element "a" ,attrs ,@body)) (defun xdl (attrs plist) (element "dl" attrs (loop for (key val . r) on plist by #'cddr do (element "dt" nil (put-string (string-downcase key))) (dd nil val)))) (defun xdd (attrs v) (if (atom v) (setf v (list v))) (dolist (el v) (element "dd" attrs (text el))))