Skip to content

Instantly share code, notes, and snippets.

@pblasucci
Last active June 12, 2023 19:21
Show Gist options
  • Save pblasucci/fde4b9c77e1a6ded7b4e369c378b050e to your computer and use it in GitHub Desktop.
Save pblasucci/fde4b9c77e1a6ded7b4e369c378b050e to your computer and use it in GitHub Desktop.
One possible way to handle dependency management with F# and AvaloniaUI
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
namespace Example
/// Provides access and utilities for clock, calender, and timezone.
type IClock =
/// Return the current instant,
/// as configured in a particular time zone (usually, system default).
abstract JustNow : unit -> ZonedDateTime
/// Provides access and utilities for data persistence.
type IStore =
/// Returns a new database connection.
/// Callers are expected to handle closing/discarding the returned instance.
abstract Connect : unit -> IDbConnection
/// Helpers for working with AppEnv (n.b. this module is "auto-open'ed").
[<AutoOpen>]
module Patterns =
/// Helper to simplify working with IClock instances.
let inline (|Clock|) (source : #IClock) = Clock (source :> IClock)
/// Helper to simplify working with IStore instances.
let inline (|Store|) (source : #IStore) = Store (source :> IStore)
/// Provides execution-environment dependent data and functionality.
type AppEnv(basePath, zone, clock, ?dbFile) =
let appFolder = DirectoryInfo(Path.Combine(basePath, ".example"))
do appFolder.Create()
let dataFolder = appFolder.CreateSubdirectory("data")
let storeFile = dataFolder.AppendPath(defaultArg dbFile "example.db")
let connection =
SQLiteConnectionStringBuilder(
DataSource = storeFile,
Version = 3,
JournalMode = SQLiteJournalModeEnum.Wal
)
let clock = ZonedClock(clock, zone, CalendarSystem.Iso)
interface IClock with
member _.JustNow() = clock.GetCurrentZonedDateTime()
interface IStore with
member _.Connect() =
new SQLiteConnection(string connection) :> IDbConnection
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyri
ght law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
namespace Example
[<NoComparison>]
type Note =
{
Id : string<nanoid>
Content : string
UpdatedAt : ZonedDateTime option
}
member me.IsNew = Option.isNone me.UpdatedAt
static member New() =
{
Id = NanoId.NewId()
Content = ""
UpdatedAt = None
}
/// An abstraction to help decouple communications between the application logic and the GUI layer
type INoteHost =
/// Creates data in persistent storage,
/// or updates existing data in storage.
abstract Upsert : text : string -> unit
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
namespace Example
type NoteHost(env: AppEnv, ?data : Note) as me =
inherit HostWindow()
let mutable data' =
data |> Option.defaultWith (fun () -> Note.New())
do (* .ctor *)
me.Content <- NoteView.main host data'.Content
interface INoteHost with
member me.Upsert(content) =
let origin = me.Position
let update = { data' with Content = content }
match Storage.upsertNote env update with
| Ok data ->
data' <- data
| Error failure ->
// ... error handling elided ...
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
namespace Example
[<RequireQualifiedAccess>]
module NoteView =
// ... lots of code elided ...
let main (host : INoteHost) text =
Component(fun context ->
let state = context.useState text
context.useEffect (
handler = (fun () -> host.Upsert(state.Current)),
triggers = [ EffectTrigger.AfterChange state ]
)
content host state
)
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
namespace Example
type App() =
inherit Application()
let ensureTimeZone () =
let zone = DateTimeZoneProviders.Tzdb.GetSystemDefault()
if isNull zone then invalidProg "Unable to determine current time zone!"
zone
let ensureBasePath () =
match GetFolderPath(SpecialFolder.Personal) with
| Length 0u -> invalidProg "Unable to determine home folder."
| folder -> folder
let tryGetDbFile args =
match args with
| [| "--db"; Length n as file |]
when 0u < n -> Some file
| _otherwise -> None
override me.Initialize() = AvaloniaXamlLoader.Load(me)
override me.OnFrameworkInitializationCompleted() =
match me.ApplicationLifetime with
| :? IClassicDesktopStyleApplicationLifetime as desktop ->
let env = AppEnv(
ensureBasePath (),
ensureTimeZone (),
SystemClock.Instance,
?dbFile=tryGetDbFile desktop.Args
)
// ... other start up code elided ...
| _ -> invalidProg "Incorrect application lifetime detected."
base.OnFrameworkInitializationCompleted()
module Program =
[<EntryPoint>]
let main args =
try
AppBuilder
.Configure<App>()
.UsePlatformDetect()
.UseSkia()
.StartWithClassicDesktopLifetime(args, ShutdownMode.OnLastWindowClose)
with x ->
// ... error handling elided ...
1 // ⮜⮜⮜ non-success exit code
(*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*)
module Example.Storage
let upsertNote (Clock clock & Store store) note =
use db = store.Connect()
use tx = db.StartTransaction()
try
let now : ZonedDateTime = clock.JustNow()
db.Execute(
sql="... omitted for brevity...",
param=
{|
key = string note.Id
content = note.Content
updatedAt = stamp.Format(now)
|},
transaction=tx
) |> ignore
tx.Commit()
Ok { data with UpdatedAt = Some now }
with
| x ->
tx.Rollback()
Error x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment