From c98d7e32295895290d4351d387a458f1c094aa69 Mon Sep 17 00:00:00 2001 From: Matthew Butterick Date: Wed, 13 Nov 2013 11:39:08 -0800 Subject: [PATCH] start of css math lib --- library/css/math.rkt | 45 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/library/css/math.rkt b/library/css/math.rkt index 52df91d..1890fde 100644 --- a/library/css/math.rkt +++ b/library/css/math.rkt @@ -1,21 +1,46 @@ #lang racket/base -(require "core.rkt") +(require "core.rkt" racket/match) + +(define/contract (css-unit? x) + (any/c . -> . boolean?) + (x . in? . '("%" "in" "cm" "mm" "em" "ex" "pt" "pc" "px" "rem"))) (struct cssq (num unit) #:methods gen:custom-write [(define write-proc (λ(x port mode) (display (format "~a~a" (cssq-num x) (cssq-unit x)) port)))]) -(define (string->cssq str) - (apply cssq - (let ([str (string-trim str "s" #:left? #f)]) - (regexp-split #px"(?<=[.\\d])(?=[A-Za-z])" str)))) +(define/contract (cssqish? x) + (any/c . -> . boolean?) + (->boolean (or (cssq? x) (cssqish->cssq x)))) + +(define/contract (string->unit x) + (string? . -> . css-unit?) + (if (css-unit? x) + x + (error 'string->unit "'~a' not a valid css unit" x))) + +(define (cssqish->cssq x) + (cond + [(cssq? x) x] + [else (begin + (define pieces (let* ([str (string-downcase x)] + [str (string-replace str " " "")] + [str (string-trim str "s" #:left? #f)]) + (string-split str #px"(?cssq (exn-message e)))]) + (list (string->number (first pieces)) + (string->unit (second pieces))))))])) +(define/contract (css-math-op op left right) + (procedure? cssqish? cssqish? . -> . cssq?) + (let ([left (cssqish->cssq left)] + [right (cssqish->cssq right)]) + (cssqish->cssq (format "~a~a" (apply op (list (cssq-num left) (cssq-num right)))(cssq-unit left))))) -(define (css+ left right) - (string->cssq (format "~a~a" (apply + (map string->number (list (cssq-num left) (cssq-num right))))(cssq-unit left)))) +(define-values (css+ css- css* css/) + (apply values (map (λ(op) (λ(left right) (css-math-op op left right))) (list + - * /)))) (module+ main - (define q1 (string->cssq "51.2rems")) - (define q2 (string->cssq "10rem")) - (css+ q1 q2)) \ No newline at end of file + (css+ "10rem" "5rem")) \ No newline at end of file