Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
# Conflicts:
#	Project.toml
#	src/Stipple.jl
  • Loading branch information
essenciary committed Dec 14, 2023
2 parents 808cc63 + f8c7a42 commit 2715fe7
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 46 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "Stipple"
uuid = "4acbeb90-81a0-11ea-1966-bdaff8155998"
authors = ["Adrian <[email protected]>"]
version = "0.27.21"
version = "0.27.24"

[deps]
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
Expand Down
3 changes: 2 additions & 1 deletion assets/js/watchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,9 @@ const reviveMixin = {

const eventMixin = {
methods: {
handle_event: function (event_data, event_handler) {
handle_event: function (event_data, event_handler, mode) {
console.debug('event: ' + JSON.stringify(event_data) + ":" + event_handler)
if (mode=='addclient') { event_data._addclient = true}
Genie.WebChannels.sendMessageTo(window.CHANNEL, 'events', {
'event': {
'name': event_handler,
Expand Down
3 changes: 2 additions & 1 deletion src/Elements.jl
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ Sometimes preprocessing of the events is necessary, e.g. to add or skip informat
```
"""
macro on(arg, expr, preprocess = nothing)
preprocess isa QuoteNode && preprocess == :(:addclient) && (preprocess = "event._addclient = true")
kw = Symbol("v-on:", arg isa String ? arg : arg isa QuoteNode ? arg.value : arg.head == :vect ? join(lstrip.(string.(arg.args), ':'), '.') :
throw("Value '$arg' for `arg` not supported. `arg` should be of type Symbol, String, or Vector{Union{String, Symbol}}"))

Expand All @@ -370,7 +371,7 @@ macro on(arg, expr, preprocess = nothing)
:(replace("""function(event) {
const preprocess = (event) => { """ * replace($preprocess, '"' => "\\\"") * """; return event }
handle_event(preprocess(event), '$($(esc(expr)))')
}'""", '\n' => ';'))
}""", '\n' => ';'))
end
else
esc_expr(expr)
Expand Down
28 changes: 21 additions & 7 deletions src/Layout.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module Layout
using Genie, Stipple

export layout, add_css, remove_css
export page, app, row, column, cell, container, flexgrid_kwargs
export page, app, row, column, cell, container, flexgrid_kwargs, htmldiv

export theme
const THEMES = Function[]
Expand Down Expand Up @@ -115,8 +115,8 @@ function flexgrid_kwargs(; class = "", class! = nothing, symbol_class::Bool = tr
# if either class is a Symbol or class! is not nothing.
# So an argument of the form `class! = "'my-class' + 'your-class'` is supported
# Furthermore Vectors are now supported
class isa Vector && (class = Symbol(join(js_attr.(class), " + ")))
class! isa Vector && (class! = join(js_attr.(class!), " + "))
class isa Vector && (class = Symbol(join(js_attr.(class), " + ' ' + ")))
class! isa Vector && (class! = join(js_attr.(class!), " + ' ' + "))

classes = String[]
if class isa Symbol
Expand Down Expand Up @@ -173,8 +173,8 @@ function row(args...;
# for backward compatibility with `size` kwarg
col == -1 && size != -1 && (col = size)

class = class isa Symbol ? Symbol("$class + ' row'") : join(push!(split(class), "row"), " ")
kwargs = flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...)
class = class isa Symbol ? Symbol("$class + ' row'") : class isa Vector ? push!(class, "row") : join(push!(split(class), "row"), " ")
kwargs = Stipple.attributes(flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...))

Genie.Renderer.Html.div(args...; kwargs...)
end
Expand Down Expand Up @@ -204,7 +204,7 @@ function column(args...;
col == -1 && size != -1 && (col = size)

class = class isa Symbol ? Symbol("$class + ' column'") : join(push!(split(class), "column"), " ")
kwargs = flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...)
kwargs = Stipple.attributes(flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...))

Genie.Renderer.Html.div(args...; kwargs...)
end
Expand Down Expand Up @@ -247,7 +247,21 @@ function cell(args...;
col == 0 && size != 0 && (col = size)

class = class isa Symbol ? Symbol("$class + ' st-col'") : join(push!(split(class), "st-col"), " ")
kwargs = flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...)
kwargs = Stipple.attributes(flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...))

Genie.Renderer.Html.div(args...; kwargs...)
end

function htmldiv(args...;
col::Union{Int,AbstractString,Symbol,Nothing} = -1,
xs::Union{Int,AbstractString,Symbol,Nothing} = -1, sm::Union{Int,AbstractString,Symbol,Nothing} = -1, md::Union{Int,AbstractString,Symbol,Nothing} = -1,
lg::Union{Int,AbstractString,Symbol,Nothing} = -1, xl::Union{Int,AbstractString,Symbol,Nothing} = -1, size::Union{Int,AbstractString,Symbol,Nothing} = -1,
class = "", kwargs...)

# for backward compatibility with `size` kwarg
col == -1 && size != -1 && (col = size)

kwargs = Stipple.attributes(flexgrid_kwargs(; class, col, xs, sm, md, lg, xl, symbol_class = false, kwargs...))

Genie.Renderer.Html.div(args...; kwargs...)
end
Expand Down
99 changes: 72 additions & 27 deletions src/Stipple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ using Logging, Mixers, Random, Reexport, Dates, Tables
@reexport @using_except Genie: download
import Genie.Router.download
@reexport @using_except Genie.Renderers.Html: mark, div, time, view, render, Headers, menu
const htmldiv = Html.div
export render, htmldiv, js_attr
@reexport using JSON3
@reexport using StructTypes
Expand Down Expand Up @@ -473,17 +472,49 @@ function init(t::Type{M};
end

ch = "/$channel/watchers"
# if ! Genie.Router.ischannel(Router.channelname(ch))
Genie.Router.channel(ch, named = Router.channelname(ch)) do
payload = Genie.Requests.payload(:payload)["payload"]
client = transport == Genie.WebChannels ? Genie.Requests.wsclient() : Genie.Requests.wtclient()
Genie.Router.channel(ch, named = Router.channelname(ch)) do
payload = Genie.Requests.payload(:payload)["payload"]
client = transport == Genie.WebChannels ? Genie.WebChannels.id(Genie.Requests.wsclient()) : Genie.Requests.wtclient()

try
haskey(payload, "sesstoken") && ! isempty(payload["sesstoken"]) &&
Genie.Router.params!(:session,
Stipple.ModelStorage.Sessions.GenieSession.load(payload["sesstoken"] |> Genie.Encryption.decrypt))
catch ex
@error ex
try
haskey(payload, "sesstoken") && ! isempty(payload["sesstoken"]) &&
Genie.Router.params!(:session,
Stipple.ModelStorage.Sessions.GenieSession.load(payload["sesstoken"] |> Genie.Encryption.decrypt))
catch ex
@error ex
end

@debug payload

field = Symbol(payload["field"])

#check if field exists
hasfield(CM, field) || return ok_response

valtype = Dict(zip(fieldnames(CM), CM.types))[field]
val = valtype <: Reactive ? getfield(model, field) : Ref{valtype}(getfield(model, field))

# reject non-public types
( isprivate(field, model) || isreadonly(field, model) ) && return ok_response

newval = convertvalue(val, payload["newval"])
oldval = try
convertvalue(val, payload["oldval"])
catch ex
val[]
end

push!(model, field => newval; channel = channel, except = client)
LAST_ACTIVITY[Symbol(channel)] = now()

try
update!(model, field, newval, oldval)
catch ex
# send the error to the frontend
if Genie.Configuration.isdev()
return ex
else
return "An error has occured -- please check the logs"
end

field = Symbol(payload["field"])
Expand Down Expand Up @@ -520,7 +551,7 @@ function init(t::Type{M};

ok_response
end
# end
end

ch = "/$channel/keepalive"
if ! Genie.Router.ischannel(Router.channelname(ch))
Expand All @@ -538,6 +569,13 @@ function init(t::Type{M};
# form handler parameter & call event notifier
handler = Symbol(get(event, "name", nothing))
event_info = get(event, "event", nothing)

# add client id if requested
if event_info isa Dict && get(event_info, "_addclient", false)
client = transport == Genie.WebChannels ? Genie.WebChannels.id(Genie.Requests.wsclient()) : Genie.Requests.wtclient()
push!(event_info, "_client" => client)
end

isempty(methods(notify, (M, Val{handler}))) || notify(model, Val(handler))
isempty(methods(notify, (M, Val{handler}, Any))) || notify(model, Val(handler), event_info)
LAST_ACTIVITY[Symbol(channel)] = now()
Expand Down Expand Up @@ -622,46 +660,53 @@ const max_retry_times = 10

"""
Base.push!(app::M, vals::Pair{Symbol,T}; channel::String,
except::Union{Genie.WebChannels.HTTP.WebSockets.WebSocket,Nothing,UInt}) where {T,M<:ReactiveModel}
except::Union{Nothing,UInt,Vector{UInt}}) where {T,M<:ReactiveModel}
Pushes data payloads over to the frontend by broadcasting the `vals` through the `channel`.
"""
function Base.push!(app::M, vals::Pair{Symbol,T};
channel::String = Genie.config.webchannels_default_route,
except::Union{Genie.WebChannels.HTTP.WebSockets.WebSocket,Nothing,UInt} = nothing)::Bool where {T,M<:ReactiveModel}
channel::String = getchannel(app),
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing)::Bool where {T,M<:ReactiveModel}
try
webtransport().broadcast(channel, json(Dict("key" => julia_to_vue(vals[1]), "value" => Stipple.render(vals[2], vals[1]))), except = except)
webtransport().broadcast(channel, json(Dict("key" => julia_to_vue(vals[1]), "value" => Stipple.render(vals[2], vals[1]))); except, restrict)
catch ex
@debug ex
false
end
end

function Base.push!(model::M, vals::Pair{Symbol,Reactive{T}};
channel::String = getchannel(model),
except::Union{Genie.WebChannels.HTTP.WebSockets.WebSocket,Nothing,UInt} = nothing)::Bool where {T,M<:ReactiveModel}
function Base.push!(app::M, vals::Pair{Symbol,Reactive{T}};
channel::String = getchannel(app),
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing)::Bool where {T,M<:ReactiveModel}
v = vals[2].r_mode != JSFUNCTION ? vals[2][] : replace_jsfunction(vals[2][])
push!(model, Symbol(julia_to_vue(vals[1])) => v; channel, except)
push!(app, Symbol(julia_to_vue(vals[1])) => v; channel, except, restrict)
end

function Base.push!(model::M;
channel::String = getchannel(model),
function Base.push!(app::M;
channel::String = getchannel(app),
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing,
skip::Vector{Symbol} = Symbol[])::Bool where {M<:ReactiveModel}

result = true

for field in fieldnames(M)
(isprivate(field, model) || field in skip) && continue
(isprivate(field, app) || field in skip) && continue

push!(model, field => getproperty(model, field); channel) === false && (result = false)
push!(app, field => getproperty(app, field); channel, except, restrict) === false && (result = false)
end

result
end

function Base.push!(model::M, field::Symbol; channel::String = getchannel(model))::Bool where {M<:ReactiveModel}
isprivate(field, model) && return false
push!(model, field => getproperty(model, field); channel)
function Base.push!(app::M, field::Symbol;
channel::String = getchannel(app),
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing)::Bool where {M<:ReactiveModel}
isprivate(field, app) && return false
push!(app, field => getproperty(app, field); channel, except, restrict)
end

@specialize
Expand Down
6 changes: 3 additions & 3 deletions src/stipple/jsintegration.jl
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ end
Execute js code in the frontend. `context` can be `:model`, `:app` or `:console`
"""
function Base.run(model::ReactiveModel, jscode::String; context = :model)
context (:model, :app) && return push!(model, Symbol("js_", context) => jsfunction(jscode); channel = getchannel(model))
context == :console && push!(model, :js_model => jsfunction("console.log('$jscode')"); channel = getchannel(model))
function Base.run(model::ReactiveModel, jscode::String; context = :model, kwargs...)
context (:model, :app) && return push!(model, Symbol("js_", context) => jsfunction(jscode); channel = getchannel(model), kwargs...)
context == :console && push!(model, :js_model => jsfunction("console.log('$jscode')"); channel = getchannel(model), kwargs...)

nothing
end
Expand Down
14 changes: 8 additions & 6 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ using Stipple.Genie.HTTPUtils.HTTP

using Test

version = Genie.Assets.package_version(Stipple)

function string_get(x)
String(HTTP.get(x, retries = 0, status_exception = false).body)
end
Expand Down Expand Up @@ -396,13 +398,13 @@ end
@page("/", ui)
payload = String(HTTP.payload(HTTP.get("http://127.0.0.1:$port")))
@test match(r"<div id=\"test\" .*?div>", payload).match == p1
@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")

# route constant ParsedHTMLString
@page("/", ui())
payload = String(HTTP.payload(HTTP.get("http://127.0.0.1:$port")))
@test match(r"<div id=\"test\" .*?div>", payload).match == p1
@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")

# ----------------------------

Expand All @@ -414,13 +416,13 @@ end
@test match(r"<div id=\"test\" .*?div>", payload).match == p1
@test contains(payload, r"<a>test \d+</a>")

@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")

# route constant Vector{ParsedHTMLString}
@page("/", ui())
payload = String(HTTP.payload(HTTP.get("http://127.0.0.1:$port")))
@test match(r"<div id=\"test\" .*?div>", payload).match == p1
@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")

# Supply a String instead of a ParsedHTMLString.
# As the '@' character is not correctly parsed, the match is expected to differ
Expand All @@ -430,14 +432,14 @@ end
@page("/", ui)
payload = String(HTTP.payload(HTTP.get("http://127.0.0.1:$port")))
@test match(r"<div id=\"test\" .*?div>", payload).match != p1
@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")
@test contains(payload, r"<a>test \d+</a>")

# route constant String
@page("/", ui())
payload = String(HTTP.payload(HTTP.get("http://127.0.0.1:$port")))
@test match(r"<div id=\"test\" .*?div>", payload).match != p1
@test contains(payload, """<link href="/stipple.jl/master/assets/css/stipplecore.css""")
@test contains(payload, """<link href="/stipple.jl/$version/assets/css/stipplecore.css""")
@test contains(payload, r"<a>test \d+</a>")

down()
Expand Down

2 comments on commit 2715fe7

@essenciary
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request created: JuliaRegistries/General/97138

Tip: Release Notes

Did you know you can add release notes too? Just add markdown formatted text underneath the comment after the text
"Release notes:" and it will be added to the registry PR, and if TagBot is installed it will also be added to the
release that TagBot creates. i.e.

@JuliaRegistrator register

Release notes:

## Breaking changes

- blah

To add them here just re-invoke and the PR will be updated.

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.27.24 -m "<description of version>" 2715fe707d4399b89912d36dc83f145600eee7c5
git push origin v0.27.24

Please sign in to comment.