Compare commits

..

No commits in common. "main" and "v24" have entirely different histories.
main ... v24

18 changed files with 119 additions and 709 deletions

View file

@ -8,10 +8,6 @@ Create an empty database. The configured user needs to be able to create and alt
Create a configuration file `$HOME/.config/notes.yaml` with the following content:
```yaml
network:
address: '[::]'
port: 1371
websocket:
domains:
- notes.com

59
main.go
View file

@ -67,7 +67,7 @@ func logCallback(e WrappedError.Error) { // {{{
Month int
Day int
Time string
Error error
Error any
}{now.Year(), int(now.Month()), now.Day(), now.Format("15:04:05"), e}
j, _ := json.Marshal(out)
@ -147,7 +147,6 @@ func main() { // {{{
service.Register("/key/create", true, true, keyCreate)
service.Register("/key/counter", true, true, keyCounter)
service.Register("/notification/ack", false, false, notificationAcknowledge)
service.Register("/schedule/list", true, true, scheduleList)
service.Register("/", false, false, service.StaticHandler)
if flagCreateUser {
@ -174,6 +173,28 @@ func main() { // {{{
os.Exit(1)
}
} // }}}
func scheduleHandler() { // {{{
// Wait for the approximate minute.
wait := 60000 - time.Now().Sub(time.Now().Truncate(time.Minute)).Milliseconds()
time.Sleep(time.Millisecond * time.Duration(wait))
tick := time.NewTicker(time.Minute)
for {
<-tick.C
for _, event := range ExpiredSchedules() {
notificationManager.Send(
event.UserID,
event.ScheduleUUID,
[]byte(
fmt.Sprintf(
"%s\n%s",
event.Time.Format("2006-01-02 15:04"),
event.Description,
),
),
)
}
}
} // }}}
func nodeTree(w http.ResponseWriter, r *http.Request, sess *session.T) { // {{{
logger.Info("webserver", "request", "/node/tree")
@ -743,7 +764,7 @@ func keyCounter(w http.ResponseWriter, r *http.Request, sess *session.T) { // {{
func notificationAcknowledge(w http.ResponseWriter, r *http.Request, sess *session.T) { // {{{
logger.Info("webserver", "request", "/notification/ack")
var err error
w.Header().Add("Access-Control-Allow-Origin", "*")
err = AcknowledgeNotification(r.URL.Query().Get("uuid"))
if err != nil {
@ -755,36 +776,4 @@ func notificationAcknowledge(w http.ResponseWriter, r *http.Request, sess *sessi
"OK": true,
})
} // }}}
func scheduleList(w http.ResponseWriter, r *http.Request, sess *session.T) { // {{{
logger.Info("webserver", "request", "/schedule/list")
var err error
w.Header().Add("Access-Control-Allow-Origin", "*")
request := struct {
NodeID int
StartDate time.Time
EndDate time.Time
}{}
body, _ := io.ReadAll(r.Body)
if len(body) > 0 {
err = json.Unmarshal(body, &request)
if err != nil {
responseError(w, err)
return
}
}
var schedules []Schedule
schedules, err = FutureSchedules(sess.UserID, request.NodeID, request.StartDate, request.EndDate)
if err != nil {
responseError(w, err)
return
}
responseData(w, map[string]interface{}{
"OK": true,
"ScheduleEvents": schedules,
})
} // }}}
// vim: foldmethod=marker

15
node.go
View file

@ -3,7 +3,6 @@ package main
import (
// External
"github.com/jmoiron/sqlx"
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"time"
@ -325,20 +324,8 @@ func CreateNode(userID, parentID int, name string) (node Node, err error) { // {
return
} // }}}
func UpdateNode(userID, nodeID, timeOffset int, content string, cryptoKeyID int, markdown bool) (err error) { // {{{
if nodeID == 0 {
return
}
var timezone string
row := service.Db.Conn.QueryRow(`SELECT timezone FROM _webservice.user WHERE id=$1`, userID)
err = row.Scan(&timezone)
if err != nil {
err = werr.Wrap(err).WithCode("002-000F")
return
}
var scannedSchedules, dbSchedules, add, remove []Schedule
scannedSchedules = ScanForSchedules(timezone, content)
scannedSchedules = ScanForSchedules(timeOffset, content)
for i := range scannedSchedules {
scannedSchedules[i].Node.ID = nodeID
scannedSchedules[i].UserID = userID

View file

@ -44,8 +44,6 @@ func (ntfy NTFY) Send(uuid string, msg []byte) (err error) {
ackURL := fmt.Sprintf("http, OK, %s/notification/ack?uuid=%s", ntfy.AcknowledgeURL, uuid)
req.Header.Add("X-Actions", ackURL)
req.Header.Add("X-Priority", "5")
req.Header.Add("X-Tags", "calendar")
res, err = http.DefaultClient.Do(req)
if err != nil {

View file

@ -37,7 +37,7 @@ func InitNotificationManager() (err error) {// {{{
user_id ASC,
prio ASC
)
SELECT COALESCE(jsonb_agg(s.*), '[]')
SELECT jsonb_agg(s.*)
FROM services s
`,
)

View file

@ -1,9 +1,6 @@
package main
import (
// External
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"encoding/json"
"io"
@ -21,8 +18,6 @@ func responseError(w http.ResponseWriter, err error) {
}
resJSON, _ := json.Marshal(res)
werr.Wrap(err).Log()
w.Header().Add("Content-Type", "application/json")
w.Write(resJSON)
}

View file

@ -8,7 +8,6 @@ import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
@ -18,45 +17,19 @@ func init() {
}
type Schedule struct {
ID int
UserID int `json:"user_id" db:"user_id"`
Node Node
ScheduleUUID string `db:"schedule_uuid"`
Time time.Time
RemindMinutes int `db:"remind_minutes"`
Description string
Acknowledged bool
ID int
UserID int `json:"user_id" db:"user_id"`
Node Node
ScheduleUUID string `db:"schedule_uuid"`
Time time.Time
Description string
Acknowledged bool
}
func scheduleHandler() { // {{{
// Wait for the approximate minute.
wait := 60000 - time.Now().Sub(time.Now().Truncate(time.Minute)).Milliseconds()
logger.Info("schedule", "wait", wait/1000)
time.Sleep(time.Millisecond * time.Duration(wait))
tick := time.NewTicker(time.Minute)
for {
schedules := ExpiredSchedules()
for _, event := range schedules {
notificationManager.Send(
event.UserID,
event.ScheduleUUID,
[]byte(
fmt.Sprintf(
"%s\n%s",
event.Time.Format("2006-01-02 15:04"),
event.Description,
),
),
)
}
<-tick.C
}
} // }}}
func ScanForSchedules(timezone string, content string) (schedules []Schedule) { // {{{
func ScanForSchedules(timeOffset int, content string) (schedules []Schedule) {// {{{
schedules = []Schedule{}
rxp := regexp.MustCompile(`\{\s*([0-9]{4}-[0-9]{2}-[0-9]{2}\s+[0-9]{2}:[0-9]{2}(?::[0-9]{2})?)\s*\,\s*(?:(\d+)\s*(h|min)\s*,)?\s*([^\]]+?)\s*\}`)
rxp := regexp.MustCompile(`\{\s*([0-9]{4}-[0-9]{2}-[0-9]{2}\s+[0-9]{2}:[0-9]{2}(?::[0-9]{2})?)\s*\,\s*([^\]]+?)\s*\}`)
foundSchedules := rxp.FindAllStringSubmatch(content, -1)
for _, data := range foundSchedules {
@ -65,56 +38,45 @@ func ScanForSchedules(timezone string, content string) (schedules []Schedule) {
data[1] = data[1] + ":00"
}
logger.Info("time", "parse", data[1])
location, err := time.LoadLocation(timezone)
if err != nil {
err = werr.Wrap(err).WithCode("002-00010")
return
var timeTZ string
if timeOffset < 0 {
hours := (-timeOffset) / 60
mins := (-timeOffset) % 60
timeTZ = fmt.Sprintf("%s -%02d%02d", data[1], hours, mins)
} else {
hours := timeOffset / 60
mins := timeOffset % 60
timeTZ = fmt.Sprintf("%s +%02d%02d", data[1], hours, mins)
}
timestamp, err := time.ParseInLocation("2006-01-02 15:04:05", data[1], location)
timestamp, err := time.Parse("2006-01-02 15:04:05 -0700", timeTZ)
if err != nil {
continue
}
// Reminder
var remindMinutes int
if data[2] != "" && data[3] != "" {
value, _ := strconv.Atoi(data[2])
unit := strings.ToLower(data[3])
switch unit {
case "min":
remindMinutes = value
case "h":
remindMinutes = value * 60
}
}
schedule := Schedule{
Time: timestamp,
RemindMinutes: remindMinutes,
Description: data[4],
Time: timestamp,
Description: data[2],
}
schedules = append(schedules, schedule)
}
return
} // }}}
func RetrieveSchedules(userID int, nodeID int) (schedules []Schedule, err error) { // {{{
}// }}}
func RetrieveSchedules(userID int, nodeID int) (schedules []Schedule, err error) {// {{{
schedules = []Schedule{}
res := service.Db.Conn.QueryRow(`
WITH schedule_events AS (
SELECT
s.id,
s.user_id,
json_build_object('id', s.node_id) AS node,
s.schedule_uuid,
(time - MAKE_INTERVAL(mins => s.remind_minutes)) AT TIME ZONE u.timezone AS time,
s.description,
s.acknowledged
FROM schedule s
INNER JOIN _webservice.user u ON s.user_id = u.id
id,
user_id,
json_build_object('id', node_id) AS node,
schedule_uuid,
time,
description,
acknowledged
FROM schedule
WHERE
user_id=$1 AND
CASE
@ -133,41 +95,34 @@ func RetrieveSchedules(userID int, nodeID int) (schedules []Schedule, err error)
var data []byte
err = res.Scan(&data)
if err != nil {
err = werr.Wrap(err).WithCode("002-000E")
return
}
err = json.Unmarshal(data, &schedules)
return
} // }}}
}// }}}
func (a Schedule) IsEqual(b Schedule) bool { // {{{
func (a Schedule) IsEqual(b Schedule) bool {// {{{
return a.UserID == b.UserID &&
a.Node.ID == b.Node.ID &&
a.Time.Equal(b.Time) &&
a.RemindMinutes == b.RemindMinutes &&
a.Description == b.Description
} // }}}
func (s *Schedule) Insert(queryable Queryable) error { // {{{
}// }}}
func (s *Schedule) Insert(queryable Queryable) error {// {{{
res := queryable.QueryRow(`
INSERT INTO schedule(user_id, node_id, time, remind_minutes, description)
VALUES($1, $2, $3, $4, $5)
INSERT INTO schedule(user_id, node_id, time, description)
VALUES($1, $2, $3, $4)
RETURNING id
`,
s.UserID,
s.Node.ID,
s.Time.Format("2006-01-02 15:04:05"),
s.RemindMinutes,
s.Time,
s.Description,
)
err := res.Scan(&s.ID)
if err != nil {
err = werr.Wrap(err).WithCode("002-000D")
}
return err
} // }}}
func (s *Schedule) Delete(queryable Queryable) error { // {{{
return res.Scan(&s.ID)
}// }}}
func (s *Schedule) Delete(queryable Queryable) error {// {{{
_, err := queryable.Exec(`
DELETE FROM schedule
WHERE
@ -178,23 +133,22 @@ func (s *Schedule) Delete(queryable Queryable) error { // {{{
s.ID,
)
return err
} // }}}
}// }}}
func ExpiredSchedules() (schedules []Schedule) { // {{{
func ExpiredSchedules() (schedules []Schedule) {// {{{
schedules = []Schedule{}
res, err := service.Db.Conn.Queryx(`
SELECT
s.id,
s.user_id,
s.node_id,
s.schedule_uuid,
(s.time - MAKE_INTERVAL(mins => s.remind_minutes)) AT TIME ZONE u.timezone AS time,
s.description
FROM schedule s
INNER JOIN _webservice.user u ON s.user_id = u.id
id,
user_id,
node_id,
schedule_uuid,
time,
description
FROM schedule
WHERE
(time - MAKE_INTERVAL(mins => remind_minutes)) AT TIME ZONE u.timezone < NOW() AND
time < NOW() AND
NOT acknowledged
ORDER BY
time ASC
@ -214,76 +168,4 @@ func ExpiredSchedules() (schedules []Schedule) { // {{{
schedules = append(schedules, s)
}
return
} // }}}
func FutureSchedules(userID int, nodeID int, start time.Time, end time.Time) (schedules []Schedule, err error) { // {{{
schedules = []Schedule{}
var foo string
row := service.Db.Conn.QueryRow(`SELECT TO_CHAR($1::date AT TIME ZONE 'UTC', 'yyyy-mm-dd HH24:MI')`, start)
err = row.Scan(&foo)
if err != nil {
return
}
logger.Info("FOO", "date", foo)
res := service.Db.Conn.QueryRow(`
WITH schedule_events AS (
SELECT
s.id,
s.user_id,
jsonb_build_object(
'id', n.id,
'name', n.name,
'updated', n.updated
) AS node,
s.schedule_uuid,
time AT TIME ZONE u.timezone AS time,
s.description,
s.acknowledged,
s.remind_minutes AS RemindMinutes
FROM schedule s
INNER JOIN _webservice.user u ON s.user_id = u.id
INNER JOIN node n ON s.node_id = n.id
WHERE
s.user_id = $1 AND
(
CASE
WHEN $2 > 0 THEN n.id = $2
ELSE true
END
) AND (
CASE WHEN TO_CHAR($3::date, 'yyyy-mm-dd HH24:MI') = '0001-01-01 00:00' THEN TRUE
ELSE (s.time AT TIME ZONE u.timezone) >= $3
END
) AND (
CASE WHEN TO_CHAR($4::date, 'yyyy-mm-dd HH24:MI') = '0001-01-01 00:00' THEN TRUE
ELSE (s.time AT TIME ZONE u.timezone) <= $4
END
) AND
time >= NOW() AND
NOT acknowledged
)
SELECT
COALESCE(jsonb_agg(s.*), '[]'::jsonb)
FROM schedule_events s
`,
userID,
nodeID,
start,
end,
)
var j []byte
err = res.Scan(&j)
if err != nil {
err = werr.Wrap(err).WithCode("002-000B").WithData(userID)
return
}
err = json.Unmarshal(j, &schedules)
if err != nil {
err = werr.Wrap(err).WithCode("002-0010").WithData(string(j)).Log()
return
}
return
} // }}}
}// }}}

View file

@ -1 +0,0 @@
ALTER TABLE public.schedule ADD COLUMN remind_minutes int NOT NULL DEFAULT 0;

View file

@ -1,2 +0,0 @@
ALTER TABLE _webservice."user" ADD timezone varchar DEFAULT 'UTC' NOT NULL;
ALTER TABLE public.schedule ALTER COLUMN "time" TYPE timestamp USING "time"::timestamp;

View file

@ -1 +0,0 @@
ALTER TABLE public.node ALTER COLUMN updated TYPE timestamptz USING updated::timestamptz;

View file

@ -13,11 +13,6 @@ html {
*:after {
box-sizing: inherit;
}
*,
*:focus,
*:hover {
outline: none;
}
[onClick] {
cursor: pointer;
}
@ -34,17 +29,13 @@ body {
height: 100%;
}
h1 {
font-size: 1.25em;
font-size: 1.5em;
color: #518048;
border-bottom: 1px solid #ccc;
}
h2 {
font-size: 1em;
font-size: 1.25em;
color: #518048;
}
h3 {
font-size: 1em;
}
button {
font-size: 1em;
padding: 6px;
@ -212,7 +203,6 @@ header .menu {
padding: 16px;
background-color: #333;
color: #ddd;
z-index: 100;
}
#tree .node {
display: grid;
@ -418,7 +408,6 @@ header .menu {
cursor: pointer;
}
#checklist .checklist-item {
transform: translate(0, 0);
display: grid;
grid-template-columns: repeat(3, min-content);
grid-gap: 0 8px;
@ -532,7 +521,7 @@ header .menu {
grid-area: 1 / 1 / 2 / 2;
}
/* ============================================================= */
#schedule-section {
#file-section {
grid-area: files;
justify-self: center;
width: calc(100% - 32px);
@ -542,23 +531,6 @@ header .menu {
border-radius: 8px;
margin-top: 32px;
margin-bottom: 32px;
color: #000;
}
#schedule-section .header {
font-weight: bold;
color: #000;
margin-bottom: 16px;
}
#file-section {
grid-area: schedule;
justify-self: center;
width: calc(100% - 32px);
max-width: 900px;
padding: 32px;
background: #f5f5f5;
border-radius: 8px;
margin-top: 32px;
margin-bottom: 16px;
}
#file-section .header {
font-weight: bold;
@ -657,9 +629,9 @@ header .menu {
}
.layout-tree {
display: grid;
grid-template-areas: "header header" "tree crumbs" "tree child-nodes" "tree name" "tree content" "tree checklist" "tree schedule" "tree files" "tree blank";
grid-template-areas: "header header" "tree crumbs" "tree child-nodes" "tree name" "tree content" "tree checklist" "tree files" "tree blank";
grid-template-columns: min-content 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* schedule */ min-content /* files */ 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* files */ 1fr;
/* blank */
color: #fff;
min-height: 100%;
@ -692,9 +664,9 @@ header .menu {
display: block;
}
.layout-crumbs {
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "schedule" "files" "blank";
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "files" "blank";
grid-template-columns: 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* schedule */ min-content /* files */ 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* files */ 1fr;
/* blank */
}
.layout-crumbs #tree {
@ -741,17 +713,17 @@ header .menu {
}
#app.node {
display: grid;
grid-template-areas: "header header" "tree crumbs" "tree child-nodes" "tree name" "tree content" "tree checklist" "tree schedule" "tree files" "tree blank";
grid-template-areas: "header header" "tree crumbs" "tree child-nodes" "tree name" "tree content" "tree checklist" "tree files" "tree blank";
grid-template-columns: min-content 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* schedule */ min-content /* files */ 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* files */ 1fr;
/* blank */
color: #fff;
min-height: 100%;
}
#app.node.toggle-tree {
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "schedule" "files" "blank";
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "files" "blank";
grid-template-columns: 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* schedule */ min-content /* files */ 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* files */ 1fr;
/* blank */
}
#app.node.toggle-tree #tree {
@ -773,72 +745,11 @@ header .menu {
#profile-settings .passwords div {
white-space: nowrap;
}
#schedule-events {
display: grid;
grid-template-columns: repeat(5, min-content);
grid-gap: 4px 12px;
margin: 32px;
color: #000;
white-space: nowrap;
}
#schedule-events .header {
font-weight: bold;
}
#input-text {
border: 1px solid #000 !important;
padding: 16px;
width: 300px;
}
#input-text .label {
margin-bottom: 4px;
}
#input-text input[type=text] {
width: 100%;
padding: 4px;
}
#input-text .buttons {
display: grid;
grid-template-columns: 1fr 64px 64px;
grid-gap: 8px;
margin-top: 8px;
}
#fullcalendar {
margin: 32px;
color: #444;
}
.folder .tabs {
border-left: 1px solid #888;
display: flex;
}
.folder .tabs .tab {
padding: 16px 32px;
border-top: 1px solid #888;
border-bottom: 1px solid #888;
border-right: 1px solid #888;
color: #444;
background: #eee;
cursor: pointer;
}
.folder .tabs .tab.selected {
border-bottom: none;
background: #fff;
}
.folder .tabs .hack {
border-bottom: 1px solid #888;
width: 100%;
}
.folder .content {
padding-top: 1px;
border-left: 1px solid #888;
border-right: 1px solid #888;
border-bottom: 1px solid #888;
padding-bottom: 1px;
}
@media only screen and (max-width: 932px) {
#app.node {
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "schedule" "files" "blank";
grid-template-areas: "header" "crumbs" "child-nodes" "name" "content" "checklist" "files" "blank";
grid-template-columns: 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* schedule */ min-content /* files */ 1fr;
grid-template-rows: min-content /* header */ min-content /* crumbs */ min-content /* child-nodes */ min-content /* name */ min-content /* content */ min-content /* checklist */ min-content /* files */ 1fr;
/* blank */
}
#app.node #tree {

View file

@ -27,7 +27,6 @@
</script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/sjcl.js"></script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/node_modules/marked/marked.min.js"></script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/fullcalendar.min.js"></script>
</head>
<body>

View file

@ -113,7 +113,7 @@ class App extends Component {
this.websocket.register('open', ()=>console.log('websocket connected'))
this.websocket.register('close', ()=>console.log('websocket disconnected'))
this.websocket.register('error', msg=>console.log(msg))
this.websocket.register('message', msg=>this.websocketMessage(msg))
this.websocket.register('message', this.websocketMessage)
this.websocket.start()
}//}}}
websocketMessage(data) {//{{{
@ -121,7 +121,7 @@ class App extends Component {
switch (msg.Op) {
case 'css_reload':
this.websocket.refreshCSS()
refreshCSS()
break;
}
}//}}}

View file

@ -110,11 +110,10 @@ export class Checklist extends Component {
this.groupElements = {}
this.state = {
confirmDeletion: true,
continueAddingItems: true,
}
window._checklist = this
}//}}}
render({ ui, groups }, { confirmDeletion, continueAddingItems }) {//{{{
render({ ui, groups }, { confirmDeletion }) {//{{{
this.groupElements = {}
if (groups.length == 0 && !ui.node.value.ShowChecklist.value)
return
@ -137,10 +136,6 @@ export class Checklist extends Component {
<input type="checkbox" id="confirm-checklist-delete" checked=${confirmDeletion} onchange=${() => this.setState({ confirmDeletion: !confirmDeletion })} />
<label for="confirm-checklist-delete">Confirm checklist deletion</label>
</div>
<div>
<input type="checkbox" id="continue-adding-items" checked=${continueAddingItems} onchange=${() => this.setState({ continueAddingItems: !continueAddingItems })} />
<label for="continue-adding-items">Continue adding items</label>
</div>
`
}
@ -199,62 +194,10 @@ export class Checklist extends Component {
}//}}}
}
class InputElement extends Component {
render({ placeholder, label }) {//{{{
return html`
<dialog id="input-text">
<div class="container">
<div class="label">${label}</div>
<input id="input-text-el" type="text" placeholder=${placeholder} />
<div class="buttons">
<div></div>
<button onclick=${()=>this.cancel()}>Cancel</button>
<button onclick=${()=>this.ok()}>OK</button>
</div>
</div>
</dialog>
`
}//}}}
componentDidMount() {//{{{
const dlg = document.getElementById('input-text')
const input = document.getElementById('input-text-el')
dlg.showModal()
dlg.addEventListener("keydown", evt => this.keyhandler(evt))
input.addEventListener("keydown", evt => this.keyhandler(evt))
input.focus()
}//}}}
ok() {//{{{
const input = document.getElementById('input-text-el')
this.props.callback(true, input.value)
}//}}}
cancel() {//{{{
this.props.callback(false)
}//}}}
keyhandler(evt) {//{{{
let handled = true
switch (evt.key) {
case 'Enter':
this.ok()
break;
case 'Escape':
this.cancel()
break;
default:
handled = false
}
if (handled) {
evt.stopPropagation()
evt.preventDefault()
}
}//}}}
}
class ChecklistGroupElement extends Component {
constructor() {//{{{
super()
this.label = createRef()
this.addingItem = signal(false)
}//}}}
render({ ui, group }) {//{{{
let items = ({ ui, group }) =>
@ -263,42 +206,30 @@ class ChecklistGroupElement extends Component {
.map(item => html`<${ChecklistItemElement} key="item-${item.ID}" ui=${ui} group=${this} item=${item} />`)
let label = () => html`<div class="label" style="cursor: pointer" ref=${this.label} onclick=${() => this.editLabel()}>${group.Label}</div>`
let addItem = () => {
if (this.addingItem.value)
return html`<${InputElement} label="New item" callback=${(ok, val) => this.addItem(ok, val)} />`
}
return html`
<${addItem} />
<div class="checklist-group-container">
<div class="checklist-group ${ui.edit.value ? 'edit' : ''}">
<div class="reorder" style="cursor: grab"></div>
<img src="/images/${_VERSION}/trashcan.svg" onclick=${() => this.delete()} />
<${label} />
<img src="/images/${_VERSION}/add-gray.svg" onclick=${() => this.addingItem.value = true} />
<img src="/images/${_VERSION}/add-gray.svg" onclick=${() => this.addItem()} />
</div>
<${items} ui=${ui} group=${group} />
</div>
`
}//}}}
addItem(ok, label) {//{{{
if (!ok) {
this.addingItem.value = false
addItem() {//{{{
let label = prompt("Create a new item")
if (label === null)
return
}
label = label.trim()
if (label == '') {
this.addingItem.value = false
if (label == '')
return
}
this.props.group.addItem(label, () => {
this.forceUpdate()
})
if (!this.props.ui.state.continueAddingItems)
this.addingItem.value = false
}//}}}
editLabel() {//{{{
let label = prompt('Edit label', this.props.group.Label)
@ -368,7 +299,7 @@ class ChecklistItemElement extends Component {
`
}//}}}
componentDidMount() {//{{{
this.base.addEventListener('dragstart', evt => this.dragStart(evt))
this.base.addEventListener('dragstart', () => this.dragStart())
this.base.addEventListener('dragend', () => this.dragEnd())
this.base.addEventListener('dragenter', evt => this.dragEnter(evt))
}//}}}
@ -422,13 +353,10 @@ class ChecklistItemElement extends Component {
setDragTarget(state) {//{{{
this.setState({ dragTarget: state })
}//}}}
dragStart(evt) {//{{{
dragStart() {//{{{
// Shouldn't be needed, but in case the previous drag was bungled up, we reset.
this.props.ui.dragReset()
this.props.ui.dragItemSource = this
const img = new Image();
evt.dataTransfer.setDragImage(img, 10, 10);
}//}}}
dragEnter(evt) {//{{{
evt.preventDefault()
@ -465,7 +393,7 @@ class ChecklistItemElement extends Component {
this.props.ui.groupElements[fromGroup.ID].current.forceUpdate()
this.props.ui.groupElements[toGroup.ID].current.forceUpdate()
from.move(to, () => {})
from.move(to, ()=>console.log('ok'))
}//}}}
}

File diff suppressed because one or more lines are too long

View file

@ -14,6 +14,7 @@ export class NodeUI extends Component {
this.nodeContent = createRef()
this.nodeProperties = createRef()
this.keys = signal([])
this.page = signal('node')
window.addEventListener('popstate', evt => {
if (evt.state && evt.state.hasOwnProperty('nodeID'))
@ -58,7 +59,6 @@ export class NodeUI extends Component {
case 'node':
if (node.ID == 0) {
page = html`
<div style="cursor: pointer; color: #000; text-align: center;" onclick=${() => this.page.value = 'schedule-events'}>Schedule events</div>
${children.length > 0 ? html`<div class="child-nodes">${children}</div><div id="notes-version">Notes version ${window._VERSION}</div>` : html``}
`
} else {
@ -72,7 +72,6 @@ export class NodeUI extends Component {
${node.Name} ${padlock}
</div>
<${NodeContent} key=${node.ID} node=${node} ref=${this.nodeContent} />
<${NodeEvents} events=${node.ScheduleEvents.value} />
<${Checklist} ui=${this} groups=${node.ChecklistGroups} />
<${NodeFiles} node=${this.node.value} />
`
@ -98,14 +97,10 @@ export class NodeUI extends Component {
case 'search':
page = html`<${Search} nodeui=${this} />`
break
case 'schedule-events':
page = html`<${ScheduleEventList} nodeui=${this} />`
break
}
let menu = () => (this.menu.value ? html`<${Menu} nodeui=${this} />` : null)
let checklist = () =>
let menu = ()=> (this.menu.value ? html`<${Menu} nodeui=${this} />` : null)
let checklist = ()=>
html`
<div class="checklist" onclick=${evt => { evt.stopPropagation(); this.toggleChecklist() }}>
<img src="/images/${window._VERSION}/${this.showChecklist() ? 'checklist-on.svg' : 'checklist-off.svg'}" />
@ -250,12 +245,15 @@ export class NodeUI extends Component {
})
}//}}}
saveNode() {//{{{
/*
let nodeContent = this.nodeContent.current
if (this.page.value != 'node' || nodeContent === null)
return
*/
let content = this.node.value.content()
this.node.value.setContent(content)
this.node.value.save(() => {
this.props.app.nodeModified.value = false
this.node.value.retrieve()
})
this.node.value.save(() => this.props.app.nodeModified.value = false)
}//}}}
renameNode() {//{{{
let name = prompt("New name")
@ -309,7 +307,7 @@ export class NodeUI extends Component {
this.node.value.ShowChecklist.value = !this.node.value.ShowChecklist.value
}//}}}
toggleMarkdown() {//{{{
this.node.value.RenderMarkdown.value = !this.node.value.RenderMarkdown.value
this.node.value.RenderMarkdown.value = !this.node.value.RenderMarkdown.value
}//}}}
}
@ -386,24 +384,6 @@ class MarkdownContent extends Component {
}//}}}
}
class NodeEvents extends Component {
render({ events }) {//{{{
if (events.length == 0)
return html``
const eventElements = events.map(evt => {
const dt = evt.Time.split('T')
return html`<div>${dt[0]} ${dt[1].slice(0, 5)}</div>`
})
return html`
<div id="schedule-section">
<div class="header">Schedule events</div>
${eventElements}
</div>
`
}//}}}
}
class NodeFiles extends Component {
render({ node }) {//{{{
if (node.Files === null || node.Files.length == 0)
@ -458,16 +438,10 @@ export class Node {
this._decrypted = false
this._expanded = false // start value for the TreeNode component,
this.ChecklistGroups = {}
this.ScheduleEvents = signal([])
// it doesn't control it afterwards.
// Used to expand the crumbs upon site loading.
}//}}}
retrieve(callback) {//{{{
this.app.request('/schedule/list', { NodeID: this.ID })
.then(res => {
this.ScheduleEvents.value = res.ScheduleEvents
})
this.app.request('/node/retrieve', { ID: this.ID })
.then(res => {
this.ParentID = res.Node.ParentID
@ -644,7 +618,7 @@ export class Node {
initChecklist(checklistData) {//{{{
if (checklistData === undefined || checklistData === null)
return
this.ChecklistGroups = checklistData.map(groupData => {
this.ChecklistGroups = checklistData.map(groupData=>{
return new ChecklistGroup(groupData)
})
}//}}}
@ -804,7 +778,7 @@ class NodeProperties extends Component {
<div style="margin-bottom: 16px">These properties are only for this note.</div>
<div class="checks">
<input type="checkbox" id="render-markdown" checked=${nodeui.node.value.Markdown} onchange=${evt => nodeui.node.value.Markdown = evt.target.checked} />
<input type="checkbox" id="render-markdown" checked=${nodeui.node.value.Markdown} onchange=${evt=>nodeui.node.value.Markdown = evt.target.checked} />
<label for="render-markdown">Markdown view</label>
</div>
@ -985,133 +959,4 @@ class ProfileSettings extends Component {
}//}}}
}
class ScheduleEventList extends Component {
static CALENDAR = Symbol('CALENDAR')
static LIST = Symbol('LIST')
constructor() {//{{{
super()
this.tab = signal(ScheduleEventList.CALENDAR)
}//}}}
render() {//{{{
var tab
switch (this.tab.value) {
case ScheduleEventList.CALENDAR:
tab = html`<${ScheduleCalendarTab} />`
break;
case ScheduleEventList.LIST:
tab = html`<${ScheduleEventListTab} />`
break;
}
return html`
<div style="margin: 32px">
<div class="folder">
<div class="tabs">
<div onclick=${() => this.tab.value = ScheduleEventList.CALENDAR} class="tab ${this.tab.value == ScheduleEventList.CALENDAR ? 'selected' : ''}">Calendar</div>
<div onclick=${() => this.tab.value = ScheduleEventList.LIST} class="tab ${this.tab.value == ScheduleEventList.LIST ? 'selected' : ''}">List</div>
<div class="hack"></div>
</div>
<div class="content">
${tab}
</div>
</div>
</div>
`
}//}}}
}
class ScheduleEventListTab extends Component {
constructor() {//{{{
super()
this.events = signal(null)
this.retrieveFutureEvents()
}//}}}
render() {//{{{
if (this.events.value === null)
return
let events = this.events.value.sort((a, b) => {
if (a.Time < b.Time) return -1
if (a.Time > b.Time) return 1
return 0
}).map(evt => {
const dt = evt.Time.split('T')
const remind = () => {
if (evt.RemindMinutes > 0)
return html`${evt.RemindMinutes} min`
}
const nodeLink = () => html`<a href="/?node=${evt.Node.ID}">${evt.Node.Name}</a>`
return html`
<div class="date">${dt[0]}</div>
<div class="time">${dt[1].slice(0, 5)}</div>
<div class="remind"><${remind} /></div>
<div class="description">${evt.Description}</div>
<div class="node"><${nodeLink} /></div>
`
})
return html`
<div id="schedule-events">
<div class="header">Date</div>
<div class="header">Time</div>
<div class="header">Reminder</div>
<div class="header">Event</div>
<div class="header">Node</div>
${events}
</div>
`
}//}}}
retrieveFutureEvents() {//{{{
_app.current.request('/schedule/list')
.then(data => {
this.events.value = data.ScheduleEvents
})
}//}}}
}
class ScheduleCalendarTab extends Component {
constructor() {//{{{
super()
}//}}}
componentDidMount() {
let calendarEl = document.getElementById('fullcalendar');
this.calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
events: this.events,
eventTimeFormat: {
hour12: false,
hour: '2-digit',
minute: '2-digit',
},
firstDay: 1,
aspectRatio: 2.5,
});
this.calendar.render();
}
render() {
return html`<div id="fullcalendar"></div>`
}
events(info, successCallback, failureCallback) {
const req = {
StartDate: info.startStr,
EndDate: info.endStr,
}
_app.current.request('/schedule/list', req)
.then(data => {
const fullcalendarEvents = data.ScheduleEvents.map(sch => {
return {
title: sch.Description,
start: sch.Time,
url: `/?node=${sch.Node.ID}`,
}
})
successCallback(fullcalendarEvents)
})
.catch(err=>failureCallback(err))
}
}
// vim: foldmethod=marker

View file

@ -8,10 +8,6 @@ html {
box-sizing: inherit;
}
*,*:focus,*:hover{
outline:none;
}
[onClick] {
cursor: pointer;
}
@ -31,20 +27,15 @@ html, body {
}
h1 {
font-size: 1.25em;
font-size: 1.5em;
color: @header_1;
border-bottom: 1px solid #ccc;
}
h2 {
font-size: 1.0em;
font-size: 1.25em;
color: @header_1;
}
h3 {
font-size: 1.0em;
}
button {
font-size: 1em;
padding: 6px;
@ -231,7 +222,6 @@ header {
padding: 16px;
background-color: #333;
color: #ddd;
z-index: 100; // Over crumbs shadow
.node {
display: grid;
@ -480,7 +470,6 @@ header {
}
.checklist-item {
transform: translate(0, 0);
display: grid;
grid-template-columns: repeat(3, min-content);
grid-gap: 0 8px;
@ -622,7 +611,7 @@ header {
}
/* ============================================================= */
#schedule-section {
#file-section {
grid-area: files;
justify-self: center;
width: calc(100% - 32px);
@ -632,25 +621,6 @@ header {
border-radius: 8px;
margin-top: 32px;
margin-bottom: 32px;
color: #000;
.header {
font-weight: bold;
color: #000;
margin-bottom: 16px;
}
}
#file-section {
grid-area: schedule;
justify-self: center;
width: calc(100% - 32px);
max-width: 900px;
padding: 32px;
background: #f5f5f5;
border-radius: 8px;
margin-top: 32px;
margin-bottom: 16px;
.header {
font-weight: bold;
@ -775,7 +745,6 @@ header {
"tree name"
"tree content"
"tree checklist"
"tree schedule"
"tree files"
"tree blank"
;
@ -787,7 +756,6 @@ header {
min-content /* name */
min-content /* content */
min-content /* checklist */
min-content /* schedule */
min-content /* files */
1fr; /* blank */
color: #fff;
@ -821,7 +789,6 @@ header {
"name"
"content"
"checklist"
"schedule"
"files"
"blank"
;
@ -833,7 +800,6 @@ header {
min-content /* name */
min-content /* content */
min-content /* checklist */
min-content /* schedule */
min-content /* files */
1fr; /* blank */
#tree { display: none }
@ -897,82 +863,6 @@ header {
}
}
#schedule-events {
display: grid;
grid-template-columns: repeat(5, min-content);
grid-gap: 4px 12px;
margin: 32px;
color: #000;
white-space: nowrap;
.header {
font-weight: bold;
}
}
#input-text {
border: 1px solid #000 !important;
padding: 16px;
width: 300px;
.label {
margin-bottom: 4px;
}
input[type=text] {
width: 100%;
padding: 4px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 64px 64px;
grid-gap: 8px;
margin-top: 8px;
}
}
#fullcalendar {
margin: 32px;
color: #444;
}
.folder {
.tabs {
border-left: 1px solid #888;
display: flex;
.tab {
padding: 16px 32px;
border-top: 1px solid #888;
border-bottom: 1px solid #888;
border-right: 1px solid #888;
color: #444;
background: #eee;
cursor: pointer;
&.selected {
border-bottom: none;
background: #fff;
}
}
.hack {
border-bottom: 1px solid #888;
width: 100%;
}
}
.content {
padding-top: 1px;
border-left: 1px solid #888;
border-right: 1px solid #888;
border-bottom: 1px solid #888;
padding-bottom: 1px;
}
}
@media only screen and (max-width: 932px) {
#app.node {
.layout-crumbs();

View file

@ -1 +1 @@
v29
v24