Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e6d984d95 | ||
|
|
9af41447b7 | ||
|
|
f8b5902aa1 | ||
|
|
5f425adc1d | ||
|
|
b0bf2cb083 | ||
|
|
a5727a84fc | ||
|
|
817d7876db | ||
|
|
00034c0a26 | ||
|
|
907d759a23 | ||
|
|
7421f9c788 | ||
|
|
dc31b65be8 | ||
|
|
fa281124bb | ||
|
|
9491359b52 | ||
|
|
0ec4fd017f | ||
|
|
3df5c71d81 | ||
|
|
c697001736 | ||
|
|
6c28cfc1ec | ||
|
|
8702723e01 |
No files matched your search
@@ -254,3 +254,7 @@ paket-files/
|
||||
|
||||
# Ionide VSCode extension
|
||||
.ionide
|
||||
|
||||
# in-progress: PHP version
|
||||
src/app/vendor
|
||||
**/.env
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
#!/snap/bin/pwsh
|
||||
Set-Location src/MyPrayerJournal
|
||||
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false
|
||||
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false --nologo
|
||||
@@ -318,7 +318,9 @@ module Legal =
|
||||
|
||||
/// /api/request and /request(s) URLs
|
||||
module Request =
|
||||
|
||||
|
||||
open Cuid
|
||||
|
||||
// GET /request/[req-id]/edit
|
||||
let edit requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||
let returnTo =
|
||||
@@ -461,6 +463,7 @@ module Request =
|
||||
let now = ctx.Now ()
|
||||
let req =
|
||||
{ Request.empty with
|
||||
Id = Cuid.generate () |> RequestId
|
||||
UserId = userId
|
||||
EnteredOn = now
|
||||
ShowAfter = None
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<Version>3.1.0</Version>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Version>3.2</Version>
|
||||
<DebugType>embedded</DebugType>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<NoWarn>3391</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
@@ -17,14 +19,15 @@
|
||||
<Compile Include="Program.fs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FSharp.SystemTextJson" Version="0.19.13" />
|
||||
<PackageReference Include="FSharp.SystemTextJson" Version="1.1.23" />
|
||||
<PackageReference Include="FunctionalCuid" Version="1.0.0" />
|
||||
<PackageReference Include="Giraffe" Version="6.0.0" />
|
||||
<PackageReference Include="Giraffe.Htmx" Version="1.8.0" />
|
||||
<PackageReference Include="Giraffe.ViewEngine.Htmx" Version="1.8.0" />
|
||||
<PackageReference Include="LiteDB" Version="5.0.12" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.7" />
|
||||
<PackageReference Include="NodaTime" Version="3.1.0" />
|
||||
<PackageReference Include="Giraffe.Htmx" Version="1.9.2" />
|
||||
<PackageReference Include="Giraffe.ViewEngine.Htmx" Version="1.9.2" />
|
||||
<PackageReference Include="LiteDB" Version="5.0.16" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.5" />
|
||||
<PackageReference Include="NodaTime" Version="3.1.2" />
|
||||
<PackageReference Update="FSharp.Core" Version="7.0.300" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\" />
|
||||
|
||||
@@ -30,3 +30,13 @@ let noResults heading link buttonText text =
|
||||
/// Create a date with a span tag, displaying the relative date with the full date/time in the tooltip
|
||||
let relativeDate (date : Instant) now (tz : DateTimeZone) =
|
||||
span [ _title (date.InZone(tz).ToDateTimeOffset().ToString ("f", null)) ] [ Dates.formatDistance now date |> str ]
|
||||
|
||||
/// The version of myPrayerJournal
|
||||
let version =
|
||||
let v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version
|
||||
seq {
|
||||
string v.Major
|
||||
if v.Minor > 0 then
|
||||
$".{v.Minor}"
|
||||
if v.Revision > 0 then $".{v.Revision}"
|
||||
} |> Seq.reduce (+)
|
||||
@@ -95,7 +95,7 @@ let toaster =
|
||||
let htmlFoot =
|
||||
footer [ _class "container-fluid" ] [
|
||||
p [ _class "text-muted text-end" ] [
|
||||
str "myPrayerJournal v3.1"
|
||||
str $"myPrayerJournal {version}"
|
||||
br []
|
||||
em [] [
|
||||
small [] [
|
||||
|
||||
+1
-65
@@ -1,65 +1 @@
|
||||
<!DOCTYPE html><html lang="en"><head><script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-140352188-1"></script><script>window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'UA-140352188-1');</script><meta charSet="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta name="description" content="The CDN for htmx.org"/><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"/><meta name="timestamp" content="2022-07-30T20:48:48.149Z"/><link rel="shortcut icon" href="/favicon.ico"/><title>UNPKG - htmx.org</title><script>window.Promise || document.write('\x3Cscript src="/es6-promise@4.2.5/dist/es6-promise.min.js">\x3C/script>\x3Cscript>ES6Promise.polyfill()\x3C/script>')</script><script>window.fetch || document.write('\x3Cscript src="/whatwg-fetch@3.0.0/dist/fetch.umd.js">\x3C/script>')</script><script>window.__DATA__ = {"packageName":"htmx.org","packageVersion":"1.8.0","availableVersions":["0.0.1","0.0.2","0.0.3","0.0.4","0.0.5","0.0.6","0.0.7","0.0.8","0.1.0","0.1.1","0.1.2","0.2.0","0.3.0","0.4.0","0.4.1","1.0.0","1.0.1","1.0.2","1.1.0","1.2.0","1.2.1","1.3.0","1.3.1","1.3.2","1.3.3","1.4.0","1.4.1","1.5.0","1.6.0","1.6.1","1.7.0","1.8.0"],"filename":"/dist/htmx.min.js","target":{"path":"/dist/htmx.min.js","type":"file","details":{"contentType":"application/javascript","integrity":"sha384-cZuAZ+ZbwkNRnrKi05G/fjBX+azI9DNOkNYysZ0I/X5ZFgsmMiBXgDZof30F5ofc","language":"JavaScript","size":39433,"uri":null,"highlights":["(<span class=\"code-function\"><span class=\"code-keyword\">function</span>(<span class=\"code-params\">e,t</span>)</span>{<span class=\"code-keyword\">if</span>(<span class=\"code-keyword\">typeof</span> define===<span class=\"code-string\">\"function\"</span>&&define.amd){define([],t)}<span class=\"code-keyword\">else</span>{e.htmx=e.htmx||t()}})(<span class=\"code-keyword\">typeof</span> self!==<span class=\"code-string\">\"undefined\"</span>?self:<span class=\"code-keyword\">this</span>,<span class=\"code-function\"><span class=\"code-keyword\">function</span>(<span class=\"code-params\"></span>)</span>{<span class=\"code-keyword\">return</span> <span class=\"code-function\"><span class=\"code-keyword\">function</span>(<span class=\"code-params\"></span>)</span>{<span class=\"code-string\">\"use strict\"</span>;<span class=\"code-keyword\">var</span> U={<span class=\"code-attr\">onLoad</span>:t,<span class=\"code-attr\">process</span>:vt,<span class=\"code-attr\">on</span>:X,<span class=\"code-attr\">off</span>:F,<span class=\"code-attr\">trigger</span>:$,<span class=\"code-attr\">ajax</span>:nr,<span class=\"code-attr\">find</span>:R,<span class=\"code-attr\">findAll</span>:O,<span class=\"code-attr\">closest</span>:N,<span class=\"code-attr\">values</span>:<span class=\"code-function\"><span class=\"code-keyword\">function</span>(<span class=\"code-params\">e,t</span>)</span>{<span class=\"code-keyword\">var</span> r=Pt(e,t||<span class=\"code-string\">\"post\"</span>);<span class=\"code-keyword\">return</span> r.values},<span class=\"code-attr\">remove</span>:q,<span class=\"code-attr\">addClass</span>:L,<span class=\"code-attr\">removeClass</span>:T,<span class=\"code-attr\">toggleClass</span>:A,<span class=\"code-attr\">takeClass</span>:H,<span class=\"code-attr\">defineExtension</span>:fr,<span class=\"code-attr\">removeExtension</span>:cr,<span class=\"code-attr\">logAll</span>:C,<span class=\"code-attr\">logger</span>:<span class=\"code-literal\">null</span>,<span class=\"code-attr\">config</span>:{<span class=\"code-attr\">historyEnabled</span>:<span class=\"code-literal\">true</span>,<span class=\"code-attr\">historyCacheSize</span>:<span class=\"code-number\">10</span>,<span class=\"code-attr\">refreshOnHistoryMiss</span>:<span class=\"code-literal\">false</span>,<span class=\"code-attr\">defaultSwapStyle</span>:<span class=\"code-string\">\"innerHTML\"</span>,<span class=\"code-attr\">defaultSwapDelay</span>:<span class=\"code-number\">0</span>,<span class=\"code-attr\">defaultSettleDelay</span>:<span class=\"code-number\">20</span>,<span class=\"code-attr\">includeIndicatorStyles</span>:<span class=\"code-literal\">true</span>,<span class=\"code-attr\">indicatorClass</span>:<span class=\"code-string\">\"htmx-indicator\"</span>,<span class=\"code-attr\">requestClass</span>:<span class=\"code-string\">\"htmx-request\"</span>,<span class=\"code-attr\">addedClass</span>:<span class=\"code-string\">\"htmx-added\"</span>,<span class=\"code-attr\">settlingClass</span>:<span class=\"code-string\">\"htmx-settling\"</span>,<span class=\"code-attr\">swappingClass</span>:<span class=\"code-string\">\"htmx-swapping\"</span>,<span class=\"code-attr\">allowEval</span>:<span class=\"code-literal\">true</span>,<span class=\"code-attr\">inlineScriptNonce</span>:<span class=\"code-string\">\"\"</span>,<span class=\"code-attr\">attributesToSettle</span>:[<span class=\"code-string\">\"class\"</span>,<span class=\"code-string\">\"style\"</span>,<span class=\"code-string\">\"width\"</span>,<span class=\"code-string\">\"height\"</span>],<span class=\"code-attr\">withCredentials</span>:<span class=\"codLine truncated
|
||||
"default")?a["default"]:a}function D(a,b){return b={exports:{}},a(b,b.exports),b.exports}function J(a,b,e,c,d){for(var g in a)if(ua(a,g)){try{if("function"!==typeof a[g]){var r=Error((c||"React class")+": "+e+" type `"+g+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof a[g]+"`.");r.name="Invariant Violation";throw r;}var k=a[g](b,g,c,e,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(q){k=q}!k||k instanceof Error||K((c||"React class")+": type specification of "+
|
||||
e+" `"+g+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof k+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).");if(k instanceof Error&&!(k.message in L)){L[k.message]=!0;var B=d?d():"";K("Failed "+e+" type: "+k.message+(null!=B?B:""))}}}function G(){return null}function S(a){var b,e=a.children;a=a.css;return c.jsx("div",{css:w((b={border:"1px solid #dfe2e5",
|
||||
borderRadius:3},b["@media (max-width: 700px)"]={borderRightWidth:0,borderLeftWidth:0},b),a)},e)}function T(a){var b,e=a.children;a=a.css;return c.jsx("div",{css:w((b={padding:10,background:"#f6f8fa",color:"#424242",border:"1px solid #d1d5da",borderTopLeftRadius:3,borderTopRightRadius:3,margin:"-1px -1px 0",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between"},b["@media (max-width: 700px)"]={paddingRight:20,paddingLeft:20},b),a)},e)}function U(a){return a&&a.map(function(a,
|
||||
c){return t.createElement(a.tag,z({key:c},a.attr),U(a.child))})}function E(a){return function(b){return t.createElement(va,z({attr:z({},a.attr)},b),U(a.child))}}function va(a){var b=function(b){var c=a.size||b.size||"1em";if(b.className)var e=b.className;a.className&&(e=(e?e+" ":"")+a.className);var h=a.attr,r=a.title,k=["attr","title"],B={},q;for(q in a)Object.prototype.hasOwnProperty.call(a,q)&&0>k.indexOf(q)&&(B[q]=a[q]);if(null!=a&&"function"===typeof Object.getOwnPropertySymbols){var p=0;for(q=
|
||||
Object.getOwnPropertySymbols(a);p<q.length;p++)0>k.indexOf(q[p])&&(B[q[p]]=a[q[p]])}return t.createElement("svg",z({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},b.attr,h,B,{className:e,style:z({color:a.color||b.color},b.style,a.style),height:c,width:c,xmlns:"http://www.w3.org/2000/svg"}),r&&t.createElement("title",null,r),a.children)};return void 0!==V?t.createElement(V.Consumer,null,function(a){return b(a)}):b(W)}function F(a,b){var e=b.css;b=P(b,["css"]);return c.jsx(a,w({css:w({},
|
||||
e,{verticalAlign:"text-bottom"})},b))}function wa(a){return F(X,a)}function xa(a){return F(Y,a)}function ya(a){return F(Z,a)}function za(a){return F(aa,a)}function Aa(a){return F(ba,a)}function ca(a){var b=a.path,e=a.details,g=Object.keys(e).reduce(function(a,b){var c=a.subdirs,g=a.files;b=e[b];"directory"===b.type?c.push(b):"file"===b.type&&g.push(b);return a},{subdirs:[],files:[]});a=g.subdirs;g=g.files;a.sort(da("path"));g.sort(da("path"));var d=[];"/"!==b&&d.push(c.jsx("tr",{key:".."},c.jsx("td",
|
||||
{css:M}),c.jsx("td",{css:y},c.jsx("a",{title:"Parent directory",href:"../",css:N},"..")),c.jsx("td",{css:y}),c.jsx("td",{css:O})));a.forEach(function(a){a=a.path.substr(1<b.length?b.length+1:1);var e=a+"/";d.push(c.jsx("tr",{key:a},c.jsx("td",{css:M},c.jsx(ya,null)),c.jsx("td",{css:y},c.jsx("a",{title:a,href:e,css:N},a)),c.jsx("td",{css:y},"-"),c.jsx("td",{css:O},"-")))});g.forEach(function(a){var e=a.size,g=a.contentType;a=a.path.substr(1<b.length?b.length+1:1);d.push(c.jsx("tr",{key:a},c.jsx("td",
|
||||
{css:M},"text/plain"===g||"text/markdown"===g?c.jsx(wa,null):c.jsx(xa,null)),c.jsx("td",{css:y},c.jsx("a",{title:a,href:a,css:N},a)),c.jsx("td",{css:y},ea(e)),c.jsx("td",{css:O},g)))});var h=[];0<g.length&&h.push(g.length+" file"+(1===g.length?"":"s"));0<a.length&&h.push(a.length+" folder"+(1===a.length?"":"s"));return c.jsx(S,null,c.jsx(T,null,c.jsx("span",null,h.join(", "))),c.jsx("table",{css:{width:"100%",borderCollapse:"collapse",borderRadius:2,background:"#fff","@media (max-width: 700px)":{"& th + th + th + th, & td + td + td + td":{display:"none"}},
|
||||
"& tr:first-of-type td":{borderTop:0}}},c.jsx("thead",null,c.jsx("tr",null,c.jsx("th",null,c.jsx(H,null,"Icon")),c.jsx("th",null,c.jsx(H,null,"Name")),c.jsx("th",null,c.jsx(H,null,"Size")),c.jsx("th",null,c.jsx(H,null,"Content Type")))),c.jsx("tbody",null,d)))}function Ba(a){a=a.split("/");return a[a.length-1]}function Ca(a){var b=a.uri;return c.jsx("div",{css:{padding:20,textAlign:"center"}},c.jsx("img",{alt:Ba(a.path),src:b}))}function Da(a){a=a.highlights.slice(0);var b=a.length&&""===a[a.length-
|
||||
1];b&&a.pop();return c.jsx("div",{className:"code-listing",css:{overflowX:"auto",overflowY:"hidden",paddingTop:5,paddingBottom:5}},c.jsx("table",{css:{border:"none",borderCollapse:"collapse",borderSpacing:0}},c.jsx("tbody",null,a.map(function(a,b){var e=b+1;return c.jsx("tr",{key:b},c.jsx("td",{id:"L"+e,css:{paddingLeft:10,paddingRight:10,color:"rgba(27,31,35,.3)",textAlign:"right",verticalAlign:"top",width:"1%",minWidth:50,userSelect:"none"}},c.jsx("span",null,e)),c.jsx("td",{id:"LC"+e,css:{paddingLeft:10,
|
||||
paddingRight:10,color:"#24292e",whiteSpace:"pre"}},c.jsx("code",{dangerouslySetInnerHTML:{__html:a}})))}),!b&&c.jsx("tr",{key:"no-newline"},c.jsx("td",{css:{paddingLeft:10,paddingRight:10,color:"rgba(27,31,35,.3)",textAlign:"right",verticalAlign:"top",width:"1%",minWidth:50,userSelect:"none"}},"\\"),c.jsx("td",{css:{paddingLeft:10,color:"rgba(27,31,35,.3)",userSelect:"none"}},"No newline at end of file")))))}function Ea(){return c.jsx("div",{css:{padding:20}},c.jsx("p",{css:{textAlign:"center"}},
|
||||
"No preview available."))}function fa(a){var b=a.packageName,e=a.packageVersion,g=a.path;a=a.details;var d=a.highlights,h=a.uri,r=a.language;return c.jsx(S,null,c.jsx(T,null,c.jsx("span",null,ea(a.size)),c.jsx("span",null,r),c.jsx("span",null,c.jsx("a",{href:"/"+b+"@"+e+g,css:{display:"inline-block",marginLeft:8,padding:"2px 8px",textDecoration:"none",fontWeight:600,fontSize:"0.9rem",color:"#24292e",backgroundColor:"#eff3f6",border:"1px solid rgba(27,31,35,.2)",borderRadius:3,":hover":{backgroundColor:"#e6ebf1",
|
||||
borderColor:"rgba(27,31,35,.35)"},":active":{backgroundColor:"#e9ecef",borderColor:"rgba(27,31,35,.35)",boxShadow:"inset 0 0.15em 0.3em rgba(27,31,35,.15)"}}},"View Raw"))),d?c.jsx(Da,{highlights:d}):h?c.jsx(Ca,{path:g,uri:h}):c.jsx(Ea,null))}function ha(){var a=Q(["\n .code-listing {\n background: #fbfdff;\n color: #383a42;\n }\n .code-comment,\n .code-quote {\n color: #a0a1a7;\n font-style: italic;\n }\n .code-doctag,\n .code-keyword,\n .code-link,\n .code-formula {\n color: #a626a4;\n }\n .code-section,\n .code-name,\n .code-selector-tag,\n .code-deletion,\n .code-subst {\n color: #e45649;\n }\n .code-literal {\n color: #0184bb;\n }\n .code-string,\n .code-regexp,\n .code-addition,\n .code-attribute,\n .code-meta-string {\n color: #50a14f;\n }\n .code-built_in,\n .code-class .code-title {\n color: #c18401;\n }\n .code-attr,\n .code-variable,\n .code-template-variable,\n .code-type,\n .code-selector-class,\n .code-selector-attr,\n .code-selector-pseudo,\n .code-number {\n color: #986801;\n }\n .code-symbol,\n .code-bullet,\n .code-meta,\n .code-selector-id,\n .code-title {\n color: #4078f2;\n }\n .code-emphasis {\n font-style: italic;\n }\n .code-strong {\n font-weight: bold;\n }\n"]);
|
||||
ha=function(){return a};return a}function ia(){var a=Q(["\n html {\n box-sizing: border-box;\n }\n *,\n *:before,\n *:after {\n box-sizing: inherit;\n }\n\n html,\n body,\n #root {\n height: 100%;\n margin: 0;\n }\n\n body {\n ","\n font-size: 16px;\n line-height: 1.5;\n overflow-wrap: break-word;\n background: white;\n color: black;\n }\n\n code {\n ","\n }\n\n th,\n td {\n padding: 0;\n }\n\n select {\n font-size: inherit;\n }\n\n #root {\n display: flex;\n flex-direction: column;\n }\n"]);
|
||||
ia=function(){return a};return a}function ja(a){var b=a.css;a=P(a,["css"]);return c.jsx("a",w({},a,{css:w({color:"#0076ff",textDecoration:"none",":hover":{textDecoration:"underline"}},b)}))}function Fa(){return c.jsx("header",{css:{marginTop:"2rem"}},c.jsx("h1",{css:{textAlign:"center",fontSize:"3rem",letterSpacing:"0.05em"}},c.jsx("a",{href:"/",css:{color:"#000",textDecoration:"none"}},"UNPKG")))}function Ga(a){var b=a.packageName,e=a.packageVersion,g=a.availableVersions;a=a.filename;var d=[];if("/"===
|
||||
a)d.push(b);else{var h="/browse/"+b+"@"+e;d.push(c.jsx(ja,{href:h+"/"},b));b=a.replace(/^\/+/,"").replace(/\/+$/,"").split("/");a=b.pop();b.forEach(function(a){h+="/"+a;d.push(c.jsx(ja,{href:h+"/"},a))});d.push(a)}return c.jsx("header",{css:{display:"flex",flexDirection:"row",alignItems:"center","@media (max-width: 700px)":{flexDirection:"column-reverse",alignItems:"flex-start"}}},c.jsx("h1",{css:{fontSize:"1.5rem",fontWeight:"normal",flex:1,wordBreak:"break-all"}},c.jsx("nav",null,d.map(function(a,
|
||||
b,e){return c.jsx(t.Fragment,{key:b},0!==b&&c.jsx("span",{css:{paddingLeft:5,paddingRight:5}},"/"),b===e.length-1?c.jsx("strong",null,a):a)}))),c.jsx(Ha,{packageVersion:e,availableVersions:g,onChange:function(a){window.location.href=window.location.href.replace("@"+e,"@"+a)}}))}function Ha(a){var b=a.onChange;return c.jsx("p",{css:{marginLeft:20,"@media (max-width: 700px)":{marginLeft:0,marginBottom:0}}},c.jsx("label",null,"Version:"," ",c.jsx("select",{name:"version",defaultValue:a.packageVersion,
|
||||
onChange:function(a){b&&b(a.target.value)},css:{appearance:"none",cursor:"pointer",padding:"4px 24px 4px 8px",fontWeight:600,fontSize:"0.9em",color:"#24292e",border:"1px solid rgba(27,31,35,.2)",borderRadius:3,backgroundColor:"#eff3f6",backgroundImage:"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAKCAYAAAC9vt6cAAAAAXNSR0IArs4c6QAAARFJREFUKBVjZAACNS39RhBNKrh17WI9o4quoT3Dn78HSNUMUs/CzOTI/O7Vi4dCYpJ3/jP+92BkYGAlyiBGhm8MjIxJt65e3MQM0vDu9YvLYmISILYZELOBxHABRkaGr0yMzF23r12YDFIDNgDEePv65SEhEXENBkYGFSAXuyGMjF8Z/jOsvX3tYiFIDwgwQSgIaaijnvj/P8M5IO8HsjiY/f//D4b//88A1SQhywG9jQr09PS4v/1mPAeUUPzP8B8cJowMjL+Bqu6xMQmaXL164AuyDgwDQJLa2qYSP//9vARkCoMVMzK8YeVkNbh+9uxzMB+JwGoASF5Vx0jz/98/18BqmZi171w9D2EjaaYKEwAEK00XQLdJuwAAAABJRU5ErkJggg==)",
|
||||
backgroundPosition:"right 8px center",backgroundRepeat:"no-repeat",backgroundSize:"auto 25%",":hover":{backgroundColor:"#e6ebf1",borderColor:"rgba(27,31,35,.35)"},":active":{backgroundColor:"#e9ecef",borderColor:"rgba(27,31,35,.35)",boxShadow:"inset 0 0.15em 0.3em rgba(27,31,35,.15)"}}},a.availableVersions.map(function(a){return c.jsx("option",{key:a,value:a},a)}))))}function Ia(a){var b=a.packageName,e=a.packageVersion;a=a.target;return"directory"===a.type?c.jsx(ca,{path:a.path,details:a.details}):
|
||||
"file"===a.type?c.jsx(fa,{packageName:b,packageVersion:e,path:a.path,details:a.details}):null}function ka(a){var b=a.packageName,e=a.packageVersion,g=a.availableVersions;g=void 0===g?[]:g;var d=a.filename;a=a.target;return c.jsx(t.Fragment,null,c.jsx(c.Global,{styles:Ja}),c.jsx(c.Global,{styles:Ka}),c.jsx("div",{css:{flex:"1 0 auto"}},c.jsx("div",{css:{maxWidth:940,padding:"0 20px",margin:"0 auto"}},c.jsx(Fa,null)),c.jsx("div",{css:{maxWidth:940,padding:"0 20px",margin:"0 auto"}},c.jsx(Ga,{packageName:b,
|
||||
packageVersion:e,availableVersions:g,filename:d})),c.jsx("div",{css:{maxWidth:940,padding:"0 20px",margin:"0 auto","@media (max-width: 700px)":{padding:0,margin:0}}},c.jsx(Ia,{packageName:b,packageVersion:e,target:a}))),c.jsx("footer",{css:{marginTop:"5rem",background:"black",color:"#aaa"}},c.jsx("div",{css:{maxWidth:940,padding:"10px 20px",margin:"0 auto",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between"}},c.jsx("p",null,c.jsx("span",null,"Build: ","a7ebffa")),
|
||||
c.jsx("p",null,c.jsx("span",null,"\u00a9 ",(new Date).getFullYear()," UNPKG")),c.jsx("p",{css:{fontSize:"1.5rem"}},c.jsx("a",{href:"https://twitter.com/unpkg",css:{color:"#aaa",display:"inline-block",":hover":{color:"white"}}},c.jsx(za,null)),c.jsx("a",{href:"https://github.com/mjackson/unpkg",css:{color:"#aaa",display:"inline-block",":hover":{color:"white"},marginLeft:"1rem"}},c.jsx(Aa,null))))))}var la="default"in t?t["default"]:t;A=A&&A.hasOwnProperty("default")?A["default"]:A;var La="undefined"!==
|
||||
typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{},m=D(function(a,b){function c(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case d:switch(a=a.type,a){case l:case f:case r:case m:case k:case v:return a;default:switch(a=a&&a.$$typeof,a){case p:case n:case q:return a;default:return b}}case x:case u:case h:return b}}}function g(a){return c(a)===f}Object.defineProperty(b,"__esModule",{value:!0});var d=
|
||||
(a="function"===typeof Symbol&&Symbol.for)?Symbol.for("react.element"):60103,h=a?Symbol.for("react.portal"):60106,r=a?Symbol.for("react.fragment"):60107,k=a?Symbol.for("react.strict_mode"):60108,m=a?Symbol.for("react.profiler"):60114,q=a?Symbol.for("react.provider"):60109,p=a?Symbol.for("react.context"):60110,l=a?Symbol.for("react.async_mode"):60111,f=a?Symbol.for("react.concurrent_mode"):60111,n=a?Symbol.for("react.forward_ref"):60112,v=a?Symbol.for("react.suspense"):60113,u=a?Symbol.for("react.memo"):
|
||||
60115,x=a?Symbol.for("react.lazy"):60116;b.typeOf=c;b.AsyncMode=l;b.ConcurrentMode=f;b.ContextConsumer=p;b.ContextProvider=q;b.Element=d;b.ForwardRef=n;b.Fragment=r;b.Lazy=x;b.Memo=u;b.Portal=h;b.Profiler=m;b.StrictMode=k;b.Suspense=v;b.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===r||a===f||a===m||a===k||a===v||"object"===typeof a&&null!==a&&(a.$$typeof===x||a.$$typeof===u||a.$$typeof===q||a.$$typeof===p||a.$$typeof===n)};b.isAsyncMode=function(a){return g(a)||
|
||||
c(a)===l};b.isConcurrentMode=g;b.isContextConsumer=function(a){return c(a)===p};b.isContextProvider=function(a){return c(a)===q};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===d};b.isForwardRef=function(a){return c(a)===n};b.isFragment=function(a){return c(a)===r};b.isLazy=function(a){return c(a)===x};b.isMemo=function(a){return c(a)===u};b.isPortal=function(a){return c(a)===h};b.isProfiler=function(a){return c(a)===m};b.isStrictMode=function(a){return c(a)===k};b.isSuspense=
|
||||
function(a){return c(a)===v}});R(m);var na=D(function(a,b){(function(){function a(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case h:switch(a=a.type,a){case f:case n:case k:case q:case m:case u:return a;default:switch(a=a&&a.$$typeof,a){case l:case v:case p:return a;default:return b}}case I:case x:case r:return b}}}function c(b){return a(b)===n}Object.defineProperty(b,"__esModule",{value:!0});var d="function"===typeof Symbol&&Symbol.for,h=d?Symbol.for("react.element"):60103,r=
|
||||
d?Symbol.for("react.portal"):60106,k=d?Symbol.for("react.fragment"):60107,m=d?Symbol.for("react.strict_mode"):60108,q=d?Symbol.for("react.profiler"):60114,p=d?Symbol.for("react.provider"):60109,l=d?Symbol.for("react.context"):60110,f=d?Symbol.for("react.async_mode"):60111,n=d?Symbol.for("react.concurrent_mode"):60111,v=d?Symbol.for("react.forward_ref"):60112,u=d?Symbol.for("react.suspense"):60113,x=d?Symbol.for("react.memo"):60115,I=d?Symbol.for("react.lazy"):60116;d=function(){};var Ma=function(a){for(var b=
|
||||
arguments.length,f=Array(1<b?b-1:0),c=1;c<b;c++)f[c-1]=arguments[c];var n=0;b="Warning: "+a.replace(/%s/g,function(){return f[n++]});"undefined"!==typeof console&&console.warn(b);try{throw Error(b);}catch(Xa){}},Na=d=function(a,b){if(void 0===b)throw Error("`lowPriorityWarning(condition, format, ...args)` requires a warning message argument");if(!a){for(var f=arguments.length,c=Array(2<f?f-2:0),n=2;n<f;n++)c[n-2]=arguments[n];Ma.apply(void 0,[b].concat(c))}},ma=!1;b.typeOf=a;b.AsyncMode=f;b.ConcurrentMode=
|
||||
n;b.ContextConsumer=l;b.ContextProvider=p;b.Element=h;b.ForwardRef=v;b.Fragment=k;b.Lazy=I;b.Memo=x;b.Portal=r;b.Profiler=q;b.StrictMode=m;b.Suspense=u;b.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===k||a===n||a===q||a===m||a===u||"object"===typeof a&&null!==a&&(a.$$typeof===I||a.$$typeof===x||a.$$typeof===p||a.$$typeof===l||a.$$typeof===v)};b.isAsyncMode=function(b){ma||(ma=!0,Na(!1,"The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API."));
|
||||
return c(b)||a(b)===f};b.isConcurrentMode=c;b.isContextConsumer=function(b){return a(b)===l};b.isContextProvider=function(b){return a(b)===p};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===h};b.isForwardRef=function(b){return a(b)===v};b.isFragment=function(b){return a(b)===k};b.isLazy=function(b){return a(b)===I};b.isMemo=function(b){return a(b)===x};b.isPortal=function(b){return a(b)===r};b.isProfiler=function(b){return a(b)===q};b.isStrictMode=function(b){return a(b)===
|
||||
m};b.isSuspense=function(b){return a(b)===u}})()});R(na);var oa=D(function(a){a.exports=na}),pa=Object.getOwnPropertySymbols,Oa=Object.prototype.hasOwnProperty,Pa=Object.prototype.propertyIsEnumerable,Qa=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;var b={};for(a=0;10>a;a++)b["_"+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(b).map(function(a){return b[a]}).join(""))return!1;var c={};"abcdefghijklmnopqrst".split("").forEach(function(a){c[a]=
|
||||
a});return"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},c)).join("")?!1:!0}catch(g){return!1}}()?Object.assign:function(a,b){if(null===a||void 0===a)throw new TypeError("Object.assign cannot be called with null or undefined");var c=Object(a);for(var g,d=1;d<arguments.length;d++){var h=Object(arguments[d]);for(var r in h)Oa.call(h,r)&&(c[r]=h[r]);if(pa){g=pa(h);for(var k=0;k<g.length;k++)Pa.call(h,g[k])&&(c[g[k]]=h[g[k]])}}return c},K=function(){},L={},ua=Function.call.bind(Object.prototype.hasOwnProperty);
|
||||
K=function(a){a="Warning: "+a;"undefined"!==typeof console&&console.error(a);try{throw Error(a);}catch(b){}};J.resetWarningCache=function(){L={}};var Ra=Function.call.bind(Object.prototype.hasOwnProperty),C=function(){};C=function(a){a="Warning: "+a;"undefined"!==typeof console&&console.error(a);try{throw Error(a);}catch(b){}};var Sa=function(a,b){function c(a,b){return a===b?0!==a||1/a===1/b:a!==a&&b!==b}function g(a){this.message=a;this.stack=""}function d(a){function c(c,n,v,d,e,u,h){d=d||"<<anonymous>>";
|
||||
u=u||v;if("SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==h){if(b)throw c=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"),c.name="Invariant Violation",c;"undefined"!==typeof console&&(h=d+":"+v,!f[h]&&3>l&&(C("You are manually calling a React.PropTypes validation function for the `"+u+"` prop on `"+d+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),
|
||||
f[h]=!0,l++))}return null==n[v]?c?null===n[v]?new g("The "+e+" `"+u+"` is marked as required "+("in `"+d+"`, but its value is `null`.")):new g("The "+e+" `"+u+"` is marked as required in "+("`"+d+"`, but its value is `undefined`.")):null:a(n,v,d,e,u)}var f={},l=0,d=c.bind(null,!1);d.isRequired=c.bind(null,!0);return d}function h(a){return d(function(b,c,f,d,l,e){b=b[c];return k(b)!==a?(b=m(b),new g("Invalid "+d+" `"+l+"` of type "+("`"+b+"` supplied to `"+f+"`, expected ")+("`"+a+"`."))):null})}function r(b){switch(typeof b){case "number":case "string":case "undefined":return!0;
|
||||
case "boolean":return!b;case "object":if(Array.isArray(b))return b.every(r);if(null===b||a(b))return!0;var c=b&&(p&&b[p]||b["@@iterator"]);var f="function"===typeof c?c:void 0;if(f)if(c=f.call(b),f!==b.entries)for(;!(b=c.next()).done;){if(!r(b.value))return!1}else for(;!(b=c.next()).done;){if((b=b.value)&&!r(b[1]))return!1}else return!1;return!0;default:return!1}}function k(a){var b=typeof a;return Array.isArray(a)?"array":a instanceof RegExp?"object":"symbol"===b||a&&("Symbol"===a["@@toStringTag"]||
|
||||
"function"===typeof Symbol&&a instanceof Symbol)?"symbol":b}function m(a){if("undefined"===typeof a||null===a)return""+a;var b=k(a);if("object"===b){if(a instanceof Date)return"date";if(a instanceof RegExp)return"regexp"}return b}function q(a){a=m(a);switch(a){case "array":case "object":return"an "+a;case "boolean":case "date":case "regexp":return"a "+a;default:return a}}var p="function"===typeof Symbol&&Symbol.iterator,l={array:h("array"),bool:h("boolean"),func:h("function"),number:h("number"),object:h("object"),
|
||||
string:h("string"),symbol:h("symbol"),any:d(G),arrayOf:function(a){return d(function(b,c,f,d,l){if("function"!==typeof a)return new g("Property `"+l+"` of component `"+f+"` has invalid PropType notation inside arrayOf.");b=b[c];if(!Array.isArray(b))return b=k(b),new g("Invalid "+d+" `"+l+"` of type "+("`"+b+"` supplied to `"+f+"`, expected an array."));for(c=0;c<b.length;c++){var n=a(b,c,f,d,l+"["+c+"]","SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");if(n instanceof Error)return n}return null})},
|
||||
element:function(){return d(function(b,c,d,l,e){b=b[c];return a(b)?null:(b=k(b),new g("Invalid "+l+" `"+e+"` of type "+("`"+b+"` supplied to `"+d+"`, expected a single ReactElement.")))})}(),elementType:function(){return d(function(a,b,c,d,l){a=a[b];return oa.isValidElementType(a)?null:(a=k(a),new g("Invalid "+d+" `"+l+"` of type "+("`"+a+"` supplied to `"+c+"`, expected a single ReactElement type.")))})}(),instanceOf:function(a){return d(function(b,c,f,d,l){if(!(b[c]instanceof a)){var n=a.name||
|
||||
"<<anonymous>>";b=b[c];b=b.constructor&&b.constructor.name?b.constructor.name:"<<anonymous>>";return new g("Invalid "+d+" `"+l+"` of type "+("`"+b+"` supplied to `"+f+"`, expected ")+("instance of `"+n+"`."))}return null})},node:function(){return d(function(a,b,c,d,l){return r(a[b])?null:new g("Invalid "+d+" `"+l+"` supplied to "+("`"+c+"`, expected a ReactNode."))})}(),objectOf:function(a){return d(function(b,c,f,d,l){if("function"!==typeof a)return new g("Property `"+l+"` of component `"+f+"` has invalid PropType notation inside objectOf.");
|
||||
b=b[c];c=k(b);if("object"!==c)return new g("Invalid "+d+" `"+l+"` of type "+("`"+c+"` supplied to `"+f+"`, expected an object."));for(var n in b)if(Ra(b,n)&&(c=a(b,n,f,d,l+"."+n,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"),c instanceof Error))return c;return null})},oneOf:function(a){return Array.isArray(a)?d(function(b,f,d,l,e){b=b[f];for(f=0;f<a.length;f++)if(c(b,a[f]))return null;f=JSON.stringify(a,function(a,b){return"symbol"===m(b)?String(b):b});return new g("Invalid "+l+" `"+e+"` of value `"+
|
||||
String(b)+"` "+("supplied to `"+d+"`, expected one of "+f+"."))}):(1<arguments.length?C("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."):C("Invalid argument supplied to oneOf, expected an array."),G)},oneOfType:function(a){if(!Array.isArray(a))return C("Invalid argument supplied to oneOfType, expected an instance of array."),G;for(var b=0;b<a.length;b++){var c=a[b];if("function"!==
|
||||
typeof c)return C("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+q(c)+" at index "+b+"."),G}return d(function(b,c,f,d,l){for(var e=0;e<a.length;e++)if(null==(0,a[e])(b,c,f,d,l,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return null;return new g("Invalid "+d+" `"+l+"` supplied to "+("`"+f+"`."))})},shape:function(a){return d(function(b,c,d,l,f){b=b[c];c=k(b);if("object"!==c)return new g("Invalid "+l+" `"+f+"` of type `"+c+"` "+("supplied to `"+d+"`, expected `object`."));
|
||||
for(var e in a)if(c=a[e])if(c=c(b,e,d,l,f+"."+e,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return c;return null})},exact:function(a){return d(function(b,c,d,l,f){var e=b[c],n=k(e);if("object"!==n)return new g("Invalid "+l+" `"+f+"` of type `"+n+"` "+("supplied to `"+d+"`, expected `object`."));n=Qa({},b[c],a);for(var h in n){n=a[h];if(!n)return new g("Invalid "+l+" `"+f+"` key `"+h+"` supplied to `"+d+"`.\nBad object: "+JSON.stringify(b[c],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(a),
|
||||
null," "));if(n=n(e,h,d,l,f+"."+h,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"))return n}return null})}};g.prototype=Error.prototype;l.checkPropTypes=J;l.resetWarningCache=J.resetWarningCache;return l.PropTypes=l};m=D(function(a){a.exports=Sa(oa.isElement,!0)});var Ta=Object.assign||function(a){for(var b=1;b<arguments.length;b++){var c=arguments[b],g;for(g in c)Object.prototype.hasOwnProperty.call(c,g)&&(a[g]=c[g])}return a},Ua={border:0,clip:"rect(0 0 0 0)",height:"1px",width:"1px",margin:"-1px",
|
||||
padding:0,overflow:"hidden",position:"absolute"},H=function(a){return la.createElement("div",Ta({style:Ua},a))},qa=D(function(a){(function(b,c){a.exports=c()})(La,function(){function a(a){if(!a)return!0;if(!d(a)||0!==a.length)for(var b in a)if(q.call(a,b))return!1;return!0}function c(a){return"number"===typeof a||"[object Number]"===t.call(a)}function g(a){return"string"===typeof a||"[object String]"===t.call(a)}function d(a){return"object"===typeof a&&"number"===typeof a.length&&"[object Array]"===
|
||||
t.call(a)}function h(a){var b=parseInt(a);return b.toString()===a?b:a}function m(b,d,e,k){c(d)&&(d=[d]);if(a(d))return b;if(g(d))return m(b,d.split("."),e,k);var f=h(d[0]);if(1===d.length)return d=b[f],void 0!==d&&k||(b[f]=e),d;void 0===b[f]&&(c(f)?b[f]=[]:b[f]={});return m(b[f],d.slice(1),e,k)}function k(b,f){c(f)&&(f=[f]);if(!a(b)){if(a(f))return b;if(g(f))return k(b,f.split("."));var e=h(f[0]),l=b[e];if(1===f.length)void 0!==l&&(d(b)?b.splice(e,1):delete b[e]);else if(void 0!==b[e])return k(b[e],
|
||||
f.slice(1));return b}}var t=Object.prototype.toString,q=Object.prototype.hasOwnProperty,p={ensureExists:function(a,b,c){return m(a,b,c,!0)},set:function(a,b,c,d){return m(a,b,c,d)},insert:function(a,b,c,e){var f=p.get(a,b);e=~~e;d(f)||(f=[],p.set(a,b,f));f.splice(e,0,c)},empty:function(b,f){if(a(f))return b;if(!a(b)){var e,h;if(!(e=p.get(b,f)))return b;if(g(e))return p.set(b,f,"");if("boolean"===typeof e||"[object Boolean]"===t.call(e))return p.set(b,f,!1);if(c(e))return p.set(b,f,0);if(d(e))e.length=
|
||||
0;else if("object"===typeof e&&"[object Object]"===t.call(e))for(h in e)q.call(e,h)&&delete e[h];else return p.set(b,f,null)}},push:function(a,b){var c=p.get(a,b);d(c)||(c=[],p.set(a,b,c));c.push.apply(c,Array.prototype.slice.call(arguments,2))},coalesce:function(a,b,c){for(var d,e=0,f=b.length;e<f;e++)if(void 0!==(d=p.get(a,b[e])))return d;return c},get:function(b,d,e){c(d)&&(d=[d]);if(a(d))return b;if(a(b))return e;if(g(d))return p.get(b,d.split("."),e);var f=h(d[0]);return 1===d.length?void 0===
|
||||
b[f]?e:b[f]:p.get(b[f],d.slice(1),e)},del:function(a,b){return k(a,b)}};return p})});var ra=function(a){return function(b){return typeof b===a}};var Va=function(a,b){var c=1,g=b||function(a,b){return b};"-"===a[0]&&(c=-1,a=a.substr(1));return function(b,e){var d;b=g(a,qa.get(b,a));e=g(a,qa.get(e,a));b<e&&(d=-1);b>e&&(d=1);b===e&&(d=0);return d*c}};var da=function(){var a=Array.prototype.slice.call(arguments),b=a.filter(ra("string")),c=a.filter(ra("function"))[0];return function(a,d){for(var e=b.length,
|
||||
g=0,k=0;0===g&&k<e;)g=Va(b[k],c)(a,d),k++;return g}};let sa="B kB MB GB TB PB EB ZB YB".split(" "),ta=(a,b)=>{let c=a;"string"===typeof b?c=a.toLocaleString(b):!0===b&&(c=a.toLocaleString());return c};var ea=(a,b)=>{if(!Number.isFinite(a))throw new TypeError(`Expected a finite number, got ${typeof a}: ${a}`);b=Object.assign({},b);if(b.signed&&0===a)return" 0 B";var c=0>a;let g=c?"-":b.signed?"+":"";c&&(a=-a);if(1>a)return a=ta(a,b.locale),g+a+" B";c=Math.min(Math.floor(Math.log10(a)/3),sa.length-
|
||||
1);a=Number((a/Math.pow(1E3,c)).toPrecision(3));a=ta(a,b.locale);return g+a+" "+sa[c]},W={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},V=t.createContext&&t.createContext(W),z=function(){z=Object.assign||function(a){for(var b,c=1,g=arguments.length;c<g;c++){b=arguments[c];for(var d in b)Object.prototype.hasOwnProperty.call(b,d)&&(a[d]=b[d])}return a};return z.apply(this,arguments)},Y=function(a){return E({tag:"svg",attr:{viewBox:"0 0 12 16"},child:[{tag:"path",attr:{fillRule:"evenodd",
|
||||
d:"M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM5 6.98L3.5 8.5 5 10l-.5 1L2 8.5 4.5 6l.5.98zM7.5 6L10 8.5 7.5 11l-.5-.98L8.5 8.5 7 7l.5-1z"}}]})(a)};Y.displayName="GoFileCode";var Z=function(a){return E({tag:"svg",attr:{viewBox:"0 0 14 16"},child:[{tag:"path",attr:{fillRule:"evenodd",d:"M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"}}]})(a)};Z.displayName="GoFileDirectory";var X=function(a){return E({tag:"svg",
|
||||
attr:{viewBox:"0 0 12 16"},child:[{tag:"path",attr:{fillRule:"evenodd",d:"M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"}}]})(a)};X.displayName="GoFile";var ba=function(a){return E({tag:"svg",attr:{viewBox:"0 0 496 512"},child:[{tag:"path",attr:{d:"M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"}}]})(a)};
|
||||
ba.displayName="FaGithub";var aa=function(a){return E({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"}}]})(a)};
|
||||
aa.displayName="FaTwitter";var N={color:"#0076ff",textDecoration:"none",":hover":{textDecoration:"underline"}},y={paddingTop:6,paddingRight:3,paddingBottom:6,paddingLeft:3,borderTop:"1px solid #eaecef"},M=w({},y,{color:"#424242",width:17,paddingRight:2,paddingLeft:10,"@media (max-width: 700px)":{paddingLeft:20}}),O=w({},y,{textAlign:"right",paddingRight:10,"@media (max-width: 700px)":{paddingRight:20}});ca.propTypes={path:m.string.isRequired,details:m.objectOf(m.shape({path:m.string.isRequired,type:m.oneOf(["directory",
|
||||
"file"]).isRequired,contentType:m.string,integrity:m.string,size:m.number})).isRequired};fa.propTypes={path:m.string.isRequired,details:m.shape({contentType:m.string.isRequired,highlights:m.arrayOf(m.string),uri:m.string,integrity:m.string.isRequired,language:m.string.isRequired,size:m.number.isRequired}).isRequired};var Ja=c.css(ia(),'\nfont-family: -apple-system,\n BlinkMacSystemFont,\n "Segoe UI",\n "Roboto",\n "Oxygen",\n "Ubuntu",\n "Cantarell",\n "Fira Sans",\n "Droid Sans",\n "Helvetica Neue",\n sans-serif;\n',
|
||||
"\nfont-family: Menlo,\n Monaco,\n Lucida Console,\n Liberation Mono,\n DejaVu Sans Mono,\n Bitstream Vera Sans Mono,\n Courier New,\n monospace;\n"),Ka=c.css(ha()),Wa=m.shape({path:m.string.isRequired,type:m.oneOf(["directory","file"]).isRequired,details:m.object.isRequired});ka.propTypes={packageName:m.string.isRequired,packageVersion:m.string.isRequired,availableVersions:m.arrayOf(m.string),filename:m.string.isRequired,target:Wa.isRequired};A.hydrate(la.createElement(ka,window.__DATA__||
|
||||
{}),document.getElementById("root"))})(React,ReactDOM,emotionCore);
|
||||
</script></body></html>
|
||||
(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var z={onLoad:t,process:Tt,on:le,off:ue,trigger:ie,ajax:dr,find:b,findAll:f,closest:d,values:function(e,t){var r=Jt(e,t||"post");return r.values},remove:B,addClass:j,removeClass:n,toggleClass:U,takeClass:V,defineExtension:yr,removeExtension:br,logAll:F,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false},parseInterval:v,_:e,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=z.config.wsBinaryType;return t},version:"1.9.2"};var C={addTriggerHandler:xt,bodyContains:ee,canAccessLocalStorage:D,filterValues:er,hasAttribute:q,getAttributeValue:G,getClosestMatch:c,getExpressionVars:fr,getHeaders:Qt,getInputValues:Jt,getInternalData:Y,getSwapSpecification:rr,getTriggerSpecs:ze,getTarget:de,makeFragment:l,mergeObjects:te,makeSettleInfo:S,oobSwap:me,selectAndSwap:Me,settleImmediately:Bt,shouldCancel:Ke,triggerEvent:ie,triggerErrorEvent:ne,withExtensions:w};var R=["get","post","put","delete","patch"];var O=R.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function v(e){if(e==undefined){return undefined}if(e.slice(-2)=="ms"){return parseFloat(e.slice(0,-2))||undefined}if(e.slice(-1)=="s"){return parseFloat(e.slice(0,-1))*1e3||undefined}if(e.slice(-1)=="m"){return parseFloat(e.slice(0,-1))*1e3*60||undefined}return parseFloat(e)||undefined}function $(e,t){return e.getAttribute&&e.getAttribute(t)}function q(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function G(e,t){return $(e,t)||$(e,"data-"+t)}function u(e){return e.parentElement}function J(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function T(e,t,r){var n=G(t,r);var i=G(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function Z(t,r){var n=null;c(t,function(e){return n=T(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function H(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function i(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=J().createDocumentFragment()}return i}function L(e){return e.match(/<body/)}function l(e){var t=!L(e);if(z.config.useTemplateFragments&&t){var r=i("<body><template>"+e+"</template></body>",0);return r.querySelector("template").content}else{var n=H(e);switch(n){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return i("<table>"+e+"</table>",1);case"col":return i("<table><colgroup>"+e+"</colgroup></table>",2);case"tr":return i("<table><tbody>"+e+"</tbody></table>",2);case"td":case"th":return i("<table><tbody><tr>"+e+"</tr></tbody></table>",3);case"script":return i("<div>"+e+"</div>",1);default:return i(e,0)}}}function K(e){if(e){e()}}function A(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function N(e){return A(e,"Function")}function I(e){return A(e,"Object")}function Y(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function k(e){var t=[];if(e){for(var r=0;r<e.length;r++){t.push(e[r])}}return t}function Q(e,t){if(e){for(var r=0;r<e.length;r++){t(e[r])}}}function P(e){var t=e.getBoundingClientRect();var r=t.top;var n=t.bottom;return r<window.innerHeight&&n>=0}function ee(e){if(e.getRootNode&&e.getRootNode()instanceof ShadowRoot){return J().body.contains(e.getRootNode().host)}else{return J().body.contains(e)}}function M(e){return e.trim().split(/\s+/)}function te(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function y(e){try{return JSON.parse(e)}catch(e){x(e);return null}}function D(){var e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function X(t){try{var e=new URL(t);if(e){t=e.pathname+e.search}if(!t.match("^/$")){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return sr(J().body,function(){return eval(e)})}function t(t){var e=z.Line truncated
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "bitbadger/my-prayer-journal",
|
||||
"description": "Minimalist prayer journal to enhance your prayer life",
|
||||
"type": "project",
|
||||
"license": "MIT",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"MyPrayerJournal\\": "lib/",
|
||||
"MyPrayerJournal\\Domain\\": "lib/domain/",
|
||||
"BitBadger\\PgDocuments\\": "lib/documents/"
|
||||
}
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "Daniel J. Summers",
|
||||
"email": "daniel@bitbadger.solutions"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"netresearch/jsonmapper": "^4.2",
|
||||
"guzzlehttp/guzzle": "^7.8",
|
||||
"guzzlehttp/psr7": "^2.6",
|
||||
"http-interop/http-factory-guzzle": "^1.2",
|
||||
"auth0/auth0-php": "^8.8",
|
||||
"vlucas/phpdotenv": "^5.5",
|
||||
"visus/cuid2": "^4.0"
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"php-http/discovery": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+2365
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal;
|
||||
|
||||
/**
|
||||
* Constants for use throughout the application
|
||||
*/
|
||||
class Constants
|
||||
{
|
||||
/** @var string The `$_ENV` key for the Auth0 domain configured for myPrayerJournal */
|
||||
const AUTH0_DOMAIN = 'AUTH0_DOMAIN';
|
||||
|
||||
/** @var string The `$_ENV` key for the Auth0 client ID for myPrayerJournal */
|
||||
const AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID';
|
||||
|
||||
/** @var string The `$_ENV` key for the Auth0 client secret */
|
||||
const AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET';
|
||||
|
||||
/** @var string The `$_ENV` key for the Auth0 cookie secret */
|
||||
const AUTH0_COOKIE_SECRET = 'AUTH0_COOKIE_SECRET';
|
||||
|
||||
/** @var string The `$_ENV` key for the base URL for this instance of myPrayerJournal */
|
||||
const BASE_URL = 'AUTH0_BASE_URL';
|
||||
|
||||
/** @var string The Auth0 given name (first name) claim */
|
||||
const CLAIM_GIVEN_NAME = 'given_name';
|
||||
|
||||
/** @var string The Auth0 subscriber (sub) claim */
|
||||
const CLAIM_SUB = 'sub';
|
||||
|
||||
/** @var string The name of the cookie used to persist redirection after Auth0 authentication */
|
||||
const COOKIE_REDIRECT = 'mpjredirect';
|
||||
|
||||
/** @var string the `$_SERVER` key for the HX-Request header */
|
||||
const HEADER_HX_REQUEST = 'HTTP_HX_REQUEST';
|
||||
|
||||
/** @var string The `$_SERVER` key for the HX-History-Restore-Request header */
|
||||
const HEADER_HX_HIST_REQ = 'HTTP_HX_HISTORY_RESTORE_REQUEST';
|
||||
|
||||
/** @var string The `$_SERVER` key for the X-Time-Zone header */
|
||||
const HEADER_USER_TZ = 'HTTP_X_TIME_ZONE';
|
||||
|
||||
/** @var string The `$_REQUEST` key for whether the request was initiated by htmx */
|
||||
const IS_HTMX = 'MPJ_IS_HTMX';
|
||||
|
||||
/** @var string The `$_GET` key for state passed to Auth0 if redirection is required once authenticated */
|
||||
const LOG_ON_STATE = 'state';
|
||||
|
||||
/** @var string The `$_REQUEST` key for the page title for this request */
|
||||
const PAGE_TITLE = 'MPJ_PAGE_TITLE';
|
||||
|
||||
/** @var string The `$_SERVER` key for the current page's relative URI */
|
||||
const REQUEST_URI = 'REQUEST_URI';
|
||||
|
||||
/** @var string The `$_GET` key sent to the log on page if redirection is required once authenticated */
|
||||
const RETURN_URL = 'return_url';
|
||||
|
||||
/** @var string The `$_REQUEST` key for the timezone reference to use for this request */
|
||||
const TIME_ZONE = 'MPJ_TIME_ZONE';
|
||||
|
||||
/** @var string The `$_REQUEST` key for the current user's ID */
|
||||
const USER_ID = 'MPJ_USER_ID';
|
||||
|
||||
/** @var string The `$_REQUEST` key for the current version of myPrayerJournal */
|
||||
const VERSION = 'MPJ_VERSION';
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal;
|
||||
|
||||
use BitBadger\PgDocuments\{ Definition, Document, DocumentIndex, Query };
|
||||
use MyPrayerJournal\Domain\{ History, JournalRequest, Note, Request, RequestAction };
|
||||
|
||||
class Data
|
||||
{
|
||||
/** The prayer request table */
|
||||
const REQ_TABLE = 'mpj.request';
|
||||
|
||||
/**
|
||||
* Ensure the table and index exist
|
||||
*/
|
||||
public static function startUp(): void
|
||||
{
|
||||
Definition::ensureTable(self::REQ_TABLE);
|
||||
Definition::ensureIndex(self::REQ_TABLE, DocumentIndex::Optimized);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Find a full prayer request by its ID
|
||||
// *
|
||||
// * @param string $reqId The request ID
|
||||
// * @param string $userId The ID of the currently logged-on user
|
||||
// * @return ?Request The request, or null if it is not found
|
||||
// */
|
||||
// public static function findFullRequestById(string $reqId, string $userId): ?Request
|
||||
// {
|
||||
// $req = Document::findById(self::REQ_TABLE, $reqId, Request::class);
|
||||
// return is_null($req) || $req->userId != $userId ? null : $req;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Add a history entry to the specified request
|
||||
// *
|
||||
// * @param string $reqId The request ID
|
||||
// * @param string $userId The ID of the currently logged-on user
|
||||
// * @param History $history The history entry to be added
|
||||
// */
|
||||
// public static function addHistory(string $reqId, string $userId, History $history)
|
||||
// {
|
||||
// $req = self::findFullRequestById($reqId, $userId);
|
||||
// if (is_null($req)) throw new \InvalidArgumentException("$reqId not found");
|
||||
// array_unshift($req->history, $history);
|
||||
// Document::updateFull(self::REQ_TABLE, $reqId, $req);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Add a note to the specified request
|
||||
// *
|
||||
// * @param string $reqId The request ID
|
||||
// * @param string $userId The ID of the currently logged-on user
|
||||
// * @param Note $note The note to be added
|
||||
// */
|
||||
// public static function addNote(string $reqId, string $userId, Note $note)
|
||||
// {
|
||||
// $req = self::findFullRequestById($reqId, $userId);
|
||||
// if (is_null($req)) throw new \InvalidArgumentException("$reqId not found");
|
||||
// array_unshift($req->notes, $note);
|
||||
// Document::updateFull(self::REQ_TABLE, $reqId, $req);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Add a new request
|
||||
// *
|
||||
// * @param Request $req The request to be added
|
||||
// */
|
||||
// public static function addRequest(Request $req)
|
||||
// {
|
||||
// Document::insert(self::REQ_TABLE, $req->id, $req);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Map an array of `Request`s to an array of `JournalRequest`s
|
||||
*
|
||||
* @param Request[] $reqs The requests to map
|
||||
* @param bool $full Whether to include history and notes (true) or not (false)
|
||||
* @return JournalRequest[] The journal request objects
|
||||
*/
|
||||
private static function mapToJournalRequest(array $reqs, bool $full): array
|
||||
{
|
||||
return array_map(fn (Request $req) => new JournalRequest($req, $full), $reqs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get journal requests for the given user by "answered" status
|
||||
*
|
||||
* @param string $userId The ID of the user for whom requests should be retrieved
|
||||
* @param string $op The JSON Path operator to use for comparison (`==` or `<>`)
|
||||
* @return JournalRequest[] The journal request objects
|
||||
*/
|
||||
private static function getJournalByAnswered(string $userId, string $op): array
|
||||
{
|
||||
$sql = sprintf('%s WHERE %s AND %s', Query::selectFromTable(self::REQ_TABLE), Query::whereDataContains('$1'),
|
||||
Query::whereJsonPathMatches('$2'));
|
||||
$params = [
|
||||
Query::jsonbDocParam([ 'userId' => $userId ]),
|
||||
sprintf('$.history[0].status ? (@ %s "%s")', $op, RequestAction::Answered->name)
|
||||
];
|
||||
return self::mapToJournalRequest(
|
||||
Document::customList($sql, $params, Request::class, Document::mapFromJson(...)), true);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Retrieve all answered requests for this user
|
||||
// *
|
||||
// * @param string $userId The ID of the user for whom answered requests should be retrieved
|
||||
// * @return JournalRequest[] The answered requests
|
||||
// */
|
||||
// public static function getAnsweredRequests(string $userId): array
|
||||
// {
|
||||
// $answered = self::getJournalByAnswered($userId, '==');
|
||||
// usort($answered,
|
||||
// fn (JournalRequest $a, JournalRequest $b) => $a->asOf == $b->asOf ? 0 : ($a->asOf > $b->asOf ? -1 : 1));
|
||||
// return $answered;
|
||||
// }
|
||||
|
||||
/**
|
||||
* Get the user's current prayer request journal
|
||||
*
|
||||
* @param string $userId The ID of the user whose journal should be retrieved
|
||||
* @return JournalRequest[] The journal request objects
|
||||
*/
|
||||
public static function getJournal(string $userId): array
|
||||
{
|
||||
$reqs = self::getJournalByAnswered($userId, '<>');
|
||||
usort($reqs,
|
||||
fn (JournalRequest $a, JournalRequest $b) => $a->asOf == $b->asOf ? 0 : ($a->asOf < $b->asOf ? -1 : 1));
|
||||
return $reqs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal;
|
||||
|
||||
use DateTimeImmutable, DateTimeInterface, DateTimeZone;
|
||||
|
||||
class Dates
|
||||
{
|
||||
/** Minutes in a day */
|
||||
private const A_DAY = 1_440;
|
||||
|
||||
/** Minutes in two days(-ish) */
|
||||
private const ALMOST_2_DAYS = 2_520;
|
||||
|
||||
/** Minutes in a month */
|
||||
private const A_MONTH = 43_200;
|
||||
|
||||
/** Minutes in two months */
|
||||
private const TWO_MONTHS = 86_400;
|
||||
|
||||
/**
|
||||
* Get a UTC-referenced current date/time
|
||||
*
|
||||
* @return DateTimeImmutable The current date/time with UTC reference
|
||||
*/
|
||||
public static function now(): DateTimeImmutable
|
||||
{
|
||||
return new DateTimeImmutable(timezone: new DateTimeZone('Etc/UTC'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the distance between two instants in approximate English terms
|
||||
*
|
||||
* @param DateTimeInterface $startOn The starting date/time for the comparison
|
||||
* @param DateTimeInterface $endOn THe ending date/time for the comparison
|
||||
* @return string The formatted interval
|
||||
*/
|
||||
public static function formatDistance(DateTimeInterface $startOn, DateTimeInterface $endOn): string
|
||||
{
|
||||
$diff = $startOn->diff($endOn);
|
||||
$minutes =
|
||||
$diff->i + ($diff->h * 60) + ($diff->d * 60 * 24) + ($diff->m * 60 * 24 * 30) + ($diff->y * 60 * 24 * 365);
|
||||
$months = round($minutes / self::A_MONTH);
|
||||
$years = $months / 12;
|
||||
[ $format, $number ] = match (true) {
|
||||
$minutes < 1 => [ DistanceFormat::LessThanXMinutes, 1 ],
|
||||
$minutes < 45 => [ DistanceFormat::XMinutes, $minutes ],
|
||||
$minutes < 90 => [ DistanceFormat::AboutXHours, 1 ],
|
||||
$minutes < self::A_DAY => [ DistanceFormat::AboutXHours, round($minutes / 60) ],
|
||||
$minutes < self::ALMOST_2_DAYS => [ DistanceFormat::XDays, 1 ],
|
||||
$minutes < self::A_MONTH => [ DistanceFormat::XDays, round($minutes / self::A_DAY) ],
|
||||
$minutes < self::TWO_MONTHS => [ DistanceFormat::AboutXMonths, round($minutes / self::A_MONTH) ],
|
||||
$months < 12 => [ DistanceFormat::XMonths, round($minutes / self::A_MONTH) ],
|
||||
$months % 12 < 3 => [ DistanceFormat::AboutXYears, $years ],
|
||||
$months % 12 < 9 => [ DistanceFormat::OverXYears, $years ],
|
||||
default => [ DistanceFormat::AlmostXYears, $years + 1 ],
|
||||
};
|
||||
|
||||
$relativeWords = sprintf(DistanceFormat::format($format, $number == 1), $number);
|
||||
return $startOn > $endOn ? "$relativeWords ago" : "in $relativeWords";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal;
|
||||
|
||||
/**
|
||||
* The different distance formats supported
|
||||
*/
|
||||
enum DistanceFormat
|
||||
{
|
||||
case LessThanXMinutes;
|
||||
case XMinutes;
|
||||
case AboutXHours;
|
||||
case XHours;
|
||||
case XDays;
|
||||
case AboutXWeeks;
|
||||
case XWeeks;
|
||||
case AboutXMonths;
|
||||
case XMonths;
|
||||
case AboutXYears;
|
||||
case XYears;
|
||||
case OverXYears;
|
||||
case AlmostXYears;
|
||||
|
||||
/**
|
||||
* Return the formatting string for the given format and number
|
||||
*
|
||||
* @param DistanceFormat $it The distance format
|
||||
* @param bool $singular If true, returns the singular version; if false (default), returns the plural version
|
||||
* @return string The format string
|
||||
*/
|
||||
public static function format(DistanceFormat $it, bool $singular = false): string
|
||||
{
|
||||
return match ($it) {
|
||||
self::LessThanXMinutes => $singular ? 'less than a minute' : 'less than %d minutes',
|
||||
self::XMinutes => $singular ? 'a minute' : '%d minutes',
|
||||
self::AboutXHours => $singular ? 'about an hour' : 'about %d hours',
|
||||
self::XHours => $singular ? 'an hour' : '%d hours',
|
||||
self::XDays => $singular ? 'a day' : '%d days',
|
||||
self::AboutXWeeks => $singular ? 'about a week' : 'about %d weeks',
|
||||
self::XWeeks => $singular ? 'a week' : '%d weeks',
|
||||
self::AboutXMonths => $singular ? 'about a month' : 'about %d months',
|
||||
self::XMonths => $singular ? 'a month' : '%d months',
|
||||
self::AboutXYears => $singular ? 'about a year' : 'about %d years',
|
||||
self::XYears => $singular ? 'a year' : '%d years',
|
||||
self::OverXYears => $singular ? 'over a year' : 'over %d years',
|
||||
self::AlmostXYears => $singular ? 'almost a year' : 'almost %d years',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PgDocuments;
|
||||
|
||||
use PgSql\Connection;
|
||||
|
||||
/**
|
||||
* Document table configuration
|
||||
*/
|
||||
class Configuration
|
||||
{
|
||||
/** @var string $connectionString The connection string to use when establishing a database connection */
|
||||
public static string $connectionString = '';
|
||||
|
||||
/** @var ?Connection $pgConn The active connection */
|
||||
private static ?Connection $pgConn = null;
|
||||
|
||||
/** @var ?string $startUp The name of a function to run on first connection to the database */
|
||||
public static ?string $startUp = null;
|
||||
|
||||
/** @var string $keyName The key name for document IDs (default "id") */
|
||||
public static string $keyName = 'id';
|
||||
|
||||
/**
|
||||
* Ensure that the connection string is set, either explicitly, by environment variables, or with defaults
|
||||
*/
|
||||
private static function ensureConnectionString(): void
|
||||
{
|
||||
if (self::$connectionString == "") {
|
||||
$host = $_ENV['PGDOC_HOST'] ?? 'localhost';
|
||||
$port = $_ENV['PGDOC_PORT'] ?? 5432;
|
||||
$db = $_ENV['PGDOC_DB'] ?? 'postgres';
|
||||
$user = $_ENV['PGDOC_USER'] ?? 'postgres';
|
||||
$pass = $_ENV['PGDOC_PASS'] ?? 'postgres';
|
||||
$opts = $_ENV['PGDOC_OPTS'] ?? '';
|
||||
self::$connectionString = "host=$host port=$port dbname=$db user=$user password=$pass"
|
||||
. ($opts ? " options='$opts'" : '');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A no-op function to force this file to be autoloaded if no explicit configuration is required
|
||||
*/
|
||||
public static function init() { }
|
||||
|
||||
/**
|
||||
* Get the PostgreSQL connection, connecting on first request
|
||||
*
|
||||
* @return Connection The open PostgreSQL connection
|
||||
*/
|
||||
public static function getPgConn(): Connection
|
||||
{
|
||||
if (is_null(self::$pgConn)) {
|
||||
self::ensureConnectionString();
|
||||
self::$pgConn = pg_connect(self::$connectionString);
|
||||
}
|
||||
return self::$pgConn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the PostgreSQL connection if it is open
|
||||
*/
|
||||
public static function closeConn(): void
|
||||
{
|
||||
if (!is_null(self::$pgConn)) {
|
||||
pg_close(self::$pgConn);
|
||||
self::$pgConn = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
require('functions.php');
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PgDocuments;
|
||||
|
||||
use PgSql\Result;
|
||||
|
||||
/**
|
||||
* Methods to define tables and indexes for document tables
|
||||
*/
|
||||
class Definition
|
||||
{
|
||||
/**
|
||||
* Create a statement to create a document table
|
||||
*
|
||||
* @param string $name The name of the table to create
|
||||
* @return string A `CREATE TABLE` statement for the document table
|
||||
*/
|
||||
public static function createTable(string $name): string
|
||||
{
|
||||
return "CREATE TABLE IF NOT EXISTS $name (data JSONB NOT NULL)";
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a statement to create a key for a document table
|
||||
*
|
||||
* @param string $tableName The table (or schema/table) for which a key should be created
|
||||
* @return string A `CREATE INDEX` statement for a unique key for the document table
|
||||
*/
|
||||
public static function createKey(string $tableName): string
|
||||
{
|
||||
return sprintf('CREATE UNIQUE INDEX IF NOT EXISTS idx_%s_key ON %s ((data -> \'%s\'))',
|
||||
self::extractTable($tableName), $tableName, Configuration::$keyName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a statement to create an index on a document table
|
||||
*
|
||||
* @param string $name The name of the table for which the index should be created
|
||||
* @param DocumentIndex $type The type of index to create
|
||||
* @return string A `CREATE INDEX` statement for the given table
|
||||
*/
|
||||
public static function createIndex(string $name, DocumentIndex $type): string
|
||||
{
|
||||
return sprintf('CREATE INDEX IF NOT EXISTS idx_%s ON %s USING GIN (data%s)',
|
||||
self::extractTable($name), $name, $type == DocumentIndex::Full ? '' : ' jsonb_path_ops');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the given document table exists
|
||||
*
|
||||
* @param string $tableName The name of the table
|
||||
*/
|
||||
public static function ensureTable(string $tableName): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query(pg_conn(), self::createTable($tableName));
|
||||
if ($result) pg_free_result($result);
|
||||
$result = pg_query(pg_conn(), self::createKey($tableName));
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure an index on the given document table exists
|
||||
*
|
||||
* @param string $name The name of the table for which the index should be created
|
||||
* @param DocumentIndex $type The type of index to create
|
||||
*/
|
||||
public static function ensureIndex(string $name, DocumentIndex $type): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query(pg_conn(), self::createIndex($name, $type));
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract just the table name from a possible `schema.table` name
|
||||
*
|
||||
* @param string $name The name of the table, possibly including the schema
|
||||
* @return string The table name
|
||||
*/
|
||||
private static function extractTable(string $name): string
|
||||
{
|
||||
$schemaAndTable = explode('.', $name);
|
||||
return end($schemaAndTable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PgDocuments;
|
||||
|
||||
use Exception;
|
||||
use JsonMapper;
|
||||
use PgSql\Result;
|
||||
|
||||
/** Document manipulation functions */
|
||||
class Document
|
||||
{
|
||||
/** JSON Mapper instance to use for creating a domain type instance from a document */
|
||||
private static ?JsonMapper $mapper = null;
|
||||
|
||||
/**
|
||||
* Map a domain type from the JSON document retrieved
|
||||
*
|
||||
* @param string $columnName The name of the column from the database
|
||||
* @param array $result An associative array with a single result to be mapped
|
||||
* @param class-string<Type> $className The name of the class onto which the JSON will be mapped
|
||||
* @return Type The domain type
|
||||
*/
|
||||
public static function mapDocFromJson(string $columnName, array $result, string $className): mixed
|
||||
{
|
||||
if (is_null(self::$mapper)) {
|
||||
self::$mapper = new JsonMapper();
|
||||
}
|
||||
|
||||
$mapped = new $className();
|
||||
self::$mapper->map(json_decode($result[$columnName]), $mapped);
|
||||
return $mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a domain type from the JSON document retrieved
|
||||
*
|
||||
* @param array $result An associative array with a single result to be mapped
|
||||
* @param class-string<Type> $className The name of the class onto which the JSON will be mapped
|
||||
* @return Type The domain type
|
||||
*/
|
||||
public static function mapFromJson(array $result, string $className): mixed
|
||||
{
|
||||
return self::mapDocFromJson('data', $result, $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a document-focused statement that does not return results
|
||||
*
|
||||
* @param string $query The query to be executed
|
||||
* @param array|object $document The array or object representing the document
|
||||
* @throws Exception If the document's ID is null
|
||||
*/
|
||||
private static function executeNonQuery(string $query, array|object $document): void
|
||||
{
|
||||
$docId = is_array($document)
|
||||
? $document[Configuration::$keyName]
|
||||
: get_object_vars($document)[Configuration::$keyName];
|
||||
if (is_null($docId)) throw new Exception('PgDocument: ID cannot be NULL');
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $query, [ $docId, Query::jsonbDocParam($document) ]);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a document
|
||||
*
|
||||
* @param string $tableName The name of the table into which a document should be inserted
|
||||
* @param array|object $document The array or object representing the document
|
||||
*/
|
||||
public static function insert(string $tableName, array|object $document): void
|
||||
{
|
||||
self::executeNonQuery(Query::insert($tableName), $document);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save (upsert) a document
|
||||
*
|
||||
* @param string $tableName The name of the table into which a document should be inserted
|
||||
* @param array|object $document The array or object representing the document
|
||||
*/
|
||||
public static function save(string $tableName, array|object $document): void
|
||||
{
|
||||
self::executeNonQuery(Query::save($tableName), $document);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a count query, returning the `it` parameter of that query as an integer
|
||||
*
|
||||
* @param string $sql The SQL query that will return a count
|
||||
* @param array $params Parameters needed for that query
|
||||
* @return int The count of matching rows for the query
|
||||
*/
|
||||
private static function runCount(string $sql, array $params): int
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||
if (!$result) return -1;
|
||||
$count = intval(pg_fetch_assoc($result)['it']);
|
||||
pg_free_result($result);
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count all documents in a table
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be counted
|
||||
* @return int The number of documents in the table
|
||||
*/
|
||||
public static function countAll(string $tableName): int
|
||||
{
|
||||
return self::runCount(Query::countAll($tableName), []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count documents in a table by JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be counted
|
||||
* @param array|object $criteria The criteria for the JSON containment query
|
||||
* @return int The number of documents in the table matching the JSON containment query
|
||||
*/
|
||||
public static function countByContains(string $tableName, array|object $criteria): int
|
||||
{
|
||||
return self::runCount(Query::countByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count documents in a table by JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be counted
|
||||
* @param string $jsonPath The JSON Path to be matched
|
||||
* @return int The number of documents in the table matching the JSON Path
|
||||
*/
|
||||
public static function countByJsonPath(string $tableName, string $jsonPath): int
|
||||
{
|
||||
return self::runCount(Query::countByJsonPath($tableName), [ $jsonPath ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an existence query (returning the `it` parameter of that query)
|
||||
*
|
||||
* @param string $sql The SQL query that will return existence
|
||||
* @param array $params Parameters needed for that query
|
||||
* @return bool The result of the existence query
|
||||
*/
|
||||
private static function runExists(string $sql, array $params): bool
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||
if (!$result) return false;
|
||||
$exists = boolval(pg_fetch_assoc($result)['it']);
|
||||
pg_free_result($result);
|
||||
return $exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a document exists for the given ID
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @param string $docId The ID of the document whose existence should be checked
|
||||
* @return bool True if the document exists, false if not
|
||||
*/
|
||||
public static function existsById(string $tableName, string $docId): bool
|
||||
{
|
||||
return self::runExists(Query::existsById($tableName), [ $docId ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if documents exist by JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @param array|object $criteria The criteria for the JSON containment query
|
||||
* @return bool True if any documents in the table match the JSON containment query, false if not
|
||||
*/
|
||||
public static function existsByContains(string $tableName, array|object $criteria): bool
|
||||
{
|
||||
return self::runExists(Query::existsByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if documents exist by JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @param string $jsonPath The JSON Path to be matched
|
||||
* @return bool True if any documents in the table match the JSON Path, false if not
|
||||
*/
|
||||
public static function existsByJsonPath(string $tableName, string $jsonPath): bool
|
||||
{
|
||||
return self::runExists(Query::existsByJsonPath($tableName), [ $jsonPath ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a query, mapping the results to an array of domain type objects
|
||||
*
|
||||
* @param string $sql The query to be run
|
||||
* @param array $params The parameters for the query
|
||||
* @param class-string<Type> $className The type of document to be mapped
|
||||
* @return array<Type> The documents matching the query
|
||||
*/
|
||||
private static function runListQuery(string $sql, array $params, string $className): array
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||
try {
|
||||
if (!$result || pg_result_status($result) == PGSQL_EMPTY_QUERY) return [];
|
||||
return array_map(fn ($it) => self::mapFromJson($it, $className), pg_fetch_all($result));
|
||||
} finally {
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all documents in a table
|
||||
*
|
||||
* @param string $tableName The table from which all documents should be retrieved
|
||||
* @param class-string<Type> $className The type of document to be retrieved
|
||||
* @return array<Type> An array of documents
|
||||
*/
|
||||
public static function findAll(string $tableName, string $className): array
|
||||
{
|
||||
return self::runListQuery(Query::selectFromTable($tableName), [], $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a document by its ID
|
||||
*
|
||||
* @param string $tableName The table from which a document should be retrieved
|
||||
* @param string $docId The ID of the document to retrieve
|
||||
* @param class-string<Type> $className The type of document to retrieve
|
||||
* @return Type|null The document, or null if it is not found
|
||||
*/
|
||||
public static function findById(string $tableName, string $docId, string $className): mixed
|
||||
{
|
||||
$results = self::runListQuery(Query::findById($tableName), [ $docId ], $className);
|
||||
return $results ? $results[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve documents in a table via JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be retrieved
|
||||
* @param array|object $criteria The criteria for the JSON containment query
|
||||
* @param class-string<Type> $className The type of document to be retrieved
|
||||
* @return array<Type> Documents matching the JSON containment query
|
||||
*/
|
||||
public static function findByContains(string $tableName, array|object $criteria, string $className): array
|
||||
{
|
||||
return self::runListQuery(Query::findByContains($tableName), [ Query::jsonbDocParam($criteria) ], $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the first matching document via JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be retrieved
|
||||
* @param array|object $criteria The criteria for the JSON containment query
|
||||
* @param class-string<Type> $className The type of document to be retrieved
|
||||
* @return Type|null The document, or null if none match
|
||||
*/
|
||||
public static function findFirstByContains(string $tableName, array|object $criteria, string $className): mixed
|
||||
{
|
||||
$results = self::runListQuery(Query::findByContains($tableName) . ' LIMIT 1',
|
||||
[ Query::jsonbDocParam($criteria) ], $className);
|
||||
return $results ? $results[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve documents in a table via JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be retrieved
|
||||
* @param string $jsonPath The JSON Path to be matched
|
||||
* @param class-string<Type> $className The type of document to be retrieved
|
||||
* @return array<Type> Documents matching the JSON Path
|
||||
*/
|
||||
public static function findByJsonPath(string $tableName, string $jsonPath, string $className): array
|
||||
{
|
||||
return self::runListQuery(Query::findByJsonPath($tableName), [ $jsonPath ], $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the first matching document via JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be retrieved
|
||||
* @param string $jsonPath The JSON Path to be matched
|
||||
* @param class-string<Type> $className The type of document to be retrieved
|
||||
* @return Type|null The document, or null if none match
|
||||
*/
|
||||
public static function findFirstByJsonPath(string $tableName, string $jsonPath, string $className): mixed
|
||||
{
|
||||
$results = self::runListQuery(Query::findByJsonPath($tableName) . ' LIMIT 1', [ $jsonPath ], $className);
|
||||
return $results ? $results[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a full document
|
||||
*
|
||||
* @param string $tableName The table in which the document should be updated
|
||||
* @param array|object $document The document to be updated
|
||||
*/
|
||||
public static function updateFull(string $tableName, array|object $document): void
|
||||
{
|
||||
self::executeNonQuery(Query::updateFull($tableName), $document);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a partial document by its ID
|
||||
*
|
||||
* @param string $tableName The table in which the document should be updated
|
||||
* @param array|object $document The partial document to be updated
|
||||
*/
|
||||
public static function updatePartialById(string $tableName, array|object $document): void
|
||||
{
|
||||
self::executeNonQuery(Query::updatePartialById($tableName), $document);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update partial documents by JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The table in which documents should be updated
|
||||
* @param array|object $criteria The JSON containment criteria
|
||||
* @param array|object $document The document to be updated
|
||||
*/
|
||||
public static function updatePartialByContains(string $tableName, array|object $criteria,
|
||||
array|object $document): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), Query::updatePartialByContains($tableName),
|
||||
[ Query::jsonbDocParam($criteria), Query::jsonbDocParam($document) ]);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update partial documents by JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The table in which documents should be updated
|
||||
* @param string $jsonPath The JSON Path to be matched
|
||||
* @param array|object $document The document to be updated
|
||||
*/
|
||||
public static function updatePartialByJsonPath(string $tableName, string $jsonPath, array|object $document): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), Query::updatePartialByJsonPath($tableName),
|
||||
[ $jsonPath, Query::jsonbDocParam($document) ]);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a document by its ID
|
||||
*
|
||||
* @param string $tableName The table from which a document should be deleted
|
||||
* @param string $docId The ID of the document to be deleted
|
||||
*/
|
||||
public static function deleteById(string $tableName, string $docId): void
|
||||
{
|
||||
self::executeNonQuery(Query::deleteById($tableName), [ Configuration::$keyName => $docId ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete documents by JSON containment `@>`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be deleted
|
||||
* @param array|object $criteria The criteria for the JSON containment query
|
||||
*/
|
||||
public static function deleteByContains(string $tableName, array|object $criteria): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), Query::deleteByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete documents by JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The table from which documents should be deleted
|
||||
* @param string $jsonPath The JSON Path expression to be matched
|
||||
*/
|
||||
public static function deleteByJsonPath(string $tableName, string $jsonPath): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), Query::deleteByJsonPath($tableName), [ $jsonPath ]);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve documents via a custom query and mapping
|
||||
*
|
||||
* @param string $sql The SQL query to execute
|
||||
* @param array $params A positional array of parameters for the SQL query
|
||||
* @param callable $mapFunc A function that expects an associative array and returns a value of the desired type
|
||||
* @param class-string<Type> $className The type of document to be mapped
|
||||
* @return array<Type> The documents matching the query
|
||||
*/
|
||||
public static function customList(string $sql, array $params, string $className, callable $mapFunc): array
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||
try {
|
||||
if (!$result || pg_result_status($result) == PGSQL_EMPTY_QUERY) return [];
|
||||
return array_map(fn ($it) => $mapFunc($it, $className), pg_fetch_all($result));
|
||||
} finally {
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a document via a custom query and mapping
|
||||
*
|
||||
* @param string $sql The SQL query to execute ("LIMIT 1" will be appended)
|
||||
* @param array $params A positional array of parameters for the SQL query
|
||||
* @param callable $mapFunc A function that expects an associative array and returns a value of the desired type
|
||||
* @param class-string<Type> $className The type of document to be mapped
|
||||
* @return ?Type The document matching the query, or null if none is found
|
||||
*/
|
||||
public static function customSingle(string $sql, array $params, string $className, callable $mapFunc): mixed
|
||||
{
|
||||
$results = self::customList("$sql LIMIT 1", $params, $className, $mapFunc);
|
||||
return $results ? $results[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a custom query that does not return a result
|
||||
*
|
||||
* @param string $sql The SQL query to execute
|
||||
* @param array $params A positional array of parameters for the SQL query
|
||||
*/
|
||||
public static function customNonQuery(string $sql, array $params): void
|
||||
{
|
||||
/** @var Result|bool $result */
|
||||
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||
if ($result) pg_free_result($result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PgDocuments;
|
||||
|
||||
/** The type of index to generate for the document */
|
||||
enum DocumentIndex
|
||||
{
|
||||
/** A GIN index with standard operations (all operators supported) */
|
||||
case Full;
|
||||
|
||||
/** A GIN index with JSONPath operations (optimized for `@>`, `@?`, `@@` operators) */
|
||||
case Optimized;
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PgDocuments;
|
||||
|
||||
/** Query construction functions */
|
||||
class Query
|
||||
{
|
||||
/**
|
||||
* Create a `SELECT` clause to retrieve the document data from the given table
|
||||
*
|
||||
* @param string $tableName The name of the table from which documents should be selected
|
||||
* @return string A `SELECT` clause for the given table
|
||||
*/
|
||||
public static function selectFromTable(string $tableName): string
|
||||
{
|
||||
return "SELECT data FROM $tableName";
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `WHERE` clause fragment to implement a key check condition
|
||||
*
|
||||
* @param string $paramName The name of the parameter to be replaced when the query is executed
|
||||
* @return string A `WHERE` clause fragment with the named key and parameter
|
||||
*/
|
||||
public static function whereById(string $paramName): string
|
||||
{
|
||||
return sprintf("data -> '%s' = %s", Configuration::$keyName, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `WHERE` clause fragment to implement a @> (JSON contains) condition
|
||||
*
|
||||
* @param string $paramName The name of the parameter for the contains clause
|
||||
* @return string A `WHERE` clause fragment with the named parameter
|
||||
*/
|
||||
public static function whereDataContains(string $paramName): string
|
||||
{
|
||||
return "data @> $paramName";
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `WHERE` clause fragment to implement a @? (JSON Path match) condition
|
||||
*
|
||||
* @param string $paramName THe name of the parameter for the JSON Path match
|
||||
* @return string A `WHERE` clause fragment with the named parameter
|
||||
*/
|
||||
public static function whereJsonPathMatches(string $paramName): string
|
||||
{
|
||||
return "data @? $paramName::jsonpath";
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSONB document parameter
|
||||
*
|
||||
* @param array|object $it The array or object to become a JSONB parameter
|
||||
* @return string The encoded JSON
|
||||
*/
|
||||
public static function jsonbDocParam(array|object $it): string
|
||||
{
|
||||
return json_encode($it);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to insert a document
|
||||
*
|
||||
* @param string $tableName The name of the table into which the document will be inserted
|
||||
* @return string The `INSERT` statement (with `$1` parameter defined for the document)
|
||||
*/
|
||||
public static function insert(string $tableName): string
|
||||
{
|
||||
return sprintf('INSERT INTO %s (data) VALUES ($1)', $tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
||||
*
|
||||
* @param string $tableName The name of the table into which the document will be saved
|
||||
* @return string The `INSERT`/`ON CONFLICT DO UPDATE` statement (with `$1` parameter defined for the document)
|
||||
*/
|
||||
public static function save(string $tableName): string
|
||||
{
|
||||
return sprintf('INSERT INTO %s (data) VALUES ($1) ON CONFLICT (data) DO UPDATE SET data = EXCLUDED.data',
|
||||
$tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to count documents in a table
|
||||
*
|
||||
* @param string $tableName The name of the table for which documents should be counted
|
||||
* @param string $where The condition for which documents should be counted
|
||||
* @return string A `SELECT` statement to obtain the count of documents for the given table
|
||||
*/
|
||||
private static function countQuery(string $tableName, string $where): string
|
||||
{
|
||||
return "SELECT COUNT(*) AS it FROM $tableName WHERE $where";
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to count all documents in a table
|
||||
*
|
||||
* @param string $tableName The name of the table whose rows will be counted
|
||||
* @return string A `SELECT` statement to obtain the count of all documents in the given table
|
||||
*/
|
||||
public static function countAll(string $tableName): string
|
||||
{
|
||||
return self::countQuery($tableName, '1 = 1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to count matching documents using a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table from which the count should be obtained
|
||||
* @return string A `SELECT` statement to obtain the count of documents via JSON containment
|
||||
*/
|
||||
public static function countByContains(string $tableName): string
|
||||
{
|
||||
return self::countQuery($tableName, self::whereDataContains('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to count matching documents using a JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table from which the count should be obtained
|
||||
* @return string A `SELECT` statement to obtain the count of documents via JSON Path match
|
||||
*/
|
||||
public static function countByJsonPath(string $tableName): string
|
||||
{
|
||||
return self::countQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to check document existence
|
||||
*
|
||||
* @param string $tableName The name of the table in which document existence should be checked
|
||||
* @param string $where The criteria for which document existence should be checked
|
||||
* @return string A `SELECT` statement to check document existence for the given criteria
|
||||
*/
|
||||
private static function existsQuery(string $tableName, string $where): string
|
||||
{
|
||||
return "SELECT EXISTS (SELECT 1 FROM $tableName WHERE $where) AS it";
|
||||
}
|
||||
/**
|
||||
* Query to determine if a document exists for the given ID
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @return string A `SELECT` statement to check existence of a document by its ID
|
||||
*/
|
||||
public static function existsById(string $tableName): string
|
||||
{
|
||||
return self::existsQuery($tableName, self::whereById('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to determine if documents exist using a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @return string A `SELECT` statement to check existence of a document by JSON containment
|
||||
*/
|
||||
public static function existsByContains(string $tableName): string
|
||||
{
|
||||
return self::existsQuery($tableName, self::whereDataContains('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to determine if documents exist using a JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table in which existence should be checked
|
||||
* @return string A `SELECT` statement to check existence of a document by JSON Path match
|
||||
*/
|
||||
public static function existsByJsonPath(string $tableName): string
|
||||
{
|
||||
return self::existsQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to retrieve a document by its ID
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be retrieved
|
||||
* @return string A `SELECT` statement to retrieve a document by its ID
|
||||
*/
|
||||
public static function findById(string $tableName): string
|
||||
{
|
||||
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereById('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to retrieve documents using a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be retrieved
|
||||
* @return string A `SELECT` statement to retrieve documents by JSON containment
|
||||
*/
|
||||
public static function findByContains(string $tableName): string
|
||||
{
|
||||
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereDataContains('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to retrieve documents using a JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be retrieved
|
||||
* @return string A `SELECT` statement to retrieve a documents by JSON Path match
|
||||
*/
|
||||
public static function findByJsonPath(string $tableName): string
|
||||
{
|
||||
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereJsonPathMatches('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to update a document, replacing the existing document
|
||||
*
|
||||
* @param string $tableName The name of the table in which a document should be updated
|
||||
* @return string An `UPDATE` statement to update a document by its ID
|
||||
*/
|
||||
public static function updateFull(string $tableName): string
|
||||
{
|
||||
return sprintf('UPDATE %s SET data = $2 WHERE %s', $tableName, self::whereById('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to apply a partial update to a document
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be updated
|
||||
* @param string $where The `WHERE` clause specifying which documents should be updated
|
||||
* @return string An `UPDATE` statement to update a partial document ($1 is ID, $2 is document)
|
||||
*/
|
||||
private static function updatePartial(string $tableName, string $where): string
|
||||
{
|
||||
return sprintf('UPDATE %s SET data = data || $2 WHERE %s', $tableName, $where);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to update a document, merging the existing document with the one provided
|
||||
*
|
||||
* @param string $tableName The name of the table in which a document should be updated
|
||||
* @return string An `UPDATE` statement to update a document by its ID
|
||||
*/
|
||||
public static function updatePartialById(string $tableName): string
|
||||
{
|
||||
return self::updatePartial($tableName, self::whereById('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to update partial documents matching a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be updated
|
||||
* @return string An `UPDATE` statement to update documents by JSON containment
|
||||
*/
|
||||
public static function updatePartialByContains(string $tableName): string
|
||||
{
|
||||
return self::updatePartial($tableName, self::whereDataContains('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to update partial documents matching a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table in which documents should be updated
|
||||
* @return string An `UPDATE` statement to update documents by JSON Path match
|
||||
*/
|
||||
public static function updatePartialByJsonPath(string $tableName): string
|
||||
{
|
||||
return self::updatePartial($tableName, self::whereJsonPathMatches('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to delete documents
|
||||
*
|
||||
* @param string $tableName The name of the table from which documents should be deleted
|
||||
* @param string $where The criteria by which documents should be deleted
|
||||
* @return string A `DELETE` statement to delete documents in the specified table
|
||||
*/
|
||||
private static function deleteQuery(string $tableName, string $where): string
|
||||
{
|
||||
return "DELETE FROM $tableName WHERE $where";
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to delete a document by its ID
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be deleted
|
||||
* @return string A `DELETE` statement to delete a document by its ID
|
||||
*/
|
||||
public static function deleteById(string $tableName): string
|
||||
{
|
||||
return self::deleteQuery($tableName, self::whereById('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to delete documents using a JSON containment query `@>`
|
||||
*
|
||||
* @param string $tableName The name of the table from which documents should be deleted
|
||||
* @return string A `DELETE` statement to delete documents by JSON containment
|
||||
*/
|
||||
public static function deleteByContains(string $tableName): string
|
||||
{
|
||||
return self::deleteQuery($tableName, self::whereDataContains('$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to delete documents using a JSON Path match `@?`
|
||||
*
|
||||
* @param string $tableName The name of the table from which documents should be deleted
|
||||
* @return string A `DELETE` statement to delete documents by JSON Path match
|
||||
*/
|
||||
public static function deleteByJsonPath(string $tableName): string
|
||||
{
|
||||
return self::deleteQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
use BitBadger\PgDocuments\Configuration;
|
||||
use PgSql\Connection;
|
||||
|
||||
if (!function_exists('pg_conn')) {
|
||||
/**
|
||||
* Return the active PostgreSQL connection
|
||||
*
|
||||
* @return Connection The data connection from the configuration
|
||||
*/
|
||||
function pg_conn(): Connection
|
||||
{
|
||||
return Configuration::getPgConn();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
class AsOf
|
||||
{
|
||||
/** The "as of" date/time */
|
||||
public DateTimeImmutable $asOf;
|
||||
|
||||
/**
|
||||
* Sort an as-of item from oldest to newest
|
||||
*
|
||||
* @param AsOf $a The first item to compare
|
||||
* @param AsOf $b The second item to compare
|
||||
* @return int 0 if they are equal, -1 if A is earlier than B, or 1 if B is earlier than A
|
||||
*/
|
||||
public static function oldestToNewest(AsOf $a, AsOf $b): int
|
||||
{
|
||||
return $a->asOf == $b->asOf ? 0 : ($a->asOf < $b->asOf ? -1 : 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort an as-of item from newest to oldest
|
||||
*
|
||||
* @param AsOf $a The first item to compare
|
||||
* @param AsOf $b The second item to compare
|
||||
* @return int 0 if they are equal, -1 if B is earlier than A, or 1 if A is earlier than B
|
||||
*/
|
||||
public static function newestToOldest(AsOf $a, AsOf $b): int
|
||||
{
|
||||
return $a->asOf == $b->asOf ? 0 : ($a->asOf > $b->asOf ? -1 : 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
/**
|
||||
* A record of action taken on a prayer request, including updates to its text
|
||||
*/
|
||||
class History extends AsOf
|
||||
{
|
||||
/** The action taken that generated this history entry */
|
||||
public RequestAction $status = RequestAction::Created;
|
||||
|
||||
/** The text of the update, if applicable */
|
||||
public ?string $text = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->asOf = unix_epoch();
|
||||
}
|
||||
|
||||
public function isCreated(): bool
|
||||
{
|
||||
return $this->status == RequestAction::Created;
|
||||
}
|
||||
|
||||
public function isPrayed(): bool
|
||||
{
|
||||
return $this->status == RequestAction::Prayed;
|
||||
}
|
||||
|
||||
public function isAnswered(): bool
|
||||
{
|
||||
return $this->status == RequestAction::Answered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use DateTimeImmutable, DateTimeZone;
|
||||
|
||||
/**
|
||||
* A prayer request, along with calculated fields, for use in displaying journal lists
|
||||
*/
|
||||
class JournalRequest extends AsOf
|
||||
{
|
||||
/** The ID of the prayer request */
|
||||
public string $id = '';
|
||||
|
||||
/** The ID of the user to whom the prayer request belongs */
|
||||
public string $userId = '';
|
||||
|
||||
/** The current text of the request */
|
||||
public string $text = '';
|
||||
|
||||
/** The date/time this request was last marked as prayed */
|
||||
public ?DateTimeImmutable $lastPrayed = null;
|
||||
|
||||
/** The last action taken on this request */
|
||||
public RequestAction $lastAction = RequestAction::Created;
|
||||
|
||||
/** When this request will be shown again after having been snoozed */
|
||||
public ?DateTimeImmutable $snoozedUntil = null;
|
||||
|
||||
/** When this request will be show again after a non-immediate recurrence */
|
||||
public ?DateTimeImmutable $showAfter = null;
|
||||
|
||||
/** The type of recurrence for this request */
|
||||
public RecurrenceType $recurrenceType = RecurrenceType::Immediate;
|
||||
|
||||
/** The units for non-immediate recurrence */
|
||||
public ?int $recurrence = null;
|
||||
|
||||
/**
|
||||
* The history for this request
|
||||
* @var History[] $history
|
||||
*/
|
||||
public array $history = [];
|
||||
|
||||
/**
|
||||
* The notes for this request
|
||||
* @var Note[] $notes
|
||||
*/
|
||||
public array $notes = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param ?Request $req The request off which this journal request should be populated
|
||||
* @param bool $full Whether to include history and notes (true) or exclude them (false)
|
||||
*/
|
||||
public function __construct(?Request $req = null, bool $full = false)
|
||||
{
|
||||
if (is_null($req)) {
|
||||
$this->asOf = unix_epoch();
|
||||
$this->lastPrayed = null;
|
||||
} else {
|
||||
$this->id = $req->id;
|
||||
$this->userId = $req->userId;
|
||||
$this->snoozedUntil = $req->snoozedUntil;
|
||||
$this->showAfter = $req->showAfter;
|
||||
$this->recurrenceType = $req->recurrenceType;
|
||||
$this->recurrence = $req->recurrence;
|
||||
|
||||
usort($req->history, AsOf::newestToOldest(...));
|
||||
$this->asOf = $req->history[array_key_first($req->history)]->asOf;
|
||||
$lastText = array_filter($req->history, fn (History $it) => !is_null($it->text));
|
||||
$this->text = $lastText[array_key_first($lastText)]->text;
|
||||
$lastPrayed = array_filter($req->history, fn (History $it) => $it->isPrayed());
|
||||
if ($lastPrayed) $this->lastPrayed = $lastPrayed[array_key_first($lastPrayed)]->asOf;
|
||||
|
||||
if ($full) {
|
||||
usort($req->notes, AsOf::newestToOldest(...));
|
||||
$this->history = $req->history;
|
||||
$this->notes = $req->notes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use DateTimeImmutable, DateTimeZone;
|
||||
|
||||
/**
|
||||
* A note entered on a prayer request
|
||||
*/
|
||||
class Note extends AsOf
|
||||
{
|
||||
/** The note */
|
||||
public string $notes = '';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->asOf = unix_epoch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* The unit to use when determining when to show a recurring request
|
||||
*/
|
||||
enum RecurrenceType implements JsonSerializable
|
||||
{
|
||||
/** The request should reappear immediately */
|
||||
case Immediate;
|
||||
|
||||
/** The request should reappear after the specified number of hours */
|
||||
case Hours;
|
||||
|
||||
/** The request should reappear after the specified number of days */
|
||||
case Days;
|
||||
|
||||
/** The request should reappear after the specified number of weeks */
|
||||
case Weeks;
|
||||
|
||||
/**
|
||||
* Serialize this enum using its name
|
||||
*/
|
||||
public function jsonSerialize(): mixed
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use Visus\Cuid2\Cuid2;
|
||||
|
||||
/**
|
||||
* A prayer request
|
||||
*/
|
||||
class Request
|
||||
{
|
||||
/** The ID for the request */
|
||||
public string $id;
|
||||
|
||||
/** The date/time the request was originally entered */
|
||||
public DateTimeImmutable $enteredOn;
|
||||
|
||||
/** The ID of the user to whom this request belongs */
|
||||
public string $userId = '';
|
||||
|
||||
/** The date/time the snooze expires for this request */
|
||||
public ?DateTimeImmutable $snoozedUntil = null;
|
||||
|
||||
/** The date/time this request should once again show as defined by recurrence */
|
||||
public ?DateTimeImmutable $showAfter = null;
|
||||
|
||||
/** The type of recurrence for this request */
|
||||
public RecurrenceType $recurrenceType = RecurrenceType::Immediate;
|
||||
|
||||
/** The units which apply to recurrences other than Immediate */
|
||||
public ?int $recurrence = null;
|
||||
|
||||
/**
|
||||
* The history for this request
|
||||
* @var History[] $history
|
||||
*/
|
||||
public array $history = [];
|
||||
|
||||
/**
|
||||
* The notes for this request
|
||||
* @var Note[] $notes
|
||||
*/
|
||||
public array $notes = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->id = (new Cuid2())->toString();
|
||||
$this->enteredOn = unix_epoch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MyPrayerJournal\Domain;
|
||||
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* An action that was taken on a request
|
||||
*/
|
||||
enum RequestAction: string implements JsonSerializable
|
||||
{
|
||||
/** The request was entered */
|
||||
case Created = 'Created';
|
||||
|
||||
/** Prayer was recorded for the request */
|
||||
case Prayed = 'Prayed';
|
||||
|
||||
/** The request was updated */
|
||||
case Updated = 'Updated';
|
||||
|
||||
/** The request was marked as answered */
|
||||
case Answered = 'Answered';
|
||||
|
||||
/**
|
||||
* Serialize this enum using its name
|
||||
*/
|
||||
public function jsonSerialize(): mixed
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 'On');
|
||||
|
||||
use Auth0\SDK\Auth0;
|
||||
use BitBadger\PgDocuments\Configuration;
|
||||
use DateTimeZone;
|
||||
use Dotenv\Dotenv;
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
Dotenv::createImmutable(__DIR__)->load();
|
||||
|
||||
/** @var Auth0 The Auth0 instance to use for the request */
|
||||
$auth0 = new Auth0([
|
||||
'domain' => $_ENV[Constants::AUTH0_DOMAIN],
|
||||
'clientId' => $_ENV[Constants::AUTH0_CLIENT_ID],
|
||||
'clientSecret' => $_ENV[Constants::AUTH0_CLIENT_SECRET],
|
||||
'cookieSecret' => $_ENV[Constants::AUTH0_COOKIE_SECRET]
|
||||
]);
|
||||
|
||||
/** @var ?object The Auth0 session for the current user */
|
||||
$session = $auth0->getCredentials();
|
||||
if (!is_null($session)) $_REQUEST[Constants::USER_ID] = $session->user[Constants::CLAIM_SUB];
|
||||
|
||||
$_REQUEST[Constants::IS_HTMX] = array_key_exists(Constants::HEADER_HX_REQUEST, $_SERVER)
|
||||
&& (!array_key_exists(Constants::HEADER_HX_HIST_REQ, $_SERVER));
|
||||
|
||||
$_REQUEST[Constants::TIME_ZONE] = new DateTimeZone(
|
||||
array_key_exists(Constants::HEADER_USER_TZ, $_SERVER) ? $_SERVER[Constants::HEADER_USER_TZ] : 'Etc/UTC');
|
||||
|
||||
$_REQUEST[Constants::VERSION] = 4;
|
||||
|
||||
Configuration::$startUp = '\MyPrayerJournal\Data::startUp';
|
||||
|
||||
/**
|
||||
* Bring in a template
|
||||
*/
|
||||
function template(string $name): void
|
||||
{
|
||||
require_once __DIR__ . "/../templates/$name.php";
|
||||
}
|
||||
|
||||
/**
|
||||
* If a user is not found, either redirect them or fail the request
|
||||
*
|
||||
* @param bool $fail Whether to fail the request (true) or redirect to log on (false - optional, default)
|
||||
*/
|
||||
function require_user(bool $fail = false): void
|
||||
{
|
||||
if (!array_key_exists(Constants::USER_ID, $_REQUEST)) {
|
||||
if ($fail) {
|
||||
http_response_code(403);
|
||||
} else {
|
||||
header(sprintf('Location: /user/log-on?%s=%s', Constants::RETURN_URL, $_SERVER[Constants::REQUEST_URI]));
|
||||
}
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a bare header for a component result
|
||||
*/
|
||||
function bare_header(): void
|
||||
{
|
||||
echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf8"><title></title></head><body>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a traditional and htmx link, and apply an active class if the link is active
|
||||
*
|
||||
* @param string $url The URL of the page to be linked
|
||||
* @param array $classNames CSS class names to be applied to the link (optional, default none)
|
||||
* @param bool $checkActive Whether to apply an active class if the route matches (optional, default false)
|
||||
*/
|
||||
function page_link(string $url, array $classNames = [], bool $checkActive = false): void
|
||||
{
|
||||
echo 'href="'. $url . '" hx-get="' . $url . '"';
|
||||
if ($checkActive && str_starts_with($_SERVER[Constants::REQUEST_URI], $url)) {
|
||||
$classNames[] = 'is-active-route';
|
||||
}
|
||||
if (!empty($classNames)) {
|
||||
echo sprintf(' class="%s"', implode(' ', $classNames));
|
||||
}
|
||||
echo ' hx-target="#top" hx-swap="innerHTML" hx-push-url="true"';
|
||||
}
|
||||
|
||||
/**
|
||||
* Close any open database connection; close the `body` and `html` tags
|
||||
*/
|
||||
function end_request(): void
|
||||
{
|
||||
Configuration::closeConn();
|
||||
echo '</body></html>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the Unix epoch
|
||||
*
|
||||
* @return DateTimeImmutable An immutable date/time as of the Unix epoch
|
||||
*/
|
||||
function unix_epoch(): DateTimeImmutable
|
||||
{
|
||||
return new DateTimeImmutable('1/1/1970', new DateTimeZone('Etc/UTC'));
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\{ Constants, Data, Dates };
|
||||
use MyPrayerJournal\Domain\JournalRequest;
|
||||
|
||||
require_user(true);
|
||||
|
||||
$requests = Data::getJournal($_REQUEST[Constants::USER_ID]);
|
||||
|
||||
bare_header();
|
||||
if ($requests) { ?>
|
||||
<section id="journalItems" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-3" hx-target="this"
|
||||
hx-swap="outerHTML" aria-label="Prayer Requests">
|
||||
<p class="mb-3 has-text-centered">
|
||||
<a <?php page_link('/request/edit?new'); ?> class="button is-light">
|
||||
<span class="material-icons">add_box</span> Add a Prayer Request
|
||||
</a>
|
||||
</p><?php
|
||||
array_walk($requests, journal_card(...)); ?>
|
||||
</section><?php
|
||||
} else {
|
||||
$_REQUEST['EMPTY_HEADING'] = 'No Active Requests';
|
||||
$_REQUEST['EMPTY_LINK'] = '/request/edit?new';
|
||||
$_REQUEST['EMPTY_BTN_TXT'] = 'Add a Request';
|
||||
$_REQUEST['EMPTY_TEXT'] = 'You have no requests to be shown; see the “Active” link above for '
|
||||
. 'snoozed or deferred requests, and the “Answered” link for answered requests';
|
||||
template('no_content');
|
||||
}
|
||||
end_request();
|
||||
|
||||
/**
|
||||
* Format the activity and relative time
|
||||
*
|
||||
* @param string $activity The activity performed (activity or prayed)
|
||||
* @param DateTimeImmutable $asOf The date/time the activity was performed
|
||||
*/
|
||||
function format_activity(string $activity, DateTimeImmutable $asOf): void
|
||||
{
|
||||
echo sprintf('last %s <span title="%s">%s</span>', $activity,
|
||||
$asOf->setTimezone($_REQUEST[Constants::TIME_ZONE])->format('l, F jS, Y/g:ia T'),
|
||||
Dates::formatDistance(Dates::now(), $asOf));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a card for a prayer request
|
||||
*
|
||||
* @param JournalRequest $req The request for which a card should be generated
|
||||
*/
|
||||
function journal_card(JournalRequest $req): void
|
||||
{
|
||||
$spacer = '<span> </span>'; ?>
|
||||
<div class="col">
|
||||
<div class="card h-100">
|
||||
<div class="card-header p-0 d-flex" role="toolbar">
|
||||
<a <?php page_link("/request/edit?{$req->id}"); ?> class="button btn-secondary" title="Edit Request">
|
||||
<span class="material-icons">edit</span>
|
||||
</a><?php echo $spacer; ?>
|
||||
<button type="button" class="btn btn-secondary" title="Add Notes" data-bs-toggle="modal"
|
||||
data-bs-target="#notesModal" hx-get="/components/request/<?php echo $req->id; ?>/add-notes"
|
||||
hx-target="#notesBody" hx-swap="innerHTML">
|
||||
<span class="material-icons">comment</span>
|
||||
</button><?php echo $spacer; ?>
|
||||
<button type="button" class="btn btn-secondary" title="Snooze Request" data-bs-toggle="modal"
|
||||
data-bs-target="#snoozeModal" hx-get="/components/request/<?php echo $req->id; ?>/snooze"
|
||||
hx-target="#snoozeBody" hx-swap="innerHTML">
|
||||
<span class="material-icons">schedule</span>
|
||||
</button>
|
||||
<div class="flex-grow-1"></div>
|
||||
<a href="/request/prayed?<?php echo $req->id; ?>" class="button btn-success w-25"
|
||||
hx-patch="/request/prayed?<?php echo $req->id; ?>" title="Mark as Prayed">
|
||||
<span class="material-icons">done</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="request-text"><?php echo htmlentities($req->text); ?></p>
|
||||
</div>
|
||||
<div class="card-footer text-end text-muted px-1 py-0">
|
||||
<em><?php
|
||||
[ $activity, $asOf ] = is_null($req->lastPrayed)
|
||||
? [ 'activity', $req->asOf ]
|
||||
: [ 'prayed', $req->lastPrayed ];
|
||||
format_activity($activity, $asOf); ?>
|
||||
</em>
|
||||
</div>
|
||||
</div>
|
||||
</div><?php
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
$_REQUEST[Constants::PAGE_TITLE] = 'Welcome';
|
||||
|
||||
template('layout/page_header'); ?>
|
||||
<main class="container">
|
||||
<p class="block"> </p>
|
||||
<p class="block">
|
||||
myPrayerJournal is a place where individuals can record their prayer requests, record that they prayed for them,
|
||||
update them as God moves in the situation, and record a final answer received on that request. It also allows
|
||||
individuals to review their answered prayers.
|
||||
</p>
|
||||
<p class="block">
|
||||
This site is open and available to the general public. To get started, simply click the “Log On”
|
||||
link above, and log on with either a Microsoft or Google account. You can also learn more about the site at the
|
||||
“Docs” link, also above.
|
||||
</p>
|
||||
</main><?php
|
||||
template('layout/page_footer');
|
||||
end_request();
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
require_user();
|
||||
|
||||
$_REQUEST[Constants::PAGE_TITLE] = "{$session->user[Constants::CLAIM_GIVEN_NAME]}’s Prayer Journal";
|
||||
|
||||
template('layout/page_header'); ?>
|
||||
<main class="container">
|
||||
<h2 class="title"><?php echo $_REQUEST[Constants::PAGE_TITLE]; ?></h2>
|
||||
<p hx-get="/components/journal-items" hx-swap="outerHTML" hx-trigger="load delay:.25s">
|
||||
Loading your prayer journal…
|
||||
</p>
|
||||
</main><?php
|
||||
template('layout/page_footer');
|
||||
end_request();
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
$_REQUEST[Constants::PAGE_TITLE] = 'Privacy Policy';
|
||||
|
||||
template('layout/page_header'); ?>
|
||||
<main class="container">
|
||||
<h2 class="title">Privacy Policy</h2>
|
||||
<h6 class="subtitle">as of May 21<sup>st</sup>, 2018</h6>
|
||||
<p class="mb-3">
|
||||
The nature of the service is one where privacy is a must. The items below will help you understand the data we
|
||||
collect, access, and store on your behalf as you use this service.
|
||||
</p>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">Third Party Services</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
myPrayerJournal utilizes a third-party authentication and identity provider. You should familiarize yourself
|
||||
with the privacy policy for
|
||||
<a href="https://auth0.com/privacy" target="_blank" rel="noopener">Auth0</a>, as well as your chosen
|
||||
provider
|
||||
(<a href="https://privacy.microsoft.com/en-us/privacystatement" target="_blank"
|
||||
rel="noopener">Microsoft</a> or
|
||||
<a href="https://policies.google.com/privacy" target="_blank" rel="noopener">Google</a>).
|
||||
</p>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">What We Collect</h3>
|
||||
</div>
|
||||
<div class="card-content">
|
||||
<h4 class="subtitle mb-3">Identifying Data</h4>
|
||||
<ul class="mb-3 mx-5">
|
||||
<li>
|
||||
• The only identifying data myPrayerJournal stores is the subscriber (“sub”) field
|
||||
from the token we receive from Auth0, once you have signed in through their hosted service. All
|
||||
information is associated with you via this field.
|
||||
</li>
|
||||
<li>
|
||||
• While you are signed in, within your browser, the service has access to your first and last
|
||||
names, along with a URL to the profile picture (provided by your selected identity provider). This
|
||||
information is not transmitted to the server, and is removed when “Log Off” is clicked.
|
||||
</li>
|
||||
</ul>
|
||||
<h4 class="subtitle mb-3">User Provided Data</h4>
|
||||
<ul class="mx-5">
|
||||
<li>
|
||||
• myPrayerJournal stores the information you provide, including the text of prayer requests,
|
||||
updates, and notes; and the date/time when certain actions are taken.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">How Your Data Is Accessed / Secured</h3>
|
||||
</div>
|
||||
<ul class="card-content">
|
||||
<li>
|
||||
• Your provided data is returned to you, as required, to display your journal or your answered
|
||||
requests. On the server, it is stored in a controlled-access database.
|
||||
</li>
|
||||
<li>
|
||||
• Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling
|
||||
manner; backups are preserved for the prior 7 days, and backups from the 1<sup>st</sup> and
|
||||
15<sup>th</sup> are preserved for 3 months. These backups are stored in a private cloud data repository.
|
||||
</li>
|
||||
<li>
|
||||
• The data collected and stored is the absolute minimum necessary for the functionality of the
|
||||
service. There are no plans to “monetize” this service, and storing the minimum amount of
|
||||
information means that the data we have is not interesting to purchasers (or those who may have more
|
||||
nefarious purposes).
|
||||
</li>
|
||||
<li>
|
||||
• Access to servers and backups is strictly controlled and monitored for unauthorized access
|
||||
attempts.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">Removing Your Data</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
At any time, you may choose to discontinue using this service. Both Microsoft and Google provide ways to
|
||||
revoke access from this application. However, if you want your data removed from the database, please
|
||||
contact daniel at bitbadger.solutions (via e-mail, replacing at with @) prior to doing so, to ensure we can
|
||||
determine which subscriber ID belongs to you.
|
||||
</p>
|
||||
</div>
|
||||
</main><?php
|
||||
template('layout/page_footer');
|
||||
end_request();
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
$_REQUEST[Constants::PAGE_TITLE] = 'Terms of Service';
|
||||
|
||||
template('layout/page_header'); ?>
|
||||
<main class="container">
|
||||
<h2 class="title">Terms of Service</h2>
|
||||
<h6 class="subtitle">as of May 21<sup>st</sup>, 2018</h6>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">1. Acceptance of Terms</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are
|
||||
responsible to ensure that your use of this site complies with all applicable laws. Your continued use of
|
||||
this site implies your acceptance of these terms.
|
||||
</p>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">2. Description of Service and Registration</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
myPrayerJournal is a service that allows individuals to enter and amend their prayer requests. It requires
|
||||
no registration by itself, but access is granted based on a successful login with an external identity
|
||||
provider. See <a <?php page_link('/legal/privacy-policy'); ?>>our privacy policy</a> for details on how that
|
||||
information is accessed and stored.
|
||||
</p>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">3. Third Party Services</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
This service utilizes a third-party service provider for identity management. Review the terms of service
|
||||
for <a href="https://auth0.com/terms" target="_blank" rel="noopener">Auth0</a>, as well as those for the
|
||||
selected authorization provider
|
||||
(<a href="https://www.microsoft.com/en-us/servicesagreement" target="_blank"
|
||||
rel="noopener">Microsoft</a> or
|
||||
<a href="https://policies.google.com/terms" target="_blank" rel="noopener">Google</a>).
|
||||
</p>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">4. Liability</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
This service is provided “as is”, and no warranty (express or implied) exists. The service and
|
||||
its developers may not be held liable for any damages that may arise through the use of this service.
|
||||
</p>
|
||||
</div>
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h3 class="card-header-title">5. Updates to Terms</h3>
|
||||
</div>
|
||||
<p class="card-content">
|
||||
These terms and conditions may be updated at any time, and this service does not have the capability to
|
||||
notify users when these change. The date at the top of the page will be updated when any of the text of
|
||||
these terms is updated.
|
||||
</p>
|
||||
</div>
|
||||
<p>
|
||||
You may also wish to review our <a <?php page_link('/legal/privacy-policy'); ?>>privacy policy</a> to learn how
|
||||
we handle your data.
|
||||
</p>
|
||||
</main><?php
|
||||
template('layout/page_footer');
|
||||
end_request();
|
||||
@@ -0,0 +1,104 @@
|
||||
"use strict"
|
||||
|
||||
/** myPrayerJournal script */
|
||||
this.mpj = {
|
||||
/**
|
||||
* Show a message via toast
|
||||
* @param {string} message The message to show
|
||||
*/
|
||||
showToast (message) {
|
||||
const [level, msg] = message.split("|||")
|
||||
|
||||
let header
|
||||
if (level !== "success") {
|
||||
const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>`
|
||||
|
||||
header = document.createElement("div")
|
||||
header.className = "toast-header"
|
||||
header.innerHTML = heading(level === "warning" ? level : "error")
|
||||
|
||||
const close = document.createElement("button")
|
||||
close.type = "button"
|
||||
close.className = "btn-close"
|
||||
close.setAttribute("data-bs-dismiss", "toast")
|
||||
close.setAttribute("aria-label", "Close")
|
||||
header.appendChild(close)
|
||||
}
|
||||
|
||||
const body = document.createElement("div")
|
||||
body.className = "toast-body"
|
||||
body.innerText = msg
|
||||
|
||||
const toastEl = document.createElement("div")
|
||||
toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white`
|
||||
toastEl.setAttribute("role", "alert")
|
||||
toastEl.setAttribute("aria-live", "assertlive")
|
||||
toastEl.setAttribute("aria-atomic", "true")
|
||||
toastEl.addEventListener("hidden.bs.toast", e => e.target.remove())
|
||||
if (header) toastEl.appendChild(header)
|
||||
|
||||
toastEl.appendChild(body)
|
||||
document.getElementById("toasts").appendChild(toastEl)
|
||||
new bootstrap.Toast(toastEl, { autohide: level === "success" }).show()
|
||||
},
|
||||
/**
|
||||
* Load local version of Bootstrap CSS if the CDN load failed
|
||||
*/
|
||||
ensureCss () {
|
||||
let loaded = false
|
||||
for (let i = 0; !loaded && i < document.styleSheets.length; i++) {
|
||||
loaded = document.styleSheets[i].href.endsWith("bootstrap.min.css")
|
||||
}
|
||||
if (!loaded) {
|
||||
const css = document.createElement("link")
|
||||
css.rel = "stylesheet"
|
||||
css.href = "/style/bootstrap.min.css"
|
||||
document.getElementsByTagName("head")[0].appendChild(css)
|
||||
}
|
||||
},
|
||||
/** Script for the request edit component */
|
||||
edit: {
|
||||
/**
|
||||
* Toggle the recurrence input fields
|
||||
* @param {Event} e The click event
|
||||
*/
|
||||
toggleRecurrence ({ target }) {
|
||||
const isDisabled = target.value === "Immediate"
|
||||
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled)
|
||||
}
|
||||
},
|
||||
/**
|
||||
* The time zone of the current browser
|
||||
* @type {string}
|
||||
**/
|
||||
timeZone: undefined,
|
||||
/**
|
||||
* Derive the time zone from the current browser
|
||||
*/
|
||||
deriveTimeZone () {
|
||||
try {
|
||||
this.timeZone = (new Intl.DateTimeFormat()).resolvedOptions().timeZone
|
||||
} catch (_) { }
|
||||
}
|
||||
}
|
||||
|
||||
htmx.on("htmx:afterOnLoad", function (evt) {
|
||||
const hdrs = evt.detail.xhr.getAllResponseHeaders()
|
||||
// Show a message if there was one in the response
|
||||
if (hdrs.indexOf("x-toast") >= 0) {
|
||||
mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast"))
|
||||
}
|
||||
// Hide a modal window if requested
|
||||
if (hdrs.indexOf("x-hide-modal") >= 0) {
|
||||
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click()
|
||||
}
|
||||
})
|
||||
|
||||
htmx.on("htmx:configRequest", function (evt) {
|
||||
// Send the user's current time zone so that we can display local time
|
||||
if (mpj.timeZone) {
|
||||
evt.detail.headers["X-Time-Zone"] = mpj.timeZone
|
||||
}
|
||||
})
|
||||
|
||||
mpj.deriveTimeZone()
|
||||
@@ -0,0 +1,60 @@
|
||||
|
||||
nav.navbar.is-dark {
|
||||
background-color: green;
|
||||
|
||||
& .m {
|
||||
font-weight: 100;
|
||||
}
|
||||
& .p {
|
||||
font-weight: 400;
|
||||
}
|
||||
& .j {
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
.nav-item {
|
||||
& a:link,
|
||||
& a:visited {
|
||||
padding: .5rem 1rem;
|
||||
margin: 0 .5rem;
|
||||
border-radius: .5rem;
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
}
|
||||
& a:hover {
|
||||
cursor: pointer;
|
||||
background-color: rgba(255, 255, 255, .2);
|
||||
}
|
||||
& a.is-active-route {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
border-top: solid 4px rgba(255, 255, 255, .3);
|
||||
}
|
||||
}
|
||||
form {
|
||||
max-width: 60rem;
|
||||
margin: auto;
|
||||
}
|
||||
.action-cell .material-icons {
|
||||
font-size: 1.1rem ;
|
||||
}
|
||||
.material-icons {
|
||||
vertical-align: bottom;
|
||||
}
|
||||
#toastHost {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
}
|
||||
.request-text {
|
||||
white-space: pre-line
|
||||
}
|
||||
|
||||
footer {
|
||||
border-top: solid 1px lightgray;
|
||||
margin: 1rem -1rem 0;
|
||||
padding: 0 1rem;
|
||||
|
||||
& p {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
header("Location: {$auth0->logout($_ENV[Constants::BASE_URL])}");
|
||||
exit;
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
$auth0->clear();
|
||||
|
||||
// Check for return URL; if present, store it in a cookie we'll retrieve when we're logged in
|
||||
$nonce = '';
|
||||
if (array_key_exists(Constants::RETURN_URL, $_GET)) {
|
||||
$nonce = urlencode(base64_encode(openssl_random_pseudo_bytes(8)));
|
||||
setcookie(Constants::COOKIE_REDIRECT, "$nonce|{$_GET[Constants::RETURN_URL]}", [
|
||||
'expires' => -1,
|
||||
'secure' => true,
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict'
|
||||
]);
|
||||
}
|
||||
$params = $nonce ? [ Constants::LOG_ON_STATE => $nonce ] : [];
|
||||
|
||||
header('Location: ' . $auth0->login("{$_ENV[Constants::BASE_URL]}/user/logged-on", $params));
|
||||
exit;
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once '../../lib/start.php';
|
||||
|
||||
use MyPrayerJournal\Constants;
|
||||
|
||||
$auth0->exchange("{$_ENV[Constants::BASE_URL]}/user/logged-on");
|
||||
|
||||
$nextUrl = '/journal';
|
||||
if (array_key_exists(Constants::LOG_ON_STATE, $_GET)) {
|
||||
$nonce = base64_decode(urldecode($_GET[Constants::LOG_ON_STATE]));
|
||||
[$verify, $newNext] = explode('|', $_COOKIE[Constants::COOKIE_REDIRECT]);
|
||||
if ($verify == $nonce && $newNext && str_starts_with($newNext, '/') && !str_starts_with($newNext, '//')) {
|
||||
$nextUrl = $newNext;
|
||||
}
|
||||
}
|
||||
|
||||
setcookie(Constants::COOKIE_REDIRECT, '', [
|
||||
'expires' => -1,
|
||||
'secure' => true,
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict'
|
||||
]);
|
||||
header("Location: $nextUrl");
|
||||
exit;
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
use MyPrayerJournal\Constants; ?>
|
||||
</section><?php
|
||||
if (!$_REQUEST[Constants::IS_HTMX]) { ?>
|
||||
<footer class="container-fluid mx-1">
|
||||
<p class="text-muted has-text-right">
|
||||
myPrayerJournal <?php echo $_REQUEST[Constants::VERSION]; ?><br>
|
||||
<em><small>
|
||||
<a <?php page_link('/legal/privacy-policy'); ?>>Privacy Policy</a> •
|
||||
<a <?php page_link('/legal/terms-of-service'); ?>>Terms of Service</a> •
|
||||
<a href="https://github.com/bit-badger/myprayerjournal" target="_blank" rel="noopener">Developed</a>
|
||||
and hosted by
|
||||
<a href="https://bitbadger.solutions" target="_blank" rel="noopener">Bit Badger Solutions</a>
|
||||
</small></em>
|
||||
</p>
|
||||
</footer>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.4"
|
||||
integrity="sha384-zUfuhFKKZCbHTY6aRR46gxiqszMk5tcHjsVFxnUo8VMus4kHGVdIYVbOYYNlKmHV"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="/script/mpj.js"></script><?php
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
use BitBadger\PgDocuments\Document;
|
||||
use MyPrayerJournal\{ Constants, Data };
|
||||
|
||||
$isLoggedOn = array_key_exists('MPJ_USER_ID', $_REQUEST);
|
||||
$hasSnoozed = false;
|
||||
if ($isLoggedOn) {
|
||||
$hasSnoozed = Document::countByJsonPath(Data::REQ_TABLE, '$.snoozedUntil ? (@ == "0")') > 0;
|
||||
}
|
||||
|
||||
$theTitle = array_key_exists(Constants::PAGE_TITLE, $_REQUEST) ? "{$_REQUEST[Constants::PAGE_TITLE]} « " : ''; ?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf8">
|
||||
<title><?php echo $theTitle; ?>myPrayerJournal</title><?php
|
||||
if (!$_REQUEST[Constants::IS_HTMX]) { ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.4/css/bulma.min.css"
|
||||
integrity="sha512-HqxHUkJM0SYcbvxUw5P60SzdOTy/QVwA1JJrvaXJv4q7lmbDZCmZaqz01UPOaQveoxfYRv1tHozWGPMcuTBuvQ=="
|
||||
crossorigin="anonymous" referrerpolicy="no-referrer">
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
||||
<link href="/style/style.css" rel="stylesheet"><?php
|
||||
} ?>
|
||||
</head>
|
||||
<body>
|
||||
<section id="top" aria-label="top navigation">
|
||||
<nav class="navbar is-dark has-shadow" role="navigation" aria-label="main navigation">
|
||||
<div class="navbar-brand">
|
||||
<a <?php page_link('/'); ?> class="navbar-item">
|
||||
<span class="m">my</span><span class="p">Prayer</span><span class="j">Journal</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="navbar-menu">
|
||||
<div class="navbar-start"><?php
|
||||
if ($isLoggedOn) { ?>
|
||||
<a <?php page_link('/journal', ['navbar-item'], true); ?>>Journal</a>
|
||||
<a <?php page_link('/requests/active', ['navbar-item'], true); ?>>Active</a><?php
|
||||
if ($hasSnoozed) { ?>
|
||||
<a <?php page_link('/requests/snoozed', ['navbar-item'], true); ?>>Snoozed</a><?php
|
||||
} ?>
|
||||
<a <?php page_link('/requests/answered', ['navbar-item'], true); ?>>Answered</a>
|
||||
<a href="/user/log-off" class="navbar-item">Log Off</a><?php
|
||||
} else { ?>
|
||||
<a href="/user/log-on" class="navbar-item">Log On</a><?php
|
||||
} ?>
|
||||
<a href="https://docs.prayerjournal.me" class="navbar-item" target="_blank" rel="noopener">Docs</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -0,0 +1,10 @@
|
||||
<div class="card mb-3">
|
||||
<div class="card-header has-background-light">
|
||||
<h5 class="card-header-title"><?php echo $_REQUEST['EMPTY_HEADING']; ?></h5>
|
||||
</div>
|
||||
<div class="card-content has-text-centered">
|
||||
<p class="mb-5"><?php echo $_REQUEST['EMPTY_TEXT']; ?></p>
|
||||
<a <?php page_link($_REQUEST['EMPTY_LINK']); ?>
|
||||
class="button is-link"><?php echo $_REQUEST['EMPTY_BTN_TXT']; ?></a>
|
||||
</div>
|
||||
</div>
|
||||
Reference in new issue
Block a user