diff --git a/app/.gitignore b/app/.gitignore
new file mode 100644
index 0000000..79f7eca
--- /dev/null
+++ b/app/.gitignore
@@ -0,0 +1,48 @@
+# Miscellaneous
+*.class
+*.log
+*.pyc
+*.swp
+.DS_Store
+.atom/
+.build/
+.buildlog/
+.history
+.svn/
+.swiftpm/
+migrate_working_dir/
+
+# IntelliJ related
+*.iml
+*.ipr
+*.iws
+.idea/
+
+# The .vscode folder contains launch configuration and tasks you configure in
+# VS Code which you may wish to be included in version control, so this line
+# is commented out by default.
+#.vscode/
+
+# Flutter/Dart/Pub related
+**/doc/api/
+**/ios/Flutter/.last_build_id
+.dart_tool/
+.flutter-plugins-dependencies
+.pub-cache/
+.pub/
+/build/
+/coverage/
+
+# Symbolication related
+app.*.symbols
+
+# Obfuscation related
+app.*.map.json
+
+# Android Studio will place build artifacts here
+/android/app/debug
+/android/app/profile
+/android/app/release
+
+# Widget Preview related
+.widget_preview/
diff --git a/app/.metadata b/app/.metadata
new file mode 100644
index 0000000..4494c73
--- /dev/null
+++ b/app/.metadata
@@ -0,0 +1,36 @@
+# This file tracks properties of this Flutter project.
+# Used by Flutter tool to assess capabilities and perform upgrades etc.
+#
+# This file should be version controlled and should not be manually edited.
+
+version:
+ revision: "abaf9c523780a608bd46686fd5e53740a07077f8"
+ channel: "stable"
+
+project_type: app
+
+# Tracks metadata for the flutter migrate command
+migration:
+ platforms:
+ - platform: root
+ create_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ base_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ - platform: android
+ create_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ base_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ - platform: linux
+ create_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ base_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ - platform: windows
+ create_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+ base_revision: abaf9c523780a608bd46686fd5e53740a07077f8
+
+ # User provided section
+
+ # List of Local paths (relative to this file) that should be
+ # ignored by the migrate tool.
+ #
+ # Files that are not part of the templates will be ignored by default.
+ unmanaged_files:
+ - 'lib/main.dart'
+ - 'ios/Runner.xcodeproj/project.pbxproj'
diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml
new file mode 100644
index 0000000..ea6a8f3
--- /dev/null
+++ b/app/analysis_options.yaml
@@ -0,0 +1,9 @@
+include: package:flutter_lints/flutter.yaml
+
+analyzer:
+ exclude:
+ - build/**
+ - android/**
+ - windows/**
+ - linux/**
+ - rust_builder/cargokit/**
diff --git a/app/android/.gitignore b/app/android/.gitignore
new file mode 100644
index 0000000..be3943c
--- /dev/null
+++ b/app/android/.gitignore
@@ -0,0 +1,14 @@
+gradle-wrapper.jar
+/.gradle
+/captures/
+/gradlew
+/gradlew.bat
+/local.properties
+GeneratedPluginRegistrant.java
+.cxx/
+
+# Remember to never publicly share your keystore.
+# See https://flutter.dev/to/reference-keystore
+key.properties
+**/*.keystore
+**/*.jks
diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts
new file mode 100644
index 0000000..37c27c0
--- /dev/null
+++ b/app/android/app/build.gradle.kts
@@ -0,0 +1,49 @@
+plugins {
+ id("com.android.application")
+ // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
+ id("dev.flutter.flutter-gradle-plugin")
+}
+
+android {
+ namespace = "es.zenvairo.synapse"
+ compileSdk = flutter.compileSdkVersion
+ ndkVersion = flutter.ndkVersion
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ defaultConfig {
+ // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
+ applicationId = "es.zenvairo.synapse"
+ // You can update the following values to match your application needs.
+ // For more information, see: https://flutter.dev/to/review-gradle-config.
+ minSdk = flutter.minSdkVersion
+ targetSdk = flutter.targetSdkVersion
+ // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
+ // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
+ // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
+ // flag during build.
+ versionCode = flutter.versionCode
+ versionName = flutter.versionName
+ }
+
+ buildTypes {
+ release {
+ // TODO: Add your own signing config for the release build.
+ // Signing with the debug keys for now, so `flutter run --release` works.
+ signingConfig = signingConfigs.getByName("debug")
+ }
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+ }
+}
+
+flutter {
+ source = "../.."
+}
diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml
new file mode 100644
index 0000000..399f698
--- /dev/null
+++ b/app/android/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,7 @@
+
+
+
+
diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..7620421
--- /dev/null
+++ b/app/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt b/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt
new file mode 100644
index 0000000..395e4e1
--- /dev/null
+++ b/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt
@@ -0,0 +1,5 @@
+package es.zenvairo.synapse
+
+import io.flutter.embedding.android.FlutterActivity
+
+class MainActivity : FlutterActivity()
diff --git a/app/android/app/src/main/res/drawable-v21/launch_background.xml b/app/android/app/src/main/res/drawable-v21/launch_background.xml
new file mode 100644
index 0000000..f74085f
--- /dev/null
+++ b/app/android/app/src/main/res/drawable-v21/launch_background.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
diff --git a/app/android/app/src/main/res/drawable/launch_background.xml b/app/android/app/src/main/res/drawable/launch_background.xml
new file mode 100644
index 0000000..304732f
--- /dev/null
+++ b/app/android/app/src/main/res/drawable/launch_background.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..db77bb4
Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..17987b7
Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..09d4391
Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..d5f1c8d
Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..4d6372e
Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/app/android/app/src/main/res/values-night/styles.xml b/app/android/app/src/main/res/values-night/styles.xml
new file mode 100644
index 0000000..06952be
--- /dev/null
+++ b/app/android/app/src/main/res/values-night/styles.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..cb1ef88
--- /dev/null
+++ b/app/android/app/src/main/res/values/styles.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
diff --git a/app/android/app/src/profile/AndroidManifest.xml b/app/android/app/src/profile/AndroidManifest.xml
new file mode 100644
index 0000000..399f698
--- /dev/null
+++ b/app/android/app/src/profile/AndroidManifest.xml
@@ -0,0 +1,7 @@
+
+
+
+
diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts
new file mode 100644
index 0000000..dbee657
--- /dev/null
+++ b/app/android/build.gradle.kts
@@ -0,0 +1,24 @@
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+val newBuildDir: Directory =
+ rootProject.layout.buildDirectory
+ .dir("../../build")
+ .get()
+rootProject.layout.buildDirectory.value(newBuildDir)
+
+subprojects {
+ val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
+ project.layout.buildDirectory.value(newSubprojectBuildDir)
+}
+subprojects {
+ project.evaluationDependsOn(":app")
+}
+
+tasks.register("clean") {
+ delete(rootProject.layout.buildDirectory)
+}
diff --git a/app/android/gradle.properties b/app/android/gradle.properties
new file mode 100644
index 0000000..e96108c
--- /dev/null
+++ b/app/android/gradle.properties
@@ -0,0 +1,6 @@
+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
+android.useAndroidX=true
+# This newDsl flag was added by the Flutter template
+android.newDsl=false
+# This builtInKotlin flag was added by the Flutter template
+android.builtInKotlin=false
diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..a20f2c4
--- /dev/null
+++ b/app/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
diff --git a/app/android/settings.gradle.kts b/app/android/settings.gradle.kts
new file mode 100644
index 0000000..b28021a
--- /dev/null
+++ b/app/android/settings.gradle.kts
@@ -0,0 +1,26 @@
+pluginManagement {
+ val flutterSdkPath =
+ run {
+ val properties = java.util.Properties()
+ file("local.properties").inputStream().use { properties.load(it) }
+ val flutterSdkPath = properties.getProperty("flutter.sdk")
+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
+ flutterSdkPath
+ }
+
+ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
+
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+plugins {
+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"
+ id("com.android.application") version "9.1.0" apply false
+ id("org.jetbrains.kotlin.android") version "2.4.0" apply false
+}
+
+include(":app")
diff --git a/app/assets/fonts/Inter-Bold.ttf b/app/assets/fonts/Inter-Bold.ttf
new file mode 100644
index 0000000..9fb9b75
Binary files /dev/null and b/app/assets/fonts/Inter-Bold.ttf differ
diff --git a/app/assets/fonts/Inter-BoldItalic.ttf b/app/assets/fonts/Inter-BoldItalic.ttf
new file mode 100644
index 0000000..8d05000
Binary files /dev/null and b/app/assets/fonts/Inter-BoldItalic.ttf differ
diff --git a/app/assets/fonts/Inter-Italic.ttf b/app/assets/fonts/Inter-Italic.ttf
new file mode 100644
index 0000000..e7ed211
Binary files /dev/null and b/app/assets/fonts/Inter-Italic.ttf differ
diff --git a/app/assets/fonts/Inter-Medium.ttf b/app/assets/fonts/Inter-Medium.ttf
new file mode 100644
index 0000000..458cd06
Binary files /dev/null and b/app/assets/fonts/Inter-Medium.ttf differ
diff --git a/app/assets/fonts/Inter-OFL.txt b/app/assets/fonts/Inter-OFL.txt
new file mode 100644
index 0000000..9b2ca37
--- /dev/null
+++ b/app/assets/fonts/Inter-OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/assets/fonts/Inter-Regular.ttf b/app/assets/fonts/Inter-Regular.ttf
new file mode 100644
index 0000000..b7aaca8
Binary files /dev/null and b/app/assets/fonts/Inter-Regular.ttf differ
diff --git a/app/assets/fonts/Inter-SemiBold.ttf b/app/assets/fonts/Inter-SemiBold.ttf
new file mode 100644
index 0000000..47f8ab1
Binary files /dev/null and b/app/assets/fonts/Inter-SemiBold.ttf differ
diff --git a/app/assets/fonts/NotoSerif-OFL.txt b/app/assets/fonts/NotoSerif-OFL.txt
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/app/assets/fonts/NotoSerif-OFL.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/app/assets/fonts/NotoSerif-Variable.ttf b/app/assets/fonts/NotoSerif-Variable.ttf
new file mode 100644
index 0000000..2c49f57
Binary files /dev/null and b/app/assets/fonts/NotoSerif-Variable.ttf differ
diff --git a/app/assets/fonts/SourceCodePro-OFL.md b/app/assets/fonts/SourceCodePro-OFL.md
new file mode 100644
index 0000000..70288a8
--- /dev/null
+++ b/app/assets/fonts/SourceCodePro-OFL.md
@@ -0,0 +1,93 @@
+© 2023 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/assets/fonts/SourceCodePro-Regular.otf b/app/assets/fonts/SourceCodePro-Regular.otf
new file mode 100644
index 0000000..16c7b0b
Binary files /dev/null and b/app/assets/fonts/SourceCodePro-Regular.otf differ
diff --git a/app/assets/fonts/SourceCodePro-Semibold.otf b/app/assets/fonts/SourceCodePro-Semibold.otf
new file mode 100644
index 0000000..11e64fb
Binary files /dev/null and b/app/assets/fonts/SourceCodePro-Semibold.otf differ
diff --git a/app/flutter_rust_bridge.yaml b/app/flutter_rust_bridge.yaml
new file mode 100644
index 0000000..bad4d6e
--- /dev/null
+++ b/app/flutter_rust_bridge.yaml
@@ -0,0 +1,3 @@
+rust_input: crate::api
+rust_root: ../crates/synapse-ffi/
+dart_output: lib/src/rust
diff --git a/app/lib/main.dart b/app/lib/main.dart
new file mode 100644
index 0000000..1a1e79b
--- /dev/null
+++ b/app/lib/main.dart
@@ -0,0 +1,24 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import 'src/app.dart';
+import 'src/backend/graph_backend.dart';
+import 'src/editor/block_row.dart' as editor;
+import 'src/rust/frb_generated.dart';
+
+Future main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+ await RustLib.init();
+ editor.openUrl = (url) {
+ final uri = Uri.tryParse(url);
+ if (uri != null) launchUrl(uri, mode: LaunchMode.externalApplication);
+ };
+ final dir =
+ Platform.environment['SYNAPSE_GRAPH'] ??
+ '${(await getApplicationSupportDirectory()).path}${Platform.pathSeparator}graph';
+ final backend = await FfiGraphBackend.open(dir);
+ runApp(SynapseApp(backend: backend));
+}
diff --git a/app/lib/src/app.dart b/app/lib/src/app.dart
new file mode 100644
index 0000000..982cad8
--- /dev/null
+++ b/app/lib/src/app.dart
@@ -0,0 +1,42 @@
+import 'package:flutter/material.dart';
+
+import 'backend/graph_backend.dart';
+import 'state/app_state.dart';
+import 'theme/theme.dart';
+import 'views/shell.dart';
+
+class SynapseApp extends StatefulWidget {
+ const SynapseApp({super.key, required this.backend});
+ final GraphBackend backend;
+
+ @override
+ State createState() => _SynapseAppState();
+}
+
+class _SynapseAppState extends State {
+ late final AppState _state = AppState(widget.backend)..loadRecent();
+
+ @override
+ void dispose() {
+ _state.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AppScope(
+ state: _state,
+ child: ListenableBuilder(
+ listenable: _state,
+ builder: (context, _) => MaterialApp(
+ title: 'Synapse',
+ debugShowCheckedModeBanner: false,
+ theme: buildTheme(Brightness.light),
+ darkTheme: buildTheme(Brightness.dark),
+ themeMode: _state.themeMode,
+ home: const Shell(),
+ ),
+ ),
+ );
+ }
+}
diff --git a/app/lib/src/backend/graph_backend.dart b/app/lib/src/backend/graph_backend.dart
new file mode 100644
index 0000000..be4a4ec
--- /dev/null
+++ b/app/lib/src/backend/graph_backend.dart
@@ -0,0 +1,148 @@
+import '../rust/api/dto.dart';
+import '../rust/api/graph.dart';
+
+export '../rust/api/dto.dart';
+
+/// What the UI needs from a graph. [FfiGraphBackend] talks to the Rust core; tests use an
+/// in-memory implementation. Keeping the UI on this interface (instead of the generated
+/// opaque class) is what makes the editor testable without the native library.
+abstract class GraphBackend {
+ /// Today's date in the graph clock, `YYYY-MM-DD`.
+ String today();
+
+ Future> journals({String? before, required int limit});
+ Future journal(String date);
+ Future page(String id);
+ Future pageByTitle(String title);
+
+ /// Page by title or alias, created if missing.
+ Future openPage(String title);
+ Future> listPages({
+ bool includeJournals = false,
+ required int limit,
+ int offset = 0,
+ });
+ Future renamePage(String id, String newTitle);
+ Future deletePage(String id);
+ Future addAlias(String pageId, String alias);
+ Future removeAlias(String alias);
+
+ Future insertBlock(String pageId, Place place, String content);
+ Future updateBlock(String id, String content);
+ Future setCollapsed(String id, bool collapsed);
+ Future> deleteBlock(String id);
+ Future> moveBlock(String id, String pageId, Place place);
+ Future> indentBlock(String id);
+ Future> outdentBlock(String id);
+ Future> mergeBlock(String id, String into);
+ Future> outline(String pageId);
+
+ Future> backlinks(String pageId);
+ Future> related(String pageId, {int limit = 12});
+ Future recordVisit(String? from, String to);
+ Future blockRef(String id);
+ Future timeline(String from, String to);
+
+ Future> searchTitles(String query, {int limit = 20});
+ Future> searchBlocks(String query, {int limit = 20});
+
+ /// Local path of an `asset://` blob, if present.
+ String? assetPath(String hash);
+ Future putAssetFile(String path, {String? mime});
+}
+
+class FfiGraphBackend implements GraphBackend {
+ FfiGraphBackend(this._g);
+
+ final SynapseGraph _g;
+
+ static Future open(String dir) async =>
+ FfiGraphBackend(await SynapseGraph.open(dir: dir));
+
+ @override
+ String today() => _g.today();
+
+ @override
+ Future> journals({String? before, required int limit}) =>
+ _g.journals(before: before, limit: limit);
+ @override
+ Future journal(String date) => _g.journal(date: date);
+ @override
+ Future page(String id) => _g.page(id: id);
+ @override
+ Future pageByTitle(String title) => _g.pageByTitle(title: title);
+ @override
+ Future openPage(String title) => _g.openPage(title: title);
+ @override
+ Future> listPages({
+ bool includeJournals = false,
+ required int limit,
+ int offset = 0,
+ }) => _g.listPages(
+ includeJournals: includeJournals,
+ limit: limit,
+ offset: offset,
+ );
+ @override
+ Future renamePage(String id, String newTitle) =>
+ _g.renamePage(id: id, newTitle: newTitle);
+ @override
+ Future deletePage(String id) => _g.deletePage(id: id);
+ @override
+ Future addAlias(String pageId, String alias) =>
+ _g.addAlias(pageId: pageId, alias: alias);
+ @override
+ Future removeAlias(String alias) => _g.removeAlias(alias: alias);
+
+ @override
+ Future insertBlock(String pageId, Place place, String content) =>
+ _g.insertBlock(pageId: pageId, place: place, content: content);
+ @override
+ Future updateBlock(String id, String content) =>
+ _g.updateBlock(id: id, content: content);
+ @override
+ Future setCollapsed(String id, bool collapsed) =>
+ _g.setCollapsed(id: id, collapsed: collapsed);
+ @override
+ Future> deleteBlock(String id) => _g.deleteBlock(id: id);
+ @override
+ Future> moveBlock(String id, String pageId, Place place) =>
+ _g.moveBlock(id: id, pageId: pageId, place: place);
+ @override
+ Future> indentBlock(String id) => _g.indentBlock(id: id);
+ @override
+ Future> outdentBlock(String id) => _g.outdentBlock(id: id);
+ @override
+ Future> mergeBlock(String id, String into) =>
+ _g.mergeBlock(id: id, into: into);
+ @override
+ Future> outline(String pageId) => _g.outline(pageId: pageId);
+
+ @override
+ Future> backlinks(String pageId) =>
+ _g.backlinks(pageId: pageId);
+ @override
+ Future> related(String pageId, {int limit = 12}) =>
+ _g.related(pageId: pageId, limit: limit);
+ @override
+ Future recordVisit(String? from, String to) =>
+ _g.recordVisit(from: from, to: to);
+ @override
+ Future blockRef(String id) => _g.blockRef(id: id);
+ @override
+ Future timeline(String from, String to) =>
+ _g.timeline(from: from, to: to);
+
+ @override
+ Future> searchTitles(String query, {int limit = 20}) =>
+ _g.searchTitles(query: query, limit: limit);
+ @override
+ Future> searchBlocks(String query, {int limit = 20}) =>
+ _g.searchBlocks(query: query, limit: limit);
+
+ @override
+ String? assetPath(String hash) => _g.assetPath(hash: hash);
+ @override
+ Future putAssetFile(String path, {String? mime}) =>
+ _g.putAssetFile(path: path, mime: mime);
+}
diff --git a/app/lib/src/editor/block_row.dart b/app/lib/src/editor/block_row.dart
new file mode 100644
index 0000000..3b8510b
--- /dev/null
+++ b/app/lib/src/editor/block_row.dart
@@ -0,0 +1,875 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+
+import '../backend/graph_backend.dart';
+import '../state/app_state.dart';
+import '../state/outline_controller.dart';
+import '../state/outline_ops.dart';
+import '../theme/theme.dart';
+import 'completion.dart';
+import 'markdown.dart';
+
+const indentWidth = 24.0;
+const _gutter = 18.0;
+const _bulletBox = 18.0;
+
+/// What a bullet drag carries.
+class BlockDrag {
+ const BlockDrag(this.controller, this.node);
+ final OutlineController controller;
+ final OutlineNode node;
+}
+
+enum _Drop { before, after, child }
+
+/// One outline row: guides, collapse arrow, bullet (drag handle) and the block itself,
+/// rendered when idle and a raw-Markdown editor when focused.
+class BlockRow extends StatefulWidget {
+ const BlockRow({
+ super.key,
+ required this.controller,
+ required this.node,
+ required this.editing,
+ required this.hasChildren,
+ });
+
+ final OutlineController controller;
+ final OutlineNode node;
+ final bool editing;
+ final bool hasChildren;
+
+ @override
+ State createState() => _BlockRowState();
+}
+
+class _BlockRowState extends State {
+ bool _hover = false;
+ _Drop? _drop;
+
+ OutlineController get c => widget.controller;
+ OutlineNode get n => widget.node;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.colors;
+ final depth = n.depth;
+ final lineH = blockFontSize * blockLineHeight;
+ return DragTarget(
+ onWillAcceptWithDetails: (d) =>
+ d.data.controller == c && d.data.node != n,
+ onMove: (d) => _updateDrop(d.offset),
+ onLeave: (_) => setState(() => _drop = null),
+ onAcceptWithDetails: (d) {
+ final drop = _drop;
+ setState(() => _drop = null);
+ if (drop == null) return;
+ c.moveTo(d.data.node, switch (drop) {
+ _Drop.before => PlaceKind.before,
+ _Drop.after => PlaceKind.after,
+ _Drop.child => PlaceKind.firstChildOf,
+ }, n);
+ },
+ builder: (context, _, _) => MouseRegion(
+ onEnter: (_) => setState(() => _hover = true),
+ onExit: (_) => setState(() => _hover = false),
+ child: CustomPaint(
+ painter: _GuidesPainter(depth, colors.line, _drop, colors.accent),
+ child: Padding(
+ padding: EdgeInsets.only(left: depth * indentWidth),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: _gutter,
+ height: lineH + 4,
+ child: (widget.hasChildren && (_hover || n.collapsed))
+ ? _Arrow(
+ collapsed: n.collapsed,
+ onTap: () => c.toggleCollapsed(n),
+ )
+ : null,
+ ),
+ _bullet(colors, lineH),
+ const SizedBox(width: 6),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 2),
+ child: widget.editing
+ ? BlockEditor(
+ key: ValueKey('edit-${identityHashCode(n)}'),
+ controller: c,
+ node: n,
+ )
+ : BlockView(controller: c, node: n),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _bullet(SynapseColors colors, double lineH) {
+ final collapsedWithKids = n.collapsed && widget.hasChildren;
+ final dot = SizedBox(
+ width: _bulletBox,
+ height: lineH + 4,
+ child: Center(
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 120),
+ width: 16,
+ height: 16,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: collapsedWithKids ? colors.line : Colors.transparent,
+ ),
+ child: Center(
+ child: Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: _hover ? colors.muted : colors.faint,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ return Draggable(
+ data: BlockDrag(c, n),
+ dragAnchorStrategy: pointerDragAnchorStrategy,
+ feedback: _DragFeedback(text: n.content),
+ childWhenDragging: Opacity(opacity: 0.3, child: dot),
+ child: MouseRegion(
+ cursor: SystemMouseCursors.grab,
+ child: GestureDetector(
+ onTap: widget.hasChildren ? () => c.toggleCollapsed(n) : null,
+ child: dot,
+ ),
+ ),
+ );
+ }
+
+ void _updateDrop(Offset global) {
+ final box = context.findRenderObject() as RenderBox?;
+ if (box == null) return;
+ final p = box.globalToLocal(global);
+ final contentX = n.depth * indentWidth + _gutter + _bulletBox;
+ final _Drop d;
+ if (p.dy < box.size.height / 2) {
+ d = _Drop.before;
+ } else {
+ d = p.dx > contentX + 28 ? _Drop.child : _Drop.after;
+ }
+ if (d != _drop) setState(() => _drop = d);
+ }
+}
+
+class _Arrow extends StatelessWidget {
+ const _Arrow({required this.collapsed, required this.onTap});
+ final bool collapsed;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) => MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: onTap,
+ child: Center(
+ child: AnimatedRotation(
+ turns: collapsed ? 0 : 0.25,
+ duration: const Duration(milliseconds: 140),
+ child: Icon(
+ Icons.chevron_right_rounded,
+ size: 16,
+ color: context.colors.faint,
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+class _DragFeedback extends StatelessWidget {
+ const _DragFeedback({required this.text});
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.colors;
+ return Material(
+ color: Colors.transparent,
+ child: Container(
+ constraints: const BoxConstraints(maxWidth: 320),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: colors.paper,
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(color: colors.line),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withAlpha(0x22),
+ blurRadius: 16,
+ offset: const Offset(0, 6),
+ ),
+ ],
+ ),
+ child: Text(
+ text.split('\n').first,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(fontSize: 14, color: colors.ink),
+ ),
+ ),
+ );
+ }
+}
+
+/// Vertical indent guides plus the drop indicator.
+class _GuidesPainter extends CustomPainter {
+ _GuidesPainter(this.depth, this.color, this.drop, this.accent);
+ final int depth;
+ final Color color;
+ final _Drop? drop;
+ final Color accent;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final p = Paint()
+ ..color = color
+ ..strokeWidth = 1;
+ for (var k = 0; k < depth; k++) {
+ final x = k * indentWidth + _gutter + _bulletBox / 2;
+ canvas.drawLine(Offset(x, 0), Offset(x, size.height), p);
+ }
+ if (drop != null) {
+ final a = Paint()
+ ..color = accent
+ ..strokeWidth = 2
+ ..strokeCap = StrokeCap.round;
+ var x = depth * indentWidth + _gutter;
+ if (drop == _Drop.child) x += indentWidth;
+ final y = drop == _Drop.before ? 1.0 : size.height - 1;
+ canvas.drawLine(Offset(x, y), Offset(size.width - 8, y), a);
+ }
+ }
+
+ @override
+ bool shouldRepaint(_GuidesPainter old) =>
+ old.depth != depth ||
+ old.drop != drop ||
+ old.color != color ||
+ old.accent != accent;
+}
+
+TextStyle blockTextStyle(BuildContext context) => TextStyle(
+ fontFamily: uiFont,
+ fontSize: blockFontSize,
+ height: blockLineHeight,
+ color: context.colors.ink,
+);
+
+/// Rendered (read) mode of a block. A tap places the caret at the matching source offset.
+class BlockView extends StatefulWidget {
+ const BlockView({super.key, required this.controller, required this.node});
+ final OutlineController controller;
+ final OutlineNode node;
+
+ @override
+ State createState() => _BlockViewState();
+}
+
+class _BlockViewState extends State {
+ final _key = GlobalKey();
+ RenderedBlock? _rendered;
+ String? _renderedFor;
+ Object? _renderedTheme;
+ double _width = 0;
+
+ @override
+ void dispose() {
+ _rendered?.dispose();
+ super.dispose();
+ }
+
+ RenderedBlock _render(BuildContext context, double width) {
+ final content = widget.node.content;
+ final theme = Theme.of(context);
+ if (_rendered != null &&
+ _renderedFor == content &&
+ _renderedTheme == theme &&
+ _width == width) {
+ return _rendered!;
+ }
+ _rendered?.dispose();
+ final app = AppScope.read(context);
+ final ctx = RenderContext(
+ colors: context.colors,
+ base: blockTextStyle(context),
+ refs: app.refs,
+ assetPath: app.backend.assetPath,
+ onPage: app.openTitle,
+ onBlockRef: (r) => app.openId(r.pageId),
+ onUrl: openUrl,
+ onToggleTodo: () => widget.controller.cycleTodo(widget.node),
+ maxWidth: width,
+ );
+ _renderedFor = content;
+ _renderedTheme = theme;
+ _width = width;
+ return _rendered = BlockRenderer(ctx).render(content);
+ }
+
+ void _tap(TapUpDetails d) {
+ final rp = _key.currentContext?.findRenderObject();
+ var caret = widget.node.content.length;
+ if (rp is RenderParagraph && _rendered != null) {
+ final local = rp.globalToLocal(d.globalPosition);
+ if (local.dy <= rp.size.height) {
+ caret = _rendered!.toSource(rp.getPositionForOffset(local).offset);
+ }
+ }
+ widget.controller.focus(widget.node.id, caret: caret);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final app = AppScope.read(context);
+ final hasRef = widget.node.content.contains('((');
+ Widget build(double width) {
+ final r = _render(context, width);
+ return Text.rich(r.span, key: _key);
+ }
+
+ return LayoutBuilder(
+ builder: (context, box) => MouseRegion(
+ cursor: SystemMouseCursors.text,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapUp: _tap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ minHeight: blockFontSize * blockLineHeight,
+ ),
+ child: hasRef
+ ? ListenableBuilder(
+ listenable: app.refs,
+ builder: (context, _) {
+ _renderedFor = null;
+ return build(box.maxWidth);
+ },
+ )
+ : build(box.maxWidth),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Opens an external link. Replaced at startup with a platform launcher.
+void Function(String url) openUrl = (url) {};
+
+/// Edit mode of a block: raw Markdown with outliner key handling and autocomplete.
+class BlockEditor extends StatefulWidget {
+ const BlockEditor({super.key, required this.controller, required this.node});
+ final OutlineController controller;
+ final OutlineNode node;
+
+ @override
+ State createState() => _BlockEditorState();
+}
+
+class _BlockEditorState extends State {
+ late final TextEditingController _text;
+ late final FocusNode _focus;
+ final _fieldKey = GlobalKey();
+ final _link = LayerLink();
+ final _portal = OverlayPortalController();
+ TextEditingValue _last = TextEditingValue.empty;
+ bool _allowNewline = false;
+
+ CompletionQuery? _query;
+ List _items = const [];
+ int _selected = 0;
+ int _searchSeq = 0;
+
+ OutlineController get c => widget.controller;
+ OutlineNode get n => widget.node;
+
+ @override
+ void initState() {
+ super.initState();
+ final caret = (c.pendingCaret ?? n.content.length).clamp(
+ 0,
+ n.content.length,
+ );
+ c.pendingCaret = null;
+ _text = TextEditingController.fromValue(
+ TextEditingValue(
+ text: n.content,
+ selection: TextSelection.collapsed(offset: caret),
+ ),
+ );
+ _last = _text.value;
+ _focus = FocusNode(debugLabel: 'block', onKeyEvent: _onKey);
+ _focus.addListener(_focusChanged);
+ c.addListener(_controllerChanged);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ c.removeListener(_controllerChanged);
+ _focus.removeListener(_focusChanged);
+ _focus.dispose();
+ _text.dispose();
+ super.dispose();
+ }
+
+ void _focusChanged() {
+ if (!_focus.hasFocus) {
+ _closeCompletion();
+ // Defer: focus may be moving to another block of the same outline.
+ scheduleMicrotask(() {
+ if (mounted && !_focus.hasFocus) c.blurred(n.id);
+ });
+ }
+ }
+
+ /// Applies caret requests and external content changes (merges, todo toggles).
+ void _controllerChanged() {
+ if (!mounted || c.focusedId != n.id) return;
+ final caret = c.pendingCaret;
+ if (n.content != _text.text || caret != null) {
+ c.pendingCaret = null;
+ final off = (caret ?? _text.selection.extentOffset).clamp(
+ 0,
+ n.content.length,
+ );
+ _text.value = TextEditingValue(
+ text: n.content,
+ selection: TextSelection.collapsed(offset: off),
+ );
+ _last = _text.value;
+ }
+ if (!_focus.hasFocus) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && c.focusedId == n.id) _focus.requestFocus();
+ });
+ }
+ }
+
+ void _onChanged(String _) {
+ var v = _text.value;
+ // A newline that did not come from Shift+Enter (soft keyboards send Enter as text):
+ // split the block instead.
+ if (!_allowNewline &&
+ v.text.length == _last.text.length + 1 &&
+ v.selection.isCollapsed &&
+ v.selection.baseOffset > 0 &&
+ v.text[v.selection.baseOffset - 1] == '\n') {
+ final at = v.selection.baseOffset - 1;
+ final restored = v.text.substring(0, at) + v.text.substring(at + 1);
+ c.setText(n, restored);
+ c.split(n, at);
+ return;
+ }
+ _allowNewline = false;
+ final paired = autoPair(_last, v);
+ if (paired != null) {
+ _text.value = paired;
+ v = paired;
+ }
+ _last = v;
+ c.setText(n, v.text);
+ _updateCompletion();
+ }
+
+ // -------------------------------------------------------- completion
+
+ void _updateCompletion() {
+ final sel = _text.selection;
+ final q = sel.isCollapsed
+ ? detectCompletion(_text.text, sel.baseOffset)
+ : null;
+ if (q == null || (q.kind == CompletionKind.tag && q.query.isEmpty)) {
+ _closeCompletion();
+ return;
+ }
+ if (q == _query) return;
+ _query = q;
+ final seq = ++_searchSeq;
+ final backend = c.backend;
+ Future> search() async {
+ if (q.kind == CompletionKind.block) {
+ final hits = await backend.searchBlocks(q.query, limit: 8);
+ return [
+ for (final h in hits)
+ if (h.id != n.id)
+ CompletionItem(
+ h.content.split('\n').first,
+ h.id,
+ detail: h.pageTitle,
+ ),
+ ];
+ }
+ final hits = await backend.searchTitles(q.query, limit: 8);
+ final items = [
+ for (final h in hits)
+ CompletionItem(h.title, h.title, detail: h.isAlias ? 'alias' : null),
+ ];
+ final query = q.query.trim();
+ if (query.isNotEmpty &&
+ !items.any((i) => i.value.toLowerCase() == query.toLowerCase())) {
+ items.add(CompletionItem(query, query, isNew: true));
+ }
+ return items;
+ }
+
+ search().then((items) {
+ if (!mounted || seq != _searchSeq) return;
+ setState(() {
+ _items = items;
+ _selected = 0;
+ });
+ if (items.isEmpty) {
+ _portal.hide();
+ } else {
+ _portal.show();
+ }
+ }, onError: (Object _) {});
+ }
+
+ void _closeCompletion() {
+ _searchSeq++;
+ _query = null;
+ if (_items.isNotEmpty && mounted) setState(() => _items = const []);
+ if (_portal.isShowing) _portal.hide();
+ }
+
+ bool get _completing => _query != null && _items.isNotEmpty;
+
+ void _accept(int i) {
+ final q = _query;
+ if (q == null || i >= _items.length) return;
+ final v = applyCompletion(
+ _text.text,
+ _text.selection.baseOffset,
+ q,
+ _items[i],
+ );
+ _closeCompletion();
+ _text.value = v;
+ _last = v;
+ c.setText(n, v.text);
+ }
+
+ // -------------------------------------------------------------- keys
+
+ RenderEditable? _editable() {
+ RenderEditable? found;
+ void visit(RenderObject o) {
+ if (found != null) return;
+ if (o is RenderEditable) {
+ found = o;
+ return;
+ }
+ o.visitChildren(visit);
+ }
+
+ final ro = _fieldKey.currentContext?.findRenderObject();
+ if (ro != null) visit(ro);
+ return found;
+ }
+
+ /// Whether the caret is on the first (or last) visual line, wrapping included.
+ bool _onEdgeLine({required bool top}) {
+ final re = _editable();
+ if (re == null || !re.hasSize) return true;
+ final caret = _text.selection.extentOffset;
+ final rect = re.getLocalRectForCaret(TextPosition(offset: caret));
+ final lh = re.preferredLineHeight;
+ return top ? rect.top < lh * 0.5 : rect.bottom > re.size.height - lh * 0.5;
+ }
+
+ int get _column {
+ final caret = _text.selection.extentOffset;
+ final lineStart =
+ _text.text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1;
+ return caret - lineStart;
+ }
+
+ KeyEventResult _onKey(FocusNode _, KeyEvent e) {
+ if (e is! KeyDownEvent && e is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final kb = HardwareKeyboard.instance;
+ final shift = kb.isShiftPressed;
+ final ctrl = kb.isControlPressed || kb.isMetaPressed;
+ final alt = kb.isAltPressed;
+ final key = e.logicalKey;
+ final sel = _text.selection;
+ final collapsed = sel.isValid && sel.isCollapsed;
+ final caret = sel.isValid ? sel.extentOffset : _text.text.length;
+ final len = _text.text.length;
+
+ if (_completing) {
+ if (key == LogicalKeyboardKey.arrowDown) {
+ setState(() => _selected = (_selected + 1) % _items.length);
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.arrowUp) {
+ setState(
+ () => _selected = (_selected - 1 + _items.length) % _items.length,
+ );
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter ||
+ key == LogicalKeyboardKey.tab) {
+ _accept(_selected);
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.escape) {
+ _closeCompletion();
+ return KeyEventResult.handled;
+ }
+ }
+
+ if (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter) {
+ if (shift) {
+ _allowNewline = true;
+ return KeyEventResult.ignored;
+ }
+ if (ctrl) {
+ final shiftBy = c.cycleTodo(n);
+ c.pendingCaret = (caret + shiftBy).clamp(0, n.content.length);
+ _controllerChanged();
+ return KeyEventResult.handled;
+ }
+ if (sel.isValid && !collapsed) {
+ c.setText(n, _text.text.replaceRange(sel.start, sel.end, ''));
+ }
+ c.split(n, sel.isValid ? sel.start : len);
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.tab) {
+ if (shift) {
+ c.outdent(n, caret: caret);
+ } else {
+ c.indent(n, caret: caret);
+ }
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.backspace &&
+ collapsed &&
+ caret == 0 &&
+ !ctrl) {
+ return c.mergeIntoPrevious(n)
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ if (key == LogicalKeyboardKey.delete &&
+ collapsed &&
+ caret == len &&
+ !ctrl) {
+ return c.mergeNext(n) ? KeyEventResult.handled : KeyEventResult.ignored;
+ }
+ if (key == LogicalKeyboardKey.arrowUp ||
+ key == LogicalKeyboardKey.arrowDown) {
+ final up = key == LogicalKeyboardKey.arrowUp;
+ if (alt && shift) {
+ c.moveAmongSiblings(n, up: up, caret: caret);
+ return KeyEventResult.handled;
+ }
+ if (ctrl && !shift && !alt) {
+ if (up != n.collapsed && c.hasChildren(n)) c.toggleCollapsed(n);
+ return KeyEventResult.handled;
+ }
+ if (shift || alt || ctrl) return KeyEventResult.ignored;
+ if (!_onEdgeLine(top: up)) return KeyEventResult.ignored;
+ final other = up ? c.previousVisible(n) : c.nextVisible(n);
+ if (other == null) return KeyEventResult.ignored;
+ final col = _column;
+ final t = other.content;
+ final int target;
+ if (up) {
+ final ls = t.lastIndexOf('\n') + 1;
+ target = ls + col.clamp(0, t.length - ls);
+ } else {
+ final le = t.indexOf('\n');
+ target = col.clamp(0, le < 0 ? t.length : le);
+ }
+ c.focus(other.id, caret: target);
+ return KeyEventResult.handled;
+ }
+ if (!shift && !ctrl && !alt && collapsed) {
+ if (key == LogicalKeyboardKey.arrowLeft && caret == 0) {
+ final prev = c.previousVisible(n);
+ if (prev != null) {
+ c.focus(prev.id, caret: prev.content.length);
+ return KeyEventResult.handled;
+ }
+ }
+ if (key == LogicalKeyboardKey.arrowRight && caret == len) {
+ final next = c.nextVisible(n);
+ if (next != null) {
+ c.focus(next.id, caret: 0);
+ return KeyEventResult.handled;
+ }
+ }
+ }
+ if (key == LogicalKeyboardKey.escape) {
+ _focus.unfocus();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.colors;
+ return CompositedTransformTarget(
+ link: _link,
+ child: OverlayPortal(
+ controller: _portal,
+ overlayChildBuilder: (context) => CompositedTransformFollower(
+ link: _link,
+ targetAnchor: Alignment.bottomLeft,
+ offset: const Offset(0, 4),
+ child: Align(
+ alignment: Alignment.topLeft,
+ child: TextFieldTapRegion(
+ child: CompletionPopup(
+ items: _items,
+ selected: _selected,
+ kind: _query?.kind ?? CompletionKind.page,
+ onSelect: _accept,
+ ),
+ ),
+ ),
+ ),
+ child: TextField(
+ key: _fieldKey,
+ controller: _text,
+ focusNode: _focus,
+ onChanged: _onChanged,
+ maxLines: null,
+ keyboardType: TextInputType.multiline,
+ textInputAction: TextInputAction.newline,
+ style: blockTextStyle(context).copyWith(fontFamily: uiFont),
+ cursorColor: colors.accent,
+ cursorWidth: 1.6,
+ decoration: const InputDecoration.collapsed(hintText: null),
+ ),
+ ),
+ );
+ }
+}
+
+class CompletionPopup extends StatelessWidget {
+ const CompletionPopup({
+ super.key,
+ required this.items,
+ required this.selected,
+ required this.kind,
+ required this.onSelect,
+ });
+
+ final List items;
+ final int selected;
+ final CompletionKind kind;
+ final void Function(int) onSelect;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.colors;
+ return Material(
+ color: colors.paper,
+ elevation: 0,
+ borderRadius: BorderRadius.circular(10),
+ child: Container(
+ width: 340,
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(
+ color: colors.paper,
+ borderRadius: BorderRadius.circular(10),
+ border: Border.all(color: colors.line),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withAlpha(0x1F),
+ blurRadius: 24,
+ offset: const Offset(0, 8),
+ ),
+ ],
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (var i = 0; i < items.length; i++)
+ MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: () => onSelect(i),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 7,
+ ),
+ decoration: BoxDecoration(
+ color: i == selected ? colors.accentSoft : null,
+ borderRadius: BorderRadius.circular(7),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ items[i].isNew
+ ? Icons.add_rounded
+ : kind == CompletionKind.block
+ ? Icons.notes_rounded
+ : kind == CompletionKind.tag
+ ? Icons.tag_rounded
+ : Icons.description_outlined,
+ size: 15,
+ color: i == selected ? colors.accent : colors.muted,
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ items[i].isNew
+ ? 'New page “${items[i].label}”'
+ : items[i].label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(fontSize: 13.5, color: colors.ink),
+ ),
+ ),
+ if (items[i].detail != null) ...[
+ const SizedBox(width: 8),
+ Text(
+ items[i].detail!,
+ style: TextStyle(fontSize: 12, color: colors.faint),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/app/lib/src/editor/completion.dart b/app/lib/src/editor/completion.dart
new file mode 100644
index 0000000..1d14a89
--- /dev/null
+++ b/app/lib/src/editor/completion.dart
@@ -0,0 +1,141 @@
+import 'package:flutter/services.dart';
+
+enum CompletionKind { page, tag, block }
+
+/// An autocomplete trigger under the caret: `[[query`, `#query` or `((query`.
+class CompletionQuery {
+ const CompletionQuery(this.kind, this.start, this.query);
+
+ final CompletionKind kind;
+
+ /// Index where the query text starts (right after the trigger).
+ final int start;
+ final String query;
+
+ @override
+ bool operator ==(Object other) =>
+ other is CompletionQuery &&
+ other.kind == kind &&
+ other.start == start &&
+ other.query == query;
+
+ @override
+ int get hashCode => Object.hash(kind, start, query);
+}
+
+/// One suggestion. `value` is the page title or the block id to insert.
+class CompletionItem {
+ const CompletionItem(
+ this.label,
+ this.value, {
+ this.detail,
+ this.isNew = false,
+ });
+ final String label;
+ final String value;
+ final String? detail;
+ final bool isNew;
+}
+
+bool _ws(String c) => c.trim().isEmpty;
+
+/// Finds the autocomplete trigger that the caret is in, if any.
+CompletionQuery? detectCompletion(String text, int caret) {
+ if (caret < 0 || caret > text.length) return null;
+ final lineStart = text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1;
+ final before = text.substring(lineStart, caret);
+ CompletionQuery? best;
+ void consider(CompletionQuery q) {
+ if (best == null || q.start > best!.start) best = q;
+ }
+
+ final link = before.lastIndexOf('[[');
+ if (link >= 0 && !before.substring(link + 2).contains(']]')) {
+ consider(
+ CompletionQuery(
+ CompletionKind.page,
+ lineStart + link + 2,
+ before.substring(link + 2),
+ ),
+ );
+ }
+ final ref = before.lastIndexOf('((');
+ if (ref >= 0 && !before.substring(ref + 2).contains('))')) {
+ consider(
+ CompletionQuery(
+ CompletionKind.block,
+ lineStart + ref + 2,
+ before.substring(ref + 2),
+ ),
+ );
+ }
+ final hash = before.lastIndexOf('#');
+ if (hash >= 0 && (hash == 0 || _ws(before[hash - 1]))) {
+ final q = before.substring(hash + 1);
+ if (!q.startsWith('[') &&
+ !q.contains(RegExp(r'\s')) &&
+ !q.startsWith('#')) {
+ // A bare `#` followed by a space is a heading, not a tag.
+ consider(CompletionQuery(CompletionKind.tag, lineStart + hash + 1, q));
+ }
+ }
+ return best;
+}
+
+/// Text after accepting `item` for `q` with the caret at `caret`.
+TextEditingValue applyCompletion(
+ String text,
+ int caret,
+ CompletionQuery q,
+ CompletionItem item,
+) {
+ final head = text.substring(0, q.start);
+ var tail = text.substring(caret);
+ switch (q.kind) {
+ case CompletionKind.page:
+ if (tail.startsWith(']]')) tail = tail.substring(2);
+ final t = '$head${item.value}]]';
+ return TextEditingValue(
+ text: t + tail,
+ selection: TextSelection.collapsed(offset: t.length),
+ );
+ case CompletionKind.block:
+ if (tail.startsWith('))')) tail = tail.substring(2);
+ final t = '$head${item.value}))';
+ return TextEditingValue(
+ text: t + tail,
+ selection: TextSelection.collapsed(offset: t.length),
+ );
+ case CompletionKind.tag:
+ final v = item.value.contains(RegExp(r'\s'))
+ ? '[[${item.value}]]'
+ : item.value;
+ final sep = tail.startsWith(' ') ? '' : ' ';
+ final t = '$head$v$sep';
+ return TextEditingValue(
+ text: t + tail,
+ selection: TextSelection.collapsed(offset: t.length),
+ );
+ }
+}
+
+/// Auto-pairs `[[` → `[[]]` and `((` → `(())` right after the second bracket is typed.
+TextEditingValue? autoPair(TextEditingValue old, TextEditingValue now) {
+ if (now.text.length != old.text.length + 1 || !now.selection.isCollapsed) {
+ return null;
+ }
+ final c = now.selection.baseOffset;
+ if (c < 2) return null;
+ final typed = now.text[c - 1];
+ final close = switch (typed) {
+ '[' => ']]',
+ '(' => '))',
+ _ => null,
+ };
+ if (close == null || now.text[c - 2] != typed) return null;
+ if (now.text.substring(c).startsWith(close[0])) return null;
+ return TextEditingValue(
+ text: now.text.substring(0, c) + close + now.text.substring(c),
+ selection: TextSelection.collapsed(offset: c),
+ );
+}
diff --git a/app/lib/src/editor/markdown.dart b/app/lib/src/editor/markdown.dart
new file mode 100644
index 0000000..d773882
--- /dev/null
+++ b/app/lib/src/editor/markdown.dart
@@ -0,0 +1,638 @@
+import 'dart:io';
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+
+import '../state/app_state.dart';
+import '../theme/theme.dart';
+
+/// Maps a run of rendered text back to its Markdown source, so a tap on rendered text can
+/// place the caret at the matching spot of the raw text.
+class SourceRun {
+ const SourceRun(
+ this.r0,
+ this.rLen,
+ this.s0,
+ this.sLen, {
+ this.atomic = false,
+ });
+ final int r0;
+ final int rLen;
+ final int s0;
+ final int sLen;
+
+ /// Rendered differently from the source (widgets, resolved refs): maps to its end.
+ final bool atomic;
+}
+
+/// A rendered block: its span tree, the source mapping and the recognizers to dispose.
+class RenderedBlock {
+ RenderedBlock(this.span, this.runs, this.recognizers);
+
+ final InlineSpan span;
+ final List runs;
+ final List recognizers;
+
+ /// Source offset for a rendered text offset.
+ int toSource(int rendered) {
+ SourceRun? best;
+ for (final r in runs) {
+ if (rendered < r.r0) break;
+ best = r;
+ if (rendered < r.r0 + r.rLen) break;
+ }
+ if (best == null) return 0;
+ if (best.atomic) return best.s0 + best.sLen;
+ final d = (rendered - best.r0).clamp(0, best.sLen);
+ return best.s0 + d;
+ }
+
+ void dispose() {
+ for (final r in recognizers) {
+ r.dispose();
+ }
+ }
+}
+
+/// Callbacks and context for rendering.
+class RenderContext {
+ const RenderContext({
+ required this.colors,
+ required this.base,
+ required this.refs,
+ required this.assetPath,
+ required this.onPage,
+ required this.onBlockRef,
+ required this.onUrl,
+ this.onToggleTodo,
+ this.maxWidth = 600,
+ });
+
+ final SynapseColors colors;
+ final TextStyle base;
+ final BlockRefCache refs;
+ final String? Function(String hash) assetPath;
+ final void Function(String title) onPage;
+ final void Function(BlockRefDtoLike ref) onBlockRef;
+ final void Function(String url) onUrl;
+ final VoidCallback? onToggleTodo;
+ final double maxWidth;
+}
+
+/// The bits of a block ref the renderer needs (keeps this file free of FFI types).
+class BlockRefDtoLike {
+ const BlockRefDtoLike(this.id, this.pageId);
+ final String id;
+ final String pageId;
+}
+
+final _marker = RegExp(r'^(TODO|DOING|NOW|LATER|DONE|CANCELED|CANCELLED) ');
+final _heading = RegExp(r'^(#{1,6}) ');
+final _uuid = RegExp(
+ r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
+);
+final _property = RegExp(r'^([A-Za-z0-9_\-]+):: ?(.*)$');
+
+/// Renders Logseq-flavoured Markdown of one block into a single [InlineSpan] tree.
+class BlockRenderer {
+ BlockRenderer(this.ctx);
+
+ final RenderContext ctx;
+ final _spans = [];
+ final _runs = [];
+ final _recognizers = [];
+ int _r = 0;
+
+ RenderedBlock render(String src) {
+ final lines = src.split('\n');
+ var off = 0;
+ var fenceStart = -1;
+ final fence = StringBuffer();
+ for (var li = 0; li < lines.length; li++) {
+ final line = lines[li];
+ final lineStart = off;
+ off += line.length + 1;
+ if (fenceStart >= 0) {
+ if (line.trimLeft().startsWith('```')) {
+ _codeBlock(fence.toString(), fenceStart, off - 1 - fenceStart);
+ fenceStart = -1;
+ fence.clear();
+ } else {
+ if (fence.isNotEmpty) fence.write('\n');
+ fence.write(line);
+ }
+ continue;
+ }
+ if (li > 0) _text('\n', lineStart - 1, ctx.base);
+ if (line.trimLeft().startsWith('```')) {
+ fenceStart = lineStart;
+ continue;
+ }
+ _line(line, lineStart, first: li == 0);
+ }
+ if (fenceStart >= 0) {
+ _codeBlock(fence.toString(), fenceStart, src.length - fenceStart);
+ }
+ return RenderedBlock(
+ TextSpan(style: ctx.base, children: List.of(_spans)),
+ List.of(_runs),
+ List.of(_recognizers),
+ );
+ }
+
+ void _line(String line, int off, {required bool first}) {
+ var style = ctx.base;
+ var i = 0;
+ if (first) {
+ final m = _marker.firstMatch(line);
+ if (m != null) {
+ final done = m.group(1) == 'DONE';
+ final canceled = m.group(1)!.startsWith('CANCEL');
+ _atomic(_checkbox(done || canceled), 1, off, m.end);
+ if (done || canceled) {
+ style = style.copyWith(
+ color: ctx.colors.muted,
+ decoration: TextDecoration.lineThrough,
+ decorationColor: ctx.colors.faint,
+ );
+ } else if (m.group(1) != 'TODO' && m.group(1) != 'LATER') {
+ _text(
+ '${m.group(1)} ',
+ off,
+ style.copyWith(
+ color: ctx.colors.accent,
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ ),
+ );
+ }
+ i = m.end;
+ }
+ }
+ final rest = line.substring(i);
+ final h = _heading.firstMatch(rest);
+ if (h != null) {
+ final level = h.group(1)!.length;
+ const sizes = [26.0, 22.0, 19.0, 17.0, 16.0, 15.0];
+ style = style.copyWith(
+ fontSize: sizes[level - 1],
+ fontWeight: level <= 2 ? FontWeight.w700 : FontWeight.w600,
+ height: 1.35,
+ letterSpacing: level <= 2 ? -0.2 : 0,
+ );
+ _inline(rest.substring(h.end), off + i + h.end, style);
+ return;
+ }
+ final p = _property.firstMatch(rest);
+ if (p != null) {
+ final small = style.copyWith(fontSize: 13, color: ctx.colors.muted);
+ _text(
+ '${p.group(1)}: ',
+ off + i,
+ small.copyWith(fontWeight: FontWeight.w600),
+ );
+ _inline(p.group(2)!, off + i + rest.length - p.group(2)!.length, small);
+ return;
+ }
+ if (rest.startsWith('> ')) {
+ _atomic(
+ WidgetSpan(
+ alignment: PlaceholderAlignment.middle,
+ child: Container(
+ width: 3,
+ height: 18,
+ margin: const EdgeInsets.only(right: 8),
+ color: ctx.colors.line,
+ ),
+ ),
+ 1,
+ off + i,
+ 2,
+ );
+ _inline(
+ rest.substring(2),
+ off + i + 2,
+ style.copyWith(color: ctx.colors.muted, fontStyle: FontStyle.italic),
+ );
+ return;
+ }
+ final list = RegExp(r'^(\s*)([-*+]|\d+\.) ').firstMatch(rest);
+ if (list != null) {
+ final bullet = list.group(2)!.endsWith('.') ? list.group(2)! : '•';
+ _atomic(
+ TextSpan(
+ text: '${list.group(1)}$bullet ',
+ style: style.copyWith(color: ctx.colors.muted),
+ ),
+ list.group(1)!.length + bullet.length + 1,
+ off + i,
+ list.end,
+ );
+ _inline(rest.substring(list.end), off + i + list.end, style);
+ return;
+ }
+ _inline(rest, off + i, style);
+ }
+
+ void _inline(String s, int off, TextStyle style) {
+ var i = 0;
+ var plain = 0;
+ void flush(int to) {
+ if (to > plain) _text(s.substring(plain, to), off + plain, style);
+ }
+
+ bool ws(int k) => k < 0 || k >= s.length || s[k].trim().isEmpty;
+
+ while (i < s.length) {
+ final c = s[i];
+ // `code`
+ if (c == '`') {
+ final j = s.indexOf('`', i + 1);
+ if (j > i + 1) {
+ flush(i);
+ _text(
+ s.substring(i + 1, j),
+ off + i + 1,
+ style.copyWith(
+ fontFamily: monoFont,
+ fontSize: (style.fontSize ?? blockFontSize) - 1.5,
+ backgroundColor: ctx.colors.codeBg,
+ color: ctx.colors.ink,
+ ),
+ );
+ i = plain = j + 1;
+ continue;
+ }
+ }
+ // 
+ if (s.startsWith('![', i)) {
+ final link = _mdLink(s, i + 1);
+ if (link != null) {
+ flush(i);
+ _atomic(_image(link.$2, link.$1), 1, off + i, link.$3 - i);
+ i = plain = link.$3;
+ continue;
+ }
+ }
+ // [[Page]]
+ if (s.startsWith('[[', i)) {
+ final close = _findClose(s, i + 2);
+ if (close != null && close > i + 2) {
+ flush(i);
+ final title = s.substring(i + 2, close);
+ _text(
+ title,
+ off + i + 2,
+ style.copyWith(
+ color: ctx.colors.accent,
+ fontWeight: FontWeight.w500,
+ ),
+ onTap: () => ctx.onPage(title),
+ );
+ i = plain = close + 2;
+ continue;
+ }
+ }
+ // ((block ref))
+ if (s.startsWith('((', i)) {
+ final j = s.indexOf('))', i + 2);
+ if (j > 0 && _uuid.hasMatch(s.substring(i + 2, j))) {
+ flush(i);
+ _blockRef(s.substring(i + 2, j), off + i, j + 2 - i, style);
+ i = plain = j + 2;
+ continue;
+ }
+ }
+ // #tag, #[[tag]]
+ if (c == '#' && ws(i - 1) && i + 1 < s.length) {
+ String? tag;
+ var end = i;
+ if (s.startsWith('#[[', i)) {
+ final close = _findClose(s, i + 3);
+ if (close != null && close > i + 3) {
+ tag = s.substring(i + 3, close);
+ end = close + 2;
+ }
+ } else {
+ var j = i + 1;
+ while (j < s.length && !_tagStop(s[j])) {
+ j++;
+ }
+ // Trailing punctuation is not part of the tag.
+ while (j > i + 1 && '.!?;:'.contains(s[j - 1])) {
+ j--;
+ }
+ if (j > i + 1) {
+ tag = s.substring(i + 1, j);
+ end = j;
+ }
+ }
+ if (tag != null) {
+ flush(i);
+ final t = tag;
+ final tagStyle = style.copyWith(
+ color: ctx.colors.accent.withAlpha(0xCC),
+ );
+ if (end - i == t.length + 1) {
+ _text('#$t', off + i, tagStyle, onTap: () => ctx.onPage(t));
+ } else {
+ _text('#', off + i, tagStyle, onTap: () => ctx.onPage(t));
+ _text(t, off + i + 3, tagStyle, onTap: () => ctx.onPage(t));
+ }
+ i = plain = end;
+ continue;
+ }
+ }
+ // **bold**, __bold__, ~~strike~~, ==highlight==
+ final pair = s.length > i + 1 ? s.substring(i, i + 2) : '';
+ if (pair == '**' || pair == '__' || pair == '~~' || pair == '==') {
+ final j = s.indexOf(pair, i + 2);
+ if (j > i + 2) {
+ flush(i);
+ final inner = switch (pair) {
+ '~~' => style.copyWith(
+ decoration: TextDecoration.lineThrough,
+ color: ctx.colors.muted,
+ ),
+ '==' => style.copyWith(backgroundColor: ctx.colors.highlight),
+ _ => style.copyWith(fontWeight: FontWeight.w700),
+ };
+ _inline(s.substring(i + 2, j), off + i + 2, inner);
+ i = plain = j + 2;
+ continue;
+ }
+ }
+ // *italic*, _italic_
+ if ((c == '*' || (c == '_' && ws(i - 1))) &&
+ i + 1 < s.length &&
+ !ws(i + 1)) {
+ var j = s.indexOf(c, i + 1);
+ while (j > 0 && (ws(j - 1) || (c == '_' && !ws(j + 1)))) {
+ j = s.indexOf(c, j + 1);
+ }
+ if (j > i + 1) {
+ flush(i);
+ _inline(
+ s.substring(i + 1, j),
+ off + i + 1,
+ style.copyWith(fontStyle: FontStyle.italic),
+ );
+ i = plain = j + 1;
+ continue;
+ }
+ }
+ // [label](url)
+ if (c == '[') {
+ final link = _mdLink(s, i);
+ if (link != null) {
+ flush(i);
+ final url = link.$2;
+ _text(
+ link.$1,
+ off + i + 1,
+ style.copyWith(
+ color: ctx.colors.accent,
+ decoration: TextDecoration.underline,
+ decorationColor: ctx.colors.accent.withAlpha(0x66),
+ ),
+ onTap: () => ctx.onUrl(url),
+ );
+ i = plain = link.$3;
+ continue;
+ }
+ }
+ // bare URL
+ if ((s.startsWith('https://', i) || s.startsWith('http://', i)) &&
+ ws(i - 1)) {
+ var j = i;
+ while (j < s.length && !ws(j)) {
+ j++;
+ }
+ while (j > i && '.,;:!?)'.contains(s[j - 1])) {
+ j--;
+ }
+ flush(i);
+ final url = s.substring(i, j);
+ _text(
+ url,
+ off + i,
+ style.copyWith(
+ color: ctx.colors.accent,
+ decoration: TextDecoration.underline,
+ decorationColor: ctx.colors.accent.withAlpha(0x66),
+ ),
+ onTap: () => ctx.onUrl(url),
+ );
+ i = plain = j;
+ continue;
+ }
+ i++;
+ }
+ flush(s.length);
+ }
+
+ static bool _tagStop(String ch) =>
+ ch.trim().isEmpty || ',()[]{}"\'`#'.contains(ch);
+
+ /// `[label](target)` starting at `i` (the `[`): (label, target, end).
+ static (String, String, int)? _mdLink(String s, int i) {
+ if (i >= s.length || s[i] != '[') return null;
+ final close = s.indexOf('](', i + 1);
+ if (close < 0 || s.substring(i + 1, close).contains('\n')) return null;
+ final end = s.indexOf(')', close + 2);
+ if (end < 0) return null;
+ final target = s.substring(close + 2, end).trim();
+ if (target.isEmpty || target.contains(' ')) return null;
+ return (s.substring(i + 1, close), target, end + 1);
+ }
+
+ /// Index of the `]]` closing a `[[` whose content starts at `from` (nesting aware).
+ static int? _findClose(String s, int from) {
+ var depth = 1;
+ var i = from;
+ while (i < s.length - 1) {
+ if (s.startsWith('[[', i)) {
+ depth++;
+ i += 2;
+ } else if (s.startsWith(']]', i)) {
+ depth--;
+ if (depth == 0) return i;
+ i += 2;
+ } else {
+ if (s[i] == '\n') return null;
+ i++;
+ }
+ }
+ return null;
+ }
+
+ void _text(String t, int s0, TextStyle style, {VoidCallback? onTap}) {
+ if (t.isEmpty) return;
+ TapGestureRecognizer? rec;
+ if (onTap != null) {
+ rec = TapGestureRecognizer()..onTap = onTap;
+ _recognizers.add(rec);
+ }
+ _spans.add(
+ TextSpan(
+ text: t,
+ style: style,
+ recognizer: rec,
+ mouseCursor: rec == null ? null : SystemMouseCursors.click,
+ ),
+ );
+ _runs.add(SourceRun(_r, t.length, s0, t.length));
+ _r += t.length;
+ }
+
+ void _atomic(InlineSpan span, int rLen, int s0, int sLen) {
+ _spans.add(span);
+ _runs.add(SourceRun(_r, rLen, s0, sLen, atomic: true));
+ _r += rLen;
+ }
+
+ void _blockRef(String id, int s0, int sLen, TextStyle style) {
+ final ref = ctx.refs.get(id);
+ final String text;
+ if (ref != null) {
+ final first = ref.content.split('\n').first.replaceFirst(_marker, '');
+ text = first.isEmpty ? '(empty block)' : first;
+ } else {
+ text = ctx.refs.isMissing(id) ? '((missing block))' : '…';
+ }
+ TapGestureRecognizer? rec;
+ if (ref != null) {
+ rec = TapGestureRecognizer()
+ ..onTap = () => ctx.onBlockRef(BlockRefDtoLike(ref.id, ref.pageId));
+ _recognizers.add(rec);
+ }
+ _spans.add(
+ TextSpan(
+ text: text,
+ recognizer: rec,
+ mouseCursor: rec == null ? null : SystemMouseCursors.click,
+ style: style.copyWith(
+ decoration: TextDecoration.underline,
+ decorationStyle: TextDecorationStyle.dotted,
+ decorationColor: ctx.colors.ref,
+ color: ref == null ? ctx.colors.faint : null,
+ ),
+ ),
+ );
+ _runs.add(SourceRun(_r, text.length, s0, sLen, atomic: true));
+ _r += text.length;
+ }
+
+ InlineSpan _checkbox(bool checked) {
+ final c = ctx.colors;
+ return WidgetSpan(
+ alignment: PlaceholderAlignment.middle,
+ child: Padding(
+ padding: const EdgeInsets.only(right: 7),
+ child: MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: ctx.onToggleTodo,
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 140),
+ width: 15,
+ height: 15,
+ decoration: BoxDecoration(
+ color: checked ? c.done : Colors.transparent,
+ borderRadius: BorderRadius.circular(4),
+ border: Border.all(
+ color: checked ? c.done : c.faint,
+ width: 1.5,
+ ),
+ ),
+ child: checked
+ ? Icon(Icons.check_rounded, size: 12, color: c.paper)
+ : null,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ InlineSpan _image(String src, String alt) {
+ Widget img;
+ if (src.startsWith('asset://')) {
+ final path = ctx.assetPath(src.substring(8));
+ img = path == null
+ ? _missing(alt.isEmpty ? 'missing asset' : alt)
+ : Image.file(
+ File(path),
+ fit: BoxFit.contain,
+ cacheWidth: (ctx.maxWidth * 2).round(),
+ errorBuilder: (_, _, _) => _missing(alt),
+ );
+ } else if (src.startsWith('http://') || src.startsWith('https://')) {
+ img = Image.network(
+ src,
+ fit: BoxFit.contain,
+ errorBuilder: (_, _, _) => _missing(alt),
+ );
+ } else {
+ img = _missing(alt.isEmpty ? src : alt);
+ }
+ return WidgetSpan(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: 360, maxWidth: ctx.maxWidth),
+ child: ClipRRect(borderRadius: BorderRadius.circular(8), child: img),
+ ),
+ ),
+ );
+ }
+
+ Widget _missing(String label) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(
+ color: ctx.colors.surface,
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(color: ctx.colors.line),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.image_not_supported_outlined,
+ size: 14,
+ color: ctx.colors.muted,
+ ),
+ const SizedBox(width: 6),
+ Text(label, style: TextStyle(fontSize: 12, color: ctx.colors.muted)),
+ ],
+ ),
+ );
+
+ void _codeBlock(String code, int s0, int sLen) {
+ _atomic(
+ WidgetSpan(
+ child: Container(
+ width: ctx.maxWidth,
+ margin: const EdgeInsets.symmetric(vertical: 2),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: ctx.colors.codeBg,
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Text(
+ code,
+ style: TextStyle(
+ fontFamily: monoFont,
+ fontSize: 13,
+ height: 1.5,
+ color: ctx.colors.ink,
+ ),
+ ),
+ ),
+ ),
+ 1,
+ s0,
+ sLen,
+ );
+ }
+}
diff --git a/app/lib/src/editor/outline_view.dart b/app/lib/src/editor/outline_view.dart
new file mode 100644
index 0000000..6780b1b
--- /dev/null
+++ b/app/lib/src/editor/outline_view.dart
@@ -0,0 +1,91 @@
+import 'package:flutter/material.dart';
+
+import '../state/outline_controller.dart';
+import '../state/outline_ops.dart';
+import '../theme/theme.dart';
+import 'block_row.dart';
+
+/// The outline of one page as a lazily built sliver (only visible rows are built).
+class OutlineSliver extends StatelessWidget {
+ const OutlineSliver({super.key, required this.controller});
+
+ final OutlineController controller;
+
+ @override
+ Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ final nodes = controller.nodes;
+ if (nodes.isEmpty) {
+ return SliverToBoxAdapter(
+ child: _EmptyOutline(onTap: controller.insertFirst),
+ );
+ }
+ final vis = controller.visible;
+ final keys =