diff --git a/.gitignore b/.gitignore index 3f360a5..65e1610 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# fvm (flutter version manager) +# TODO: remove this once this PR lands on stable https://github.com/flutter/flutter/issues/126531 +.fvm/flutter_sdk # Miscellaneous *.class *.log @@ -20,6 +23,8 @@ migrate_working_dir/ # VS Code which you may wish to be included in version control, so this line # is commented out by default. #.vscode/ +android/local.properties +ios/flutter/ # Flutter/Dart/Pub related # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..82aa313 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,29 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "example", + "cwd": "example", + "request": "launch", + "type": "dart", + "deviceId": "Chrome" + }, + { + "name": "example (profile mode)", + "cwd": "example", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + }, + { + "name": "example (release mode)", + "cwd": "example", + "request": "launch", + "type": "dart", + "flutterMode": "release" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..4ec39be --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cSpell.enabled": false +} \ No newline at end of file diff --git a/android/local.properties b/android/local.properties deleted file mode 100644 index afe9a3b..0000000 --- a/android/local.properties +++ /dev/null @@ -1,2 +0,0 @@ -sdk.dir=C:\\Users\\ahmed\\AppData\\Local\\Android\\Sdk -flutter.sdk=C:\\tools\\flutter \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..d9cb158 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,10 @@ +version: "3.8" + +services: + meilisearch: + image: getmeili/meilisearch:latest + ports: + - 7700:7700 + environment: + - MEILI_MASTER_KEY=masterKey + - MEILI_NO_ANALYTICS=true diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..8e54882 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,45 @@ +pubspec.lock +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +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 +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# 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 diff --git a/example/.metadata b/example/.metadata new file mode 100644 index 0000000..a83337a --- /dev/null +++ b/example/.metadata @@ -0,0 +1,39 @@ +# 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. + +version: + revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + channel: stable + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + base_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + - platform: android + create_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + base_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + - platform: ios + create_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + base_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + - platform: web + create_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + base_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + - platform: windows + create_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + base_revision: 84a1e904f44f9b0e9c4510138010edcc653163f8 + + # 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/example/README.md b/example/README.md new file mode 100644 index 0000000..b2bdce7 --- /dev/null +++ b/example/README.md @@ -0,0 +1,3 @@ +# example + +A new Flutter project. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..8e4c4f5 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1 @@ +include: package:flutter_lints/flutter.yaml diff --git a/example/android/.gitignore b/example/android/.gitignore new file mode 100644 index 0000000..5d99765 --- /dev/null +++ b/example/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle new file mode 100644 index 0000000..5add443 --- /dev/null +++ b/example/android/app/build.gradle @@ -0,0 +1,72 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + namespace "meilisearch.example" + compileSdkVersion flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "meilisearch.example" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + 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.debug + } + } +} + +flutter { + source '../..' +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..56b9291 --- /dev/null +++ b/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + diff --git a/example/android/app/src/main/kotlin/meilisearch/example/MainActivity.kt b/example/android/app/src/main/kotlin/meilisearch/example/MainActivity.kt new file mode 100644 index 0000000..3a27cda --- /dev/null +++ b/example/android/app/src/main/kotlin/meilisearch/example/MainActivity.kt @@ -0,0 +1,6 @@ +package meilisearch.example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..1cb7aa2 --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..8403758 --- /dev/null +++ b/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..360a160 --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..5fac679 --- /dev/null +++ b/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/build.gradle b/example/android/build.gradle new file mode 100644 index 0000000..0bd4dfd --- /dev/null +++ b/example/android/build.gradle @@ -0,0 +1,31 @@ +buildscript { + ext.kotlin_version = '1.7.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.3.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/example/android/gradle.properties b/example/android/gradle.properties new file mode 100644 index 0000000..46c1f16 --- /dev/null +++ b/example/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..eabb85f --- /dev/null +++ b/example/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-7.5-all.zip diff --git a/example/android/settings.gradle b/example/android/settings.gradle new file mode 100644 index 0000000..33f0745 --- /dev/null +++ b/example/android/settings.gradle @@ -0,0 +1,11 @@ +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/example/ios/.gitignore b/example/ios/.gitignore new file mode 100644 index 0000000..ad322bc --- /dev/null +++ b/example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..0d9747f --- /dev/null +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 11.0 + + diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..0b2d479 --- /dev/null +++ b/example/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..0b2d479 --- /dev/null +++ b/example/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3dcac48 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,613 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807E294A63A400263BE5 /* Frameworks */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AE0B7B92F70575B8D7E0D07E /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 89B67EB44CE7B6631473024E /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 640959BDD8F10B91D80A66BE /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = meilisearch.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..c4b79bd --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..af0309c --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c77b648 --- /dev/null +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..59c6d39 --- /dev/null +++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..af0309c --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..3763683 --- /dev/null +++ b/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..1950fd8 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..d08a4de --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..65a94b5 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..497371e --- /dev/null +++ b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..bbb83ca --- /dev/null +++ b/example/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist new file mode 100644 index 0000000..e734dc1 --- /dev/null +++ b/example/ios/Runner/Info.plist @@ -0,0 +1,51 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Example + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + example + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..fae207f --- /dev/null +++ b/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/example/ios/RunnerTests/RunnerTests.swift b/example/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..4d206de --- /dev/null +++ b/example/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 0000000..91251f8 --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,93 @@ +import 'package:example/setup.dart'; +import 'package:flutter/material.dart'; +import 'package:meilisearch/meilisearch.dart'; +import 'package:meilisearch_ui/meilisearch_ui.dart'; + +import 'src/models/book.dart'; + +final client = MeiliSearchClient('http://localhost:7700', 'masterKey'); +final indexFuture = setup(client); +void main() { + runApp(const MainApp()); +} + +class MainApp extends StatelessWidget { + const MainApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + home: FutureBuilder>( + future: indexFuture, + builder: (context, snapshot) => snapshot.hasData + ? HomePage( + indexes: snapshot.data!, + ) + : const Center(child: CircularProgressIndicator.adaptive()), + ), + ); + } +} + +class HomePage extends StatefulWidget { + const HomePage({ + super.key, + required this.indexes, + }); + final List indexes; + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + final sc = ScrollController(); + List get indexes => widget.indexes; + @override + Widget build(BuildContext context) { + return MeiliSearchOffsetBasedSearchQueryBuilder( + client: client, + mapper: Book.fromJson, + query: MultiSearchQuery( + queries: indexes + .map( + (index) => IndexSearchQuery( + indexUid: index.uid, + query: '', + limit: 30, + ), + ) + .toList(), + ), + builder: (context, state, fetchMore, refresh) => Scaffold( + appBar: AppBar( + title: Text("Books (${state.itemCount})"), + actions: [ + IconButton(onPressed: refresh, icon: const Icon(Icons.refresh)), + IconButton(onPressed: fetchMore, icon: const Icon(Icons.more)), + ], + ), + body: ListView.builder( + controller: sc, + itemCount: state.itemCount + (state.isLoading ? 1 : 0), + itemBuilder: (context, index) { + if (index + 1 >= state.itemCount) { + fetchMore(); + } + + if (state.isLoading && index == state.itemCount) { + return const Center( + child: CircularProgressIndicator.adaptive(), + ); + } + final item = state.aggregatedResult[index]; + return ListTile( + title: Text('[$index] ${item.parsed.title}'), + subtitle: Text('id: ${item.parsed.id}'), + ); + }, + ), + ), + ); + } +} diff --git a/example/lib/setup.dart b/example/lib/setup.dart new file mode 100644 index 0000000..b4a6b60 --- /dev/null +++ b/example/lib/setup.dart @@ -0,0 +1,46 @@ +import 'dart:math'; +import 'wait_for.dart'; +import 'package:example/src/models/book.dart'; +import 'package:meilisearch/meilisearch.dart'; + +Future> setup(MeiliSearchClient client) async { + final indexTask = await client + .createIndex( + 'books_en_${Random().nextInt(1000)}', + primaryKey: 'id', + ) + .waitFor(client: client); + + final index1 = client.index(indexTask.indexUid!); + await index1.updateSearchableAttributes(['title']).waitFor(client: client); + await index1.updateDocuments( + List.generate( + 500, + (i) => Book( + id: i, + title: 'Book $i', + ).toJson(), + ), + ); + + final indexTask2 = await client + .createIndex( + 'books_ar_${Random().nextInt(1000)}', + primaryKey: 'id', + ) + .waitFor(client: client); + final index2 = client.index(indexTask2.indexUid!); + await index2.updateSearchableAttributes(['title']).waitFor(client: client); + await index2 + .updateDocuments( + List.generate( + 500, + (i) => Book( + id: i, + title: 'كتاب $i', + ).toJson(), + ), + ) + .waitFor(client: client); + return [index1, index2]; +} diff --git a/example/lib/src/models/book.dart b/example/lib/src/models/book.dart new file mode 100644 index 0000000..2fd5395 --- /dev/null +++ b/example/lib/src/models/book.dart @@ -0,0 +1,27 @@ +class Book { + final int id; + final String title; + + const Book({ + required this.id, + required this.title, + }); + + factory Book.fromJson(Map src) { + return Book( + id: src['id'], + title: src['title'], + ); + } + Map toJson() { + return { + 'id': id, + 'title': title, + }; + } + + @override + String toString() { + return title; + } +} diff --git a/example/lib/wait_for.dart b/example/lib/wait_for.dart new file mode 100644 index 0000000..42ef9c6 --- /dev/null +++ b/example/lib/wait_for.dart @@ -0,0 +1,113 @@ +import 'package:meilisearch/meilisearch.dart'; +import 'package:collection/collection.dart'; + +extension TaskWaiter on Task { + Future waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 5), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + var endingTime = DateTime.now().add(timeout); + + while (DateTime.now().isBefore(endingTime)) { + final task = await client.getTask(uid!); + + if (task.status != 'enqueued' && task.status != 'processing') { + if (throwFailed && task.status != 'succeeded') { + throw MeiliSearchApiException( + "Task ($uid) failed", + code: task.error?.code, + link: task.error?.link, + type: task.error?.type, + ); + } + return task; + } + + await Future.delayed(interval); + } + + throw Exception('The task $uid timed out.'); + } +} + +extension TaskWaiterForLists on Iterable { + Future> waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 20), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + final endingTime = DateTime.now().add(timeout); + final originalUids = toList(); + final remainingUids = map((e) => e.uid).whereNotNull().toList(); + final completedTasks = {}; + final statuses = ['enqueued', 'processing']; + + while (DateTime.now().isBefore(endingTime)) { + final taskRes = + await client.getTasks(params: TasksQuery(uids: remainingUids)); + final tasks = taskRes.results; + final completed = tasks.where((e) => !statuses.contains(e.status)); + if (throwFailed) { + final failed = completed + .firstWhereOrNull((element) => element.status != 'succeeded'); + if (failed != null) { + throw MeiliSearchApiException( + "Task (${failed.uid}) failed", + code: failed.error?.code, + link: failed.error?.link, + type: failed.error?.type, + ); + } + } + + completedTasks.addEntries(completed.map((e) => MapEntry(e.uid!, e))); + remainingUids + .removeWhere((element) => completedTasks.containsKey(element)); + + if (remainingUids.isEmpty) { + return originalUids + .map((e) => completedTasks[e.uid]) + .whereNotNull() + .toList(); + } + await Future.delayed(interval); + } + + throw Exception('The tasks $originalUids timed out.'); + } +} + +extension TaskWaiterForFutures on Future { + Future waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 5), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + return await (await this).waitFor( + timeout: timeout, + interval: interval, + client: client, + throwFailed: throwFailed, + ); + } +} + +extension TaskWaiterForFutureList on Future> { + Future> waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 20), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + return await (await this).waitFor( + timeout: timeout, + interval: interval, + client: client, + throwFailed: throwFailed, + ); + } +} diff --git a/example/pubspec.yaml b/example/pubspec.yaml new file mode 100644 index 0000000..d94fe5c --- /dev/null +++ b/example/pubspec.yaml @@ -0,0 +1,23 @@ +name: example +description: A new Flutter project. +publish_to: 'none' +version: 0.1.0 + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + collection: ^1.17.1 + flutter: + sdk: flutter + meilisearch: any + meilisearch_ui: + path: ../ + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + +flutter: + uses-material-design: true diff --git a/example/web/favicon.png b/example/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/example/web/favicon.png differ diff --git a/example/web/icons/Icon-192.png b/example/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/example/web/icons/Icon-192.png differ diff --git a/example/web/icons/Icon-512.png b/example/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/example/web/icons/Icon-512.png differ diff --git a/example/web/icons/Icon-maskable-192.png b/example/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/example/web/icons/Icon-maskable-192.png differ diff --git a/example/web/icons/Icon-maskable-512.png b/example/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/example/web/icons/Icon-maskable-512.png differ diff --git a/example/web/index.html b/example/web/index.html new file mode 100644 index 0000000..b84b600 --- /dev/null +++ b/example/web/index.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + example + + + + + + + + + + diff --git a/example/web/manifest.json b/example/web/manifest.json new file mode 100644 index 0000000..d74fa59 --- /dev/null +++ b/example/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "example", + "short_name": "example", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..ec4098a --- /dev/null +++ b/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..1711b9b --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -0,0 +1,102 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..3f71e17 --- /dev/null +++ b/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..2041a04 --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..8b485fd --- /dev/null +++ b/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "meilisearch" "\0" + VALUE "FileDescription", "example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 meilisearch. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..490813d --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..28c2383 --- /dev/null +++ b/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..9632f06 --- /dev/null +++ b/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..ddc7f3e --- /dev/null +++ b/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/windows/runner/resources/app_icon.ico differ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..157e871 --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..fc55c57 --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length <= 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3f0e05c --- /dev/null +++ b/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..b5ba2a0 --- /dev/null +++ b/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..49b847f --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/ios/Flutter/Generated.xcconfig b/ios/Flutter/Generated.xcconfig deleted file mode 100644 index 6ba6cbb..0000000 --- a/ios/Flutter/Generated.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -// This is a generated file; do not edit or check into version control. -FLUTTER_ROOT=C:\tools\flutter -FLUTTER_APPLICATION_PATH=E:\Bdaya_Projects\Packages\meilisearch\meilisearch_ui -COCOAPODS_PARALLEL_CODE_SIGN=true -FLUTTER_TARGET=lib\main.dart -FLUTTER_BUILD_DIR=build -FLUTTER_BUILD_NAME=0.0.1 -FLUTTER_BUILD_NUMBER=0.0.1 -EXCLUDED_ARCHS[sdk=iphonesimulator*]=i386 -EXCLUDED_ARCHS[sdk=iphoneos*]=armv7 -DART_OBFUSCATION=false -TRACK_WIDGET_CREATION=true -TREE_SHAKE_ICONS=false -PACKAGE_CONFIG=.dart_tool/package_config.json diff --git a/ios/Flutter/flutter_export_environment.sh b/ios/Flutter/flutter_export_environment.sh deleted file mode 100644 index c1b2661..0000000 --- a/ios/Flutter/flutter_export_environment.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh -# This is a generated file; do not edit or check into version control. -export "FLUTTER_ROOT=C:\tools\flutter" -export "FLUTTER_APPLICATION_PATH=E:\Bdaya_Projects\Packages\meilisearch\meilisearch_ui" -export "COCOAPODS_PARALLEL_CODE_SIGN=true" -export "FLUTTER_TARGET=lib\main.dart" -export "FLUTTER_BUILD_DIR=build" -export "FLUTTER_BUILD_NAME=0.0.1" -export "FLUTTER_BUILD_NUMBER=0.0.1" -export "DART_OBFUSCATION=false" -export "TRACK_WIDGET_CREATION=true" -export "TREE_SHAKE_ICONS=false" -export "PACKAGE_CONFIG=.dart_tool/package_config.json" diff --git a/lib/meilisearch_ui.dart b/lib/meilisearch_ui.dart index ae8e306..26831f4 100644 --- a/lib/meilisearch_ui.dart +++ b/lib/meilisearch_ui.dart @@ -1,7 +1,7 @@ +///UI Components for using Meilisearch library meilisearch_ui; -/// A Calculator. -class Calculator { - /// Returns [value] plus 1. - int addOne(int value) => value + 1; -} +export 'src/utils/_export.dart'; +export 'src/models/_exports.dart'; +export 'src/widgets/_exports.dart'; +export 'src/types.dart'; diff --git a/lib/src/models/_exports.dart b/lib/src/models/_exports.dart new file mode 100644 index 0000000..a90c346 --- /dev/null +++ b/lib/src/models/_exports.dart @@ -0,0 +1 @@ +export 'config.dart'; diff --git a/lib/src/models/config.dart b/lib/src/models/config.dart new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lib/src/models/config.dart @@ -0,0 +1 @@ + diff --git a/lib/src/types.dart b/lib/src/types.dart new file mode 100644 index 0000000..e025d90 --- /dev/null +++ b/lib/src/types.dart @@ -0,0 +1,8 @@ +import 'package:flutter/widgets.dart'; +import 'package:meilisearch/meilisearch.dart'; + +typedef MeilisearchSearchableWidgetBuilder = Widget Function( + BuildContext context, + SearchResult result, + Widget? child, +); diff --git a/lib/src/utils/_export.dart b/lib/src/utils/_export.dart new file mode 100644 index 0000000..b7f28b4 --- /dev/null +++ b/lib/src/utils/_export.dart @@ -0,0 +1 @@ +export 'higlighted_text.dart'; diff --git a/lib/src/utils/aggregate_multi_query_results.dart b/lib/src/utils/aggregate_multi_query_results.dart new file mode 100644 index 0000000..7e96263 --- /dev/null +++ b/lib/src/utils/aggregate_multi_query_results.dart @@ -0,0 +1,9 @@ +import 'package:collection/collection.dart'; +import 'package:meilisearch/meilisearch.dart'; + +List> + bestEffortAggregateSearchResults( + List> raw, +) { + return raw.sortedBy((element) => element.rankingScore ?? 0).toList(); +} diff --git a/lib/src/utils/higlighted_text.dart b/lib/src/utils/higlighted_text.dart new file mode 100644 index 0000000..69857ce --- /dev/null +++ b/lib/src/utils/higlighted_text.dart @@ -0,0 +1,70 @@ +import 'package:flutter/widgets.dart'; + +/// Takes an input string that can have highlighting and returns its parts. +/// each part has an isHighlighted text +Iterable<({String text, bool isHighlighted})> parseHighligtableString({ + required String text, + String preTag = "", + String postTag = "", +}) sync* { + assert(preTag != postTag, + "Pre ($preTag) and post ($postTag) tags can't be the same string"); + if (text.isEmpty) { + yield (text: text, isHighlighted: false); + return; + } + final preIndex = text.indexOf(preTag); + final postIndex = text.indexOf(postTag); + if (preIndex < 0 || postIndex < 0) { + //if the text doesn't contain pre/post tags, there is no need for highlighting + yield (text: text, isHighlighted: false); + } else { + //before the pre tag should be normal text + final beforePre = preIndex == 0 ? null : text.substring(0, preIndex); + //after the post tag might be normal or highlighted + final afterPost = text.substring(postIndex + postTag.length); + //between the Pre and Post tags is the highlighted text + final between = text.substring(preIndex + preTag.length, postIndex); + if (beforePre != null && beforePre.isNotEmpty) { + yield (text: beforePre, isHighlighted: false); + } + yield (text: between, isHighlighted: true); + if (afterPost.isNotEmpty) { + yield* parseHighligtableString( + text: afterPost, + postTag: postTag, + preTag: preTag, + ); + } + } +} + +// a [highlightedStyle] must be provided +TextSpan textSpanFromHighligtableString( + String? text, { + String preTag = "", + String postTag = "", + TextStyle? highlightedStyle = const TextStyle(fontStyle: FontStyle.italic), + TextSpan? whenNullOrEmpty, + TextStyle? normalStyle, +}) { + if (text == null || text.isEmpty) { + return whenNullOrEmpty ?? const TextSpan(); + } + final parts = parseHighligtableString( + text: text, + preTag: preTag, + postTag: postTag, + ).toList(growable: false); + + return TextSpan( + children: parts + .map( + (e) => TextSpan( + text: e.text, + style: e.isHighlighted ? highlightedStyle : normalStyle, + ), + ) + .toList(), + ); +} diff --git a/lib/src/widgets/_exports.dart b/lib/src/widgets/_exports.dart new file mode 100644 index 0000000..78be396 --- /dev/null +++ b/lib/src/widgets/_exports.dart @@ -0,0 +1,5 @@ +// export 'query_builders/page_based.dart'; +export 'query_builders/offset_based/models.dart'; +export 'query_builders/offset_based/widget.dart'; +// export 'query_builders/offset_models.dart'; +export 'search_bar.dart'; diff --git a/lib/src/widgets/query_builders/_shared.dart b/lib/src/widgets/query_builders/_shared.dart new file mode 100644 index 0000000..2d87ed0 --- /dev/null +++ b/lib/src/widgets/query_builders/_shared.dart @@ -0,0 +1,33 @@ +import 'package:meilisearch/meilisearch.dart'; + +abstract class MeiliQueryContainerBase>> { + ///The latest query that was executed, or is getting executed now. + final IndexSearchQuery query; + + ///All the results at different points + final List resultHistory; + + /// true if the query has been executed before + late final bool executedAtLeastOnce = resultHistory.isNotEmpty; + + MeiliQueryContainerBase({ + required this.query, + required this.resultHistory, + }); +} + +abstract class MeiliBuilderStateBase< + T extends Object, + TSearchResult extends Searcheable>, + TContainer extends MeiliQueryContainerBase> { + final List rawResults; + final bool isLoading; + final MeiliSearchClient client; + + MeiliBuilderStateBase({ + required this.isLoading, + required this.rawResults, + required this.client, + }); +} diff --git a/lib/src/widgets/query_builders/offset_based/models.dart b/lib/src/widgets/query_builders/offset_based/models.dart new file mode 100644 index 0000000..ccb8750 --- /dev/null +++ b/lib/src/widgets/query_builders/offset_based/models.dart @@ -0,0 +1,146 @@ +import 'package:collection/collection.dart'; +import 'package:meilisearch/meilisearch.dart'; +import 'package:meilisearch_ui/src/utils/aggregate_multi_query_results.dart'; + +import '../_shared.dart'; + +class MeiliOffsetBasedQueryContainer + extends MeiliQueryContainerBase>> { + /// The latest offset that was fetched + int get latestOffset => query.offset ?? 0; + int? get estimatedTotalHits => resultHistory.lastOrNull?.estimatedTotalHits; + int get limit => query.limit ?? 20; + + ///All the results sorted by offset + late final List> accumulatedResults = + resultHistory.map((e) => e.hits).flattened.toList(); + + /// true if fetching more items will actually be useful and not return an + /// empty collection + + bool get canHaveMore => + resultHistory.isEmpty || + (resultHistory.last.hits.length >= (resultHistory.last.limit ?? 20)); + + MeiliOffsetBasedQueryContainer({ + required super.query, + required super.resultHistory, + }); + + MeiliOffsetBasedQueryContainer withNewOffsets() { + return MeiliOffsetBasedQueryContainer( + query: query.copyWith(offset: latestOffset + limit), + resultHistory: resultHistory, + ); + } + + MeiliOffsetBasedQueryContainer withNewResult( + SearchResult> newRes, + ) { + return MeiliOffsetBasedQueryContainer( + query: query, + resultHistory: [...resultHistory, newRes], + ); + } +} + +class MeiliOffsetBasedDocumentsState + extends MeiliBuilderStateBase>, + MeiliOffsetBasedQueryContainer> { + MeiliOffsetBasedDocumentsState._({ + required super.isLoading, + required super.rawResults, + required super.client, + }); + + static List> + meiliRoundRobinResults( + List>>> + rawResults, + ) { + final result = >[]; + final maxHistoryCount = rawResults.isEmpty + ? 0 + : rawResults.map((e) => e.resultHistory.length).max; + for (var i = 0; i < maxHistoryCount; i++) { + for (var perQueryResult in rawResults) { + final entry = i < perQueryResult.resultHistory.length + ? perQueryResult.resultHistory[i] + : null; + if (entry == null) { + continue; + } + result.addAll(entry.hits); + } + } + return result; + } + + late final List> aggregatedResult = + bestEffortAggregateSearchResults(meiliRoundRobinResults(rawResults)); + + /// can any of the queries get executed + late final bool canHaveMore = + rawResults.any((element) => element.canHaveMore); + + /// How many items fetched until now + late final int itemCount = aggregatedResult.length; + + factory MeiliOffsetBasedDocumentsState.initial({ + required MeiliSearchClient client, + required MultiSearchQuery multiQuery, + bool isLoading = true, + }) { + final zeroQuery = + multiQuery.queries.map((e) => e.copyWith(offset: 0)).toList(); + return MeiliOffsetBasedDocumentsState._( + isLoading: isLoading, + rawResults: zeroQuery + .map( + (e) => MeiliOffsetBasedQueryContainer( + query: e, + resultHistory: [], + ), + ) + .toList(), + client: client, + ); + } + + MeiliOffsetBasedDocumentsState withNewOffsets() { + return copyWith( + isLoading: true, + rawResults: rawResults + .map( + (perQueryData) => perQueryData.withNewOffsets(), + ) + .toList(), + ); + } + + MeiliOffsetBasedDocumentsState withNewResults( + List>> newResults, + ) { + assert(newResults.length == rawResults.length); + + return copyWith( + isLoading: false, + rawResults: rawResults + .mapIndexed((index, e) => e.withNewResult(newResults[index])) + .toList(), + ); + } + + MeiliOffsetBasedDocumentsState copyWith({ + List>? rawResults, + bool? isLoading, + MeiliSearchClient? client, + }) { + return MeiliOffsetBasedDocumentsState._( + rawResults: rawResults ?? this.rawResults, + isLoading: isLoading ?? this.isLoading, + client: client ?? this.client, + ); + } +} diff --git a/lib/src/widgets/query_builders/offset_based/widget.dart b/lib/src/widgets/query_builders/offset_based/widget.dart new file mode 100644 index 0000000..f7516f9 --- /dev/null +++ b/lib/src/widgets/query_builders/offset_based/widget.dart @@ -0,0 +1,207 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:meilisearch/meilisearch.dart'; +import 'package:meilisearch_ui/meilisearch_ui.dart'; + +import 'models.dart'; + +class MeiliSearchOffsetBasedSearchQueryBuilder + extends StatefulWidget { + MeiliSearchOffsetBasedSearchQueryBuilder({ + super.key, + required this.query, + required this.mapper, + required this.builder, + required this.client, + this.onStateChanged, + this.fetchInitially = true, + }) : assert(query.queries.isNotEmpty, 'Input must have at least one query'), + assert( + query.queries.none((p0) => p0.page != null || p0.hitsPerPage != null), + "An offset-based query shouldn't use page parameters", + ); + + final MeiliSearchClient client; + + /// The multi search query to execute + /// Note that this query shouldn't assign offset + final MultiSearchQuery query; + + // Mapper used to convert document to the proper types + final MeilisearchDocumentMapper, T> mapper; + + /// Builds a widget that reacts to the latest documents. + /// + /// Note that it's safe to call fetchMore multiple times. + final Widget Function( + BuildContext context, + MeiliOffsetBasedDocumentsState state, + VoidCallback fetchMore, + VoidCallback refresh, + ) builder; + + //Gets called everytime the state changes. + final void Function( + MeiliOffsetBasedDocumentsState state, + VoidCallback fetchMore, + VoidCallback refresh, + )? onStateChanged; + + /// if true (the default) will request the first set of items when the widget starts loading + final bool fetchInitially; + + @override + State> createState() => + _MeiliSearchOffsetBasedSearchQueryBuilderState(); +} + +class _MeiliSearchOffsetBasedSearchQueryBuilderState + extends State> { + late MeiliOffsetBasedDocumentsState latestState; + void _notifyStateChanged() { + widget.onStateChanged?.call(latestState, _fetchMore, refresh); + } + + //This makes sure latestState is set to the initial value (0 offset) and loading + + @override + void initState() { + super.initState(); + latestState = MeiliOffsetBasedDocumentsState.initial( + client: widget.client, + multiQuery: widget.query, + isLoading: widget.fetchInitially, + ); + _notifyStateChanged(); + if (widget.fetchInitially) { + _requestDataThenSetState(); + } + } + + @override + void didUpdateWidget( + covariant MeiliSearchOffsetBasedSearchQueryBuilder oldWidget) { + super.didUpdateWidget(oldWidget); + + if (widget.client != oldWidget.client || widget.query != oldWidget.query) { + latestState = MeiliOffsetBasedDocumentsState.initial( + client: widget.client, + multiQuery: widget.query, + ); + _notifyStateChanged(); + _requestDataThenSetState(); + } + } + + //Sends the request and sets latestState with the new data + void _requestDataThenSetState() async { + final toExecute = latestState.rawResults.asMap().entries.toList(); + //maps the index in rawResults to the index in the improved query + final ogMap = Map.fromEntries( + toExecute + .where((element) => element.value.canHaveMore) + .mapIndexed((newIndex, og) => MapEntry(og.key, newIndex)), + ); + //maps the index in the improved query, to its original index in rawResults + final inverseMap = + Map.fromEntries(ogMap.entries.map((e) => MapEntry(e.value, e.key))); + + //short circuit to not send any request + assert(inverseMap.isNotEmpty); + + final q = MultiSearchQuery( + queries: toExecute + .where((element) => ogMap.containsKey(element.key)) + .map((entry) => entry.value.query) + .toList(), + ); + final data = await widget.client.multiSearch(q); + if (!mounted) { + return; + } + + final mappedData = toExecute.map((historyEntry) { + final ogIndex = historyEntry.key; + final history = historyEntry.value; + final improvedIndex = ogMap[ogIndex]; + if (improvedIndex == null) { + final latestRealResult = history.resultHistory.lastOrNull; + final fakeResult = SearchResult>( + indexUid: history.query.indexUid, + query: history.query.query, + estimatedTotalHits: latestRealResult?.estimatedTotalHits, + facetDistribution: latestRealResult?.facetDistribution, + facetStats: latestRealResult?.facetStats, + hits: [], + limit: history.limit, + offset: history.latestOffset, + src: {}, + vector: [], + processingTimeMs: 0, + ); + return fakeResult; + } else { + final actualResult = data.results[improvedIndex].asSearchResult(); + return actualResult + .mapToContainer() + .map((src) => src.map(widget.mapper)); + } + }).toList(); + + setState(() { + latestState = latestState.withNewResults(mappedData); + }); + _notifyStateChanged(); + } + + //progress the state by pageSize and then request data + void _fetchMore() { + // don't fetch more data since it's already loading + // or no more data can be fetched + if (latestState.isLoading || !latestState.canHaveMore) { + return; + } + + //set it to loading with the new offsets + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + if (!mounted) { + return; + } + setState(() { + latestState = latestState.withNewOffsets(); + }); + _notifyStateChanged(); + //request the data based on the new query + _requestDataThenSetState(); + }); + } + + void refresh() { + //if it's already loading do nothing + if (latestState.isLoading == true) { + return; + } + if (!mounted) { + return; + } + setState(() { + latestState = MeiliOffsetBasedDocumentsState.initial( + client: widget.client, + multiQuery: widget.query, + ); + }); + //reset latestState to its initial state + _notifyStateChanged(); + _requestDataThenSetState(); + } + + @override + Widget build(BuildContext context) { + return widget.builder( + context, + latestState, + _fetchMore, + refresh, + ); + } +} diff --git a/lib/src/widgets/query_builders/page_based/models.dart b/lib/src/widgets/query_builders/page_based/models.dart new file mode 100644 index 0000000..34fd165 --- /dev/null +++ b/lib/src/widgets/query_builders/page_based/models.dart @@ -0,0 +1,169 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:meilisearch/meilisearch.dart'; + +import '../_shared.dart'; + +class MeiliPageBasedQueryContainer + extends MeiliQueryContainerBase>> { + /// The latest offset that was fetched + int? get totalHits => resultHistory.lastOrNull?.totalHits; + int? get totalPages => resultHistory.lastOrNull?.totalPages; + int get latestPage => query.page ?? 1; + int get hitsPerPage => query.hitsPerPage ?? 20; + + //useful to know if a page has been fetched or not in O(1) time + late final resultMap = + Map.fromEntries(resultHistory.map((e) => MapEntry(e.page!, e))); + + MeiliPageBasedQueryContainer({ + required super.query, + required super.resultHistory, + }); + + bool isPageWithinBounds(int page) { + return page >= 1 && page <= (totalPages ?? 0); + } + + bool isIndexWithinBounds(int index) { + return index >= 0 && index < (totalHits ?? 0); + } + + int indexToPage(int index) { + return (index / hitsPerPage).floor() + 1; + } + + int firstIndexOfPage(int page) { + return (page - 1) * hitsPerPage; + } + + bool wasIndexFetched(int index) { + return wasPageFetched(indexToPage(index)); + } + + bool wasPageFetched(int index) { + return resultMap.containsKey(index); + } + + MeiliDocumentContainer? getResultAtIndex(int index) { + if (!isIndexWithinBounds(index)) { + return null; + } + final page = indexToPage(index); + final hits = resultMap[page]?.hits; + if (hits == null) { + return null; + } + final relativeIndex = index - firstIndexOfPage(page); + if (relativeIndex < 0 || relativeIndex >= hits.length) { + return null; + } + return hits[relativeIndex]; + } + + MeiliPageBasedQueryContainer withPage(int page) { + return MeiliPageBasedQueryContainer( + query: query.copyWith(page: page), + resultHistory: resultHistory, + ); + } + + MeiliPageBasedQueryContainer withNewResult( + PaginatedSearchResult> newRes, + ) { + return MeiliPageBasedQueryContainer( + query: query, + resultHistory: [...resultHistory, newRes], + ); + } +} + +class MeiliPageBasedDocumentsState + extends MeiliBuilderStateBase< + T, + PaginatedSearchResult>, + MeiliPageBasedQueryContainer> { + MeiliPageBasedDocumentsState._({ + required super.isLoading, + required super.rawResults, + required super.client, + }); + + factory MeiliPageBasedDocumentsState.initial({ + required MeiliSearchClient client, + required MultiSearchQuery multiQuery, + bool isLoading = true, + }) { + final zeroQuery = + multiQuery.queries.map((e) => e.copyWith(page: 1)).toList(); + return MeiliPageBasedDocumentsState._( + isLoading: isLoading, + rawResults: zeroQuery + .map( + (e) => MeiliPageBasedQueryContainer( + query: e, + resultHistory: [], + ), + ) + .toList(), + client: client, + ); + } + + MeiliPageBasedDocumentsState withPage(int page) { + return copyWith( + isLoading: true, + rawResults: rawResults + .map( + (perQueryData) => perQueryData.withPage(page), + ) + .toList(), + ); + } + + MeiliPageBasedDocumentsState withNewResults( + List>> newResults, + ) { + assert(newResults.length == rawResults.length); + + return copyWith( + isLoading: false, + rawResults: rawResults + .mapIndexed((index, e) => e.withNewResult(newResults[index])) + .toList(), + ); + } + + MeiliPageBasedDocumentsState copyWith({ + List>? rawResults, + bool? isLoading, + MeiliSearchClient? client, + }) { + return MeiliPageBasedDocumentsState._( + rawResults: rawResults ?? this.rawResults, + isLoading: isLoading ?? this.isLoading, + client: client ?? this.client, + ); + } +} + +class MeiliDataTableSource extends DataTableSource { + @override + DataRow? getRow(int index) { + // TODO: implement getRow + throw UnimplementedError(); + } + + @override + // TODO: implement isRowCountApproximate + bool get isRowCountApproximate => throw UnimplementedError(); + + @override + // TODO: implement rowCount + int get rowCount => throw UnimplementedError(); + + @override + // TODO: implement selectedRowCount + int get selectedRowCount => throw UnimplementedError(); +} diff --git a/lib/src/widgets/query_builders/page_based/widget.dart b/lib/src/widgets/query_builders/page_based/widget.dart new file mode 100644 index 0000000..84e6280 --- /dev/null +++ b/lib/src/widgets/query_builders/page_based/widget.dart @@ -0,0 +1,212 @@ +// import 'package:collection/collection.dart'; +// import 'package:flutter/material.dart'; +// import 'package:meilisearch/meilisearch.dart'; +// import 'package:meilisearch_ui/meilisearch_ui.dart'; + +// import 'models.dart'; + + + +// class MeilisearchOffsetBasedSearchQueryBuilder extends StatefulWidget { +// MeilisearchOffsetBasedSearchQueryBuilder({ +// super.key, +// required this.query, +// required this.mapper, +// required this.builder, +// required this.client, +// this.onStateChanged, +// this.fetchInitially = true, +// }) : assert(query.queries.isNotEmpty, 'Input must have at least one query'), +// assert( +// query.queries.none((p0) => p0.page != null || p0.hitsPerPage != null), +// "An offset-based query shouldn't use page parameters", +// ); + +// final MeiliSearchClient client; + +// /// The multi search query to execute +// /// Note that this query shouldn't assign offset +// final MultiSearchQuery query; + +// // Mapper used to convert document to the proper types +// final MeilisearchDocumentMapper, T> mapper; + +// /// Builds a widget that reacts to the latest documents. +// /// +// /// Note that it's safe to call fetchMore multiple times. +// final Widget Function( +// BuildContext context, +// MeiliPageBasedDocumentsState state, +// VoidCallback fetchMore, +// VoidCallback refresh, +// ) builder; + +// //Gets called everytime the state changes. +// final void Function( +// MeiliPageBasedDocumentsState state, +// VoidCallback fetchMore, +// VoidCallback refresh, +// )? onStateChanged; + +// /// if true (the default) will request the first set of items when the widget starts loading +// final bool fetchInitially; + +// @override +// State> createState() => +// _MeilisearchOffsetBasedSearchQueryBuilderState(); +// } + +// class _MeilisearchOffsetBasedSearchQueryBuilderState +// extends State> { +// late MeiliPageBasedDocumentsState latestState; +// void _notifyStateChanged() { +// widget.onStateChanged?.call(latestState, _fetchMore, refresh); +// } + +// //This makes sure latestState is set to the initial value (0 offset) and loading + +// @override +// void initState() { +// super.initState(); +// latestState = MeiliPageBasedDocumentsState.initial( +// client: widget.client, +// multiQuery: widget.query, +// isLoading: widget.fetchInitially, +// ); +// _notifyStateChanged(); +// if (widget.fetchInitially) { +// _requestDataThenSetState(); +// } +// } + +// @override +// void didUpdateWidget( +// covariant MeilisearchOffsetBasedSearchQueryBuilder oldWidget) { +// super.didUpdateWidget(oldWidget); + +// if (widget.client != oldWidget.client || widget.query != oldWidget.query) { +// latestState = MeiliPageBasedDocumentsState.initial( +// client: widget.client, +// multiQuery: widget.query, +// ); +// _notifyStateChanged(); +// _requestDataThenSetState(); +// } +// } + +// //Sends the request and sets latestState with the new data +// void _requestDataThenSetState() async { +// final toExecute = latestState.rawResults.asMap().entries.toList(); +// //maps the index in rawResults to the index in the improved query +// final ogMap = Map.fromEntries( +// toExecute +// .where((element) => element.value.canHaveMore) +// .mapIndexed((newIndex, og) => MapEntry(og.key, newIndex)), +// ); +// //maps the index in the improved query, to its original index in rawResults +// final inverseMap = +// Map.fromEntries(ogMap.entries.map((e) => MapEntry(e.value, e.key))); + +// //short circuit to not send any request +// assert(inverseMap.isNotEmpty); + +// final q = MultiSearchQuery( +// queries: toExecute +// .where((element) => ogMap.containsKey(element.key)) +// .map((entry) => entry.value.query) +// .toList(), +// ); +// final data = await widget.client.multiSearch(q); +// if (!mounted) { +// return; +// } + +// final mappedData = toExecute.map((historyEntry) { +// final ogIndex = historyEntry.key; +// final history = historyEntry.value; +// final improvedIndex = ogMap[ogIndex]; +// if (improvedIndex == null) { +// final latestRealResult = history.resultHistory.lastOrNull; +// final fakeResult = SearchResult>( +// indexUid: history.query.indexUid, +// query: history.query.query, +// estimatedTotalHits: latestRealResult?.estimatedTotalHits, +// facetDistribution: latestRealResult?.facetDistribution, +// facetStats: latestRealResult?.facetStats, +// hits: [], +// limit: history.hitsPerPage, +// offset: history.latestPage, +// matchesPosition: {}, +// processingTimeMs: 0, +// ); +// return fakeResult; +// } else { +// final actualResult = data.results[improvedIndex].asSearchResult(); +// return actualResult.map( +// (src) => MeiliDocumentContainer( +// src: src, +// parsed: widget.mapper(src), +// fromQuery: q.queries[improvedIndex], +// fromResult: actualResult, +// ), +// ); +// } +// }).toList(); + +// setState(() { +// latestState = latestState.withNewResults(mappedData); +// }); +// _notifyStateChanged(); +// } + +// //progress the state by pageSize and then request data +// void _fetchMore() { +// // don't fetch more data since it's already loading +// // or no more data can be fetched +// if (latestState.isLoading || !latestState.canHaveMore) { +// return; +// } + +// //set it to loading with the new offsets +// WidgetsBinding.instance.addPostFrameCallback((timeStamp) { +// if (!mounted) { +// return; +// } +// setState(() { +// latestState = latestState.withPage(); +// }); +// _notifyStateChanged(); +// //request the data based on the new query +// _requestDataThenSetState(); +// }); +// } + +// void refresh() { +// //if it's already loading do nothing +// if (latestState.isLoading == true) { +// return; +// } +// if (!mounted) { +// return; +// } +// setState(() { +// latestState = MeiliPageBasedDocumentsState.initial( +// client: widget.client, +// multiQuery: widget.query, +// ); +// }); +// //reset latestState to its initial state +// _notifyStateChanged(); +// _requestDataThenSetState(); +// } + +// @override +// Widget build(BuildContext context) { +// return widget.builder( +// context, +// latestState, +// _fetchMore, +// refresh, +// ); +// } +// } diff --git a/lib/src/widgets/search_bar.dart b/lib/src/widgets/search_bar.dart new file mode 100644 index 0000000..066cbc5 --- /dev/null +++ b/lib/src/widgets/search_bar.dart @@ -0,0 +1,286 @@ +import 'dart:async'; + +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:meilisearch/meilisearch.dart'; +import 'package:meilisearch_ui/meilisearch_ui.dart'; +import 'package:rxdart/rxdart.dart'; + +class DefaultMeiliSearchItemWidget extends StatelessWidget { + const DefaultMeiliSearchItemWidget({ + super.key, + required this.item, + required this.displayAttribute, + this.itemToString, + this.preTag, + this.postTag, + this.highlightedStyle, + this.onTap, + }); + final MeiliDocumentContainer item; + final VoidCallback? onTap; + final String Function(T item)? itemToString; + final String? displayAttribute; + final TextStyle? highlightedStyle; + + final String? preTag; + final String? postTag; + @override + Widget build(BuildContext context) { + final postTag = this.postTag; + final preTag = this.preTag; + final defaultStyle = DefaultTextStyle.of(context).style; + //try to get formatted text, then fallback to displayAttribute + final String itemString = displayAttribute == null + ? itemToString?.call(item.parsed) ?? item.parsed.toString() + : item.formatted?[displayAttribute] ?? item.src[displayAttribute]; + return ListTile( + onTap: onTap, + title: postTag == null || preTag == null + ? Text(itemString) + : Text.rich(textSpanFromHighligtableString( + itemString, + preTag: preTag, + postTag: postTag, + highlightedStyle: highlightedStyle ?? + defaultStyle.copyWith( + fontWeight: FontWeight.w700, + fontStyle: FontStyle.italic, + ), + normalStyle: defaultStyle, + )), + ); + } +} + +// see examples here +// https://github.com/flutter/flutter/tree/master/examples/api/lib/material/search_anchor +class MeiliSearchBar extends StatefulWidget { + MeiliSearchBar({ + super.key, + required this.mapper, + required this.client, + this.itemToString, + required IndexSearchQuery Function(String textFilter) getQuery, + this.barHintText, + this.searchController, + this.debounce = const Duration(milliseconds: 500), + this.totalDocumentLimit, + this.itemBuilder, + this.displayAttribute, + this.preloadCount, + }) : getQuery = ((textFilter) => MultiSearchQuery( + queries: [ + getQuery(textFilter), + ], + )); + + const MeiliSearchBar.multiQuery({ + super.key, + required this.client, + required this.mapper, + required this.getQuery, + this.itemToString, + this.barHintText, + this.searchController, + this.debounce = const Duration(milliseconds: 500), + this.totalDocumentLimit, + this.itemBuilder, + this.displayAttribute, + this.preloadCount, + }); + + final MeiliSearchClient client; + + final MultiSearchQuery Function(String textFilter) getQuery; + + final Widget Function( + BuildContext context, + MeiliDocumentContainer item, + )? itemBuilder; + + final int? totalDocumentLimit; + + /// how many items should be remaining to start fetching more data + final int? preloadCount; + final String? barHintText; + final SearchController? searchController; + final MeilisearchDocumentMapper, T> mapper; + final String Function(T item)? itemToString; + final String? displayAttribute; + final Duration? debounce; + @override + State> createState() => _MeiliSearchBarState(); +} + +class _MeiliSearchBarState extends State> { + final textSubject = BehaviorSubject.seeded(''); + final isSearchControllerOpen = BehaviorSubject.seeded(false); + final queryStream = BehaviorSubject.seeded(null); + //caches results + StreamSubscription? _searchResultSub; + StreamSubscription? _subscription; + + SearchController? _internalSearchController; + SearchController get _searchController => + widget.searchController ?? _internalSearchController!; + + // Make sure textSubject only fires for non-duplicate events + void _onSearchControllerChanged() { + isSearchControllerOpen.add(_searchController.isOpen); + if (_searchController.text == textSubject.valueOrNull) { + return; + } + textSubject.add(_searchController.text); + } + + void _onUniqueTextFilterChanged(String textFilter) { + //Update the query each time a unique text filter appears + queryStream.add(widget.getQuery(textFilter)); + } + + Future getSuggestions(MultiSearchQuery query) async { + //this method reacts to text changes and executes the query + } + + Stream getUniqueTextStreamWithDebounce(Duration? debounce) { + Stream stream = textSubject.stream; + if (debounce != null) { + stream = stream.debounceTime(debounce); + } + return stream; + } + + @override + void initState() { + super.initState(); + if (widget.searchController == null) { + _internalSearchController = SearchController(); + } + _searchController.addListener(_onSearchControllerChanged); + _subscription = getUniqueTextStreamWithDebounce(widget.debounce) + .listen(_onUniqueTextFilterChanged); + + //only query results when there is a query and the search panel is open + _searchResultSub = Rx.combineLatest2( + isSearchControllerOpen.stream, + queryStream.stream, + (a, b) => (isOpen: a, query: b), + ).where((event) => event.query != null && event.isOpen).listen((event) { + // + }); + } + + @override + void didUpdateWidget(covariant MeiliSearchBar oldWidget) { + super.didUpdateWidget(oldWidget); + final newDebounce = widget.debounce; + if (newDebounce != oldWidget.debounce) { + _subscription?.cancel(); + _subscription = getUniqueTextStreamWithDebounce(newDebounce) + .listen(_onUniqueTextFilterChanged); + } + } + + @override + void dispose() { + super.dispose(); + _searchController.removeListener(_onSearchControllerChanged); + _subscription?.cancel().then((_) => textSubject.close()); + _searchResultSub?.cancel(); + _subscription = null; + _searchResultSub = null; + _internalSearchController = null; + } + + @override + Widget build(BuildContext context) { + return StreamBuilder( + stream: queryStream.whereNotNull(), + builder: (context, snapshot) { + final query = snapshot.data; + if (query == null) { + return const SizedBox.shrink(); + } + return MeiliSearchOffsetBasedSearchQueryBuilder( + query: query, + client: widget.client, + mapper: widget.mapper, + builder: (context, state, fetchMore, refresh) { + final items = state.aggregatedResult; + debugPrint( + 'Items from builder: ${items.length}, ${items.map((e) => e.parsed).join(',')}'); + return SearchAnchor( + key: UniqueKey(), + searchController: _searchController, + builder: (context, controller) { + return SearchBar( + controller: controller, + onTap: () { + controller.openView(); + }, + onChanged: (_) { + controller.openView(); + }, + padding: const MaterialStatePropertyAll( + EdgeInsets.symmetric(horizontal: 16.0)), + leading: const Icon(Icons.search), + trailing: [ + IconButton( + onPressed: refresh, + icon: const Icon(Icons.refresh), + ), + ], + ); + }, + viewBuilder: (suggestions) { + final widgetList = suggestions.toList(); + final preloadCount = widget.preloadCount ?? 5; + + return ListView.builder( + itemCount: widgetList.length, + itemBuilder: (context, index) { + //reached end of the list + if (index + preloadCount >= widgetList.length) { + //it's safe to call this here, even when there are multiple builds + fetchMore(); + } + return widgetList[index]; + }, + ); + }, + suggestionsBuilder: (context, controller) { + debugPrint("suggestionsBuilder called! ${controller.text}"); + return items.map( + (e) => + widget.itemBuilder?.call(context, e) ?? + DefaultMeiliSearchItemWidget( + key: ValueKey(e), + item: e, + displayAttribute: widget.displayAttribute, + itemToString: widget.itemToString, + postTag: query.queries + .firstWhereOrNull( + (element) => element.highlightPostTag != null, + ) + ?.highlightPostTag, + preTag: query.queries + .firstWhereOrNull( + (element) => element.highlightPreTag != null, + ) + ?.highlightPreTag, + onTap: () { + final str = widget.itemToString?.call(e.parsed) ?? + e.src[widget.displayAttribute] ?? + e.parsed.toString(); + controller.closeView(str); + }, + ), + ); + }, + ); + }, + ); + }); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 24b11eb..094b833 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,55 +1,23 @@ name: meilisearch_ui -description: A new Flutter package project. +description: The official meilisearch ui kit version: 0.0.1 homepage: https://www.meilisearch.com repository: https://github.com/meilisearch/meilisearch-flutter environment: - sdk: '>=2.19.6 <3.0.0' - flutter: ">=1.17.0" + sdk: '>=3.0.0 <4.0.0' + flutter: ^3.10.0 dependencies: + collection: ^1.17.1 flutter: sdk: flutter - + meilisearch: ^0.16.0 + #TODO: remove rxdart dependency + rxdart: ^0.27.7 dev_dependencies: flutter_test: sdk: flutter - flutter_lints: ^2.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages + flutter_lints: ^3.0.2 + dio: ^5.4.3+1 +flutter: \ No newline at end of file diff --git a/test/meilisearch_ui_test.dart b/test/meilisearch_ui_test.dart index 6b6711f..b531894 100644 --- a/test/meilisearch_ui_test.dart +++ b/test/meilisearch_ui_test.dart @@ -1,12 +1,5 @@ -import 'package:flutter_test/flutter_test.dart'; +// import 'package:flutter_test/flutter_test.dart'; -import 'package:meilisearch_ui/meilisearch_ui.dart'; +// import 'package:meilisearch_ui/meilisearch_ui.dart'; -void main() { - test('adds one to input values', () { - final calculator = Calculator(); - expect(calculator.addOne(2), 3); - expect(calculator.addOne(-7), -6); - expect(calculator.addOne(0), 1); - }); -} +// void main() {} diff --git a/test/query_builders_offset_based_test.dart b/test/query_builders_offset_based_test.dart new file mode 100644 index 0000000..f4677d0 --- /dev/null +++ b/test/query_builders_offset_based_test.dart @@ -0,0 +1,239 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meilisearch/meilisearch.dart'; +import 'package:meilisearch_ui/meilisearch_ui.dart'; +import 'package:rxdart/rxdart.dart'; + +import 'utils/books.dart'; +import 'utils/client.dart'; + +void main() { + group('Offset based', () { + setUpClient(); + late Map indexes; + late MultiSearchQuery multiQuery; + setUp(() async => indexes = await createBooksIndexes()); + setUp(() => multiQuery = MultiSearchQuery( + queries: indexes.entries + .map( + (value) => IndexSearchQuery( + indexUid: value.value.uid, + query: '', + limit: 5, + ), + ) + .toList(), + )); + test('Just query', () async { + final res = await client.multiSearch(multiQuery); + expect(res.results.length, indexes.length); + }); + testWidgets("Initial state", (tester) async { + await tester.runAsync(() async { + VoidCallback? _fetchMore; + VoidCallback? _refresh; + final listViewKey = GlobalKey(); + final statesHistory = + ReplaySubject>(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MeiliSearchOffsetBasedSearchQueryBuilder( + onStateChanged: (state, fetchMore, refresh) { + _fetchMore = fetchMore; + _refresh = refresh; + statesHistory.add(state); + }, + query: MultiSearchQuery( + queries: indexes.entries + .map( + (value) => IndexSearchQuery( + indexUid: value.value.uid, + query: '', + limit: 5, + ), + ) + .toList(), + ), + mapper: BookDto.fromMap, + builder: listViewqueryBuilder(listViewKey), + client: client, + ), + ), + ), + ); + //Displays the widget and runs all animations. + await tester.pumpAndSettle(); + //initial state test + var listViewWidget = tester.widget(find.byKey(listViewKey)); + expect(find.byType(ListTile), findsNothing); + expect(listViewWidget.childrenDelegate.estimatedChildCount, 0); + expect(_fetchMore, isNotNull); + expect(_refresh, isNotNull); + + final initialState = await statesHistory.elementAt(0); + expect(initialState.isLoading, true); + expect(initialState.itemCount, 0); + expect(initialState.canHaveMore, true); + expect(initialState.rawResults.length, indexes.length); + expect( + initialState.rawResults + .every((element) => element.accumulatedResults.isEmpty), + true, + ); + expect( + initialState.rawResults + .every((element) => element.resultHistory.isEmpty), + true, + ); + + //After loading + final afterLoadingState = await statesHistory.elementAt(1); + expect(afterLoadingState.isLoading, false); + expect(afterLoadingState.canHaveMore, true); + expect(afterLoadingState.itemCount, 5 * indexes.length); + expect(afterLoadingState.rawResults.length, indexes.length); + expect( + afterLoadingState.rawResults + .every((element) => element.accumulatedResults.length == 5), + true, + ); + expect( + afterLoadingState.rawResults + .every((element) => element.resultHistory.length == 1), + true, + ); + //refresh UI + await tester.pumpAndSettle(); + listViewWidget = tester.widget(find.byKey(listViewKey)); + expect( + listViewWidget.childrenDelegate.estimatedChildCount, + 5 * indexes.length, + ); + //The visible ListTile vary based on scroll position + final allListTiles = tester.widgetList(find.byType(ListTile)); + expect(allListTiles.length, isPositive); + }); + }); + testWidgets("Fetch More", (tester) async { + await tester.runAsync(() async { + late VoidCallback _fetchMore; + final listViewKey = GlobalKey(); + + final states = + ReplaySubject>(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MeiliSearchOffsetBasedSearchQueryBuilder( + onStateChanged: (state, fetchMore, refresh) { + _fetchMore = fetchMore; + if (states.isClosed) { + throw Exception('states are already closed'); + } + states.add(state); + + if (!state.canHaveMore) { + states.close(); + } + }, + query: MultiSearchQuery( + queries: indexes.entries + .map( + (value) => IndexSearchQuery( + indexUid: value.value.uid, + query: '', + limit: 6, + ), + ) + .toList(), + ), + mapper: BookDto.fromMap, + builder: listViewqueryBuilder(listViewKey), + client: client, + ), + ), + ), + ); + //Displays the widget and runs all animations. + await tester.pumpAndSettle(); + + //wait for the initial loading to complete + await states.elementAt(1); + //then fetch more + _fetchMore(); + //schedule a new frame so that WidgetsBinding.instance.addPostFrameCallback gets called + await tester.pump(); + + var latestState = await states.elementAt(2); + expect(latestState.isLoading, true); + expect(latestState.canHaveMore, true); + expect(latestState.itemCount, 6 * indexes.length); + expect(latestState.rawResults.length, indexes.length); + expect( + latestState.rawResults + .every((element) => element.accumulatedResults.length == 6), + true, + ); + expect( + latestState.rawResults + .every((element) => element.resultHistory.length == 1), + true, + ); + + latestState = await states.elementAt(3); + expect(latestState.isLoading, false); + expect(latestState.canHaveMore, true); + expect(latestState.itemCount, (2 * 6 * indexes.length) - 3); + //one of the indexes can't have any more items + expect(latestState.rawResults.any((element) => !element.canHaveMore), + true); + expect(latestState.rawResults.length, indexes.length); + expect( + latestState.rawResults + .any((element) => element.accumulatedResults.length == 2 * 6), + true, + ); + expect( + latestState.rawResults + .every((element) => element.resultHistory.length == 2), + true, + ); + //then fetch more (last fetch that contains data) + _fetchMore(); + //schedule a new frame so that WidgetsBinding.instance.addPostFrameCallback gets called + await tester.pump(); + latestState = await states.elementAt(5); + expect(latestState.canHaveMore, false); + + + //then fetch more (no data should be fetched, stream is closed.) + _fetchMore(); + //schedule a new frame so that WidgetsBinding.instance.addPostFrameCallback gets called + await tester.pump(); + await states.done; + }); + }, timeout: const Timeout(Duration(seconds: 10))); + }); +} + +Widget Function( + BuildContext context, + MeiliOffsetBasedDocumentsState state, + VoidCallback fetchMore, + VoidCallback refresh, +) listViewqueryBuilder(GlobalKey listViewKey) { + return (context, state, fetchMore, refresh) => ListView.builder( + key: listViewKey, + itemCount: state.itemCount, + itemBuilder: (context, index) { + final item = state.aggregatedResult[index]; + return ListTile( + title: Text('[$index] ${item.parsed.title}'), + subtitle: Text('id: ${item.parsed.bookId}'), + ); + }, + ); +} diff --git a/test/utils/books.dart b/test/utils/books.dart new file mode 100644 index 0000000..12bd18c --- /dev/null +++ b/test/utils/books.dart @@ -0,0 +1,93 @@ +import 'package:collection/collection.dart'; +import 'package:meilisearch/meilisearch.dart'; + +import 'client.dart'; +import 'wait_for.dart'; + +const kbookId = 'book_id'; +const ktitle = 'title'; +const ktag = 'tag'; +const kid = 'id'; + +const _localesBookMap = { + //arabic + 'ar': 'كتاب', + //english + 'en': 'book', + //spanish + 'es': 'libro', + //greek + // 'el': 'Βιβλίο' +}; +final tags = ['t1', 't2', 't3', 't4']; + +Future> createBooksIndexes({ + String? uid, + int baseCount = 10, +}) async { + uid ??= randomUid(); + return await Future.wait( + _localesBookMap.keys.mapIndexed( + (index, locale) => createBooksIndex( + locale: locale, + uid: uid, + count: baseCount + index, + ).then((value) => MapEntry(locale, value)), + ), + ).then((value) => Map.fromEntries(value)); +} + +Future createBooksIndex({ + String? uid, + required String locale, + required int count, +}) async { + final index = client.index((uid ?? randomUid()) + locale); + final docs = List.generate( + count, + (index) => BookDto( + bookId: index, + title: '${_localesBookMap[locale]} $index', + tag: tags[index % tags.length], + ), + ); + final response = await index + .addDocuments(docs.map((e) => e.toMap()).toList()) + .waitFor(client: client); + await index.updateSearchableAttributes([ktitle]).waitFor(client: client); + await index.updateFilterableAttributes([ktag]).waitFor(client: client); + if (response.status != 'succeeded') { + throw Exception( + 'Impossible to process test suite, the documents were not added into the index.', + ); + } + return index; +} + +class BookDto { + final int bookId; + final String title; + final String? tag; + + const BookDto({ + required this.bookId, + required this.title, + required this.tag, + }); + + Map toMap() { + return { + kbookId: bookId, + ktitle: title, + ktag: tag, + }; + } + + factory BookDto.fromMap(Map map) { + return BookDto( + bookId: map[kbookId] as int, + title: map[ktitle] as String, + tag: map[ktag] as String?, + ); + } +} diff --git a/test/utils/client.dart b/test/utils/client.dart new file mode 100644 index 0000000..b6a9f70 --- /dev/null +++ b/test/utils/client.dart @@ -0,0 +1,38 @@ +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter_test/flutter_test.dart'; + +import 'test_client.dart'; + +late TestMeiliSearchClient client; +final random = Random(); + +class TestingHttpOverrides extends HttpOverrides {} + +const bool _kIsWeb = bool.fromEnvironment('dart.library.js_util'); +String get testServer { + const defaultUrl = 'http://localhost:7700'; + if (_kIsWeb) { + return defaultUrl; + } else { + return Platform.environment['MEILISEARCH_URL'] ?? defaultUrl; + } +} + +String get testApiKey { + return 'masterKey'; +} + +void setUpClient() { + setUp(() { + HttpOverrides.global = TestingHttpOverrides(); + + client = TestMeiliSearchClient(testServer, testApiKey); + }); + tearDown(() => client.disposeUsedResources()); +} + +String randomUid([String prefix = 'index']) { + return '${prefix}_${random.nextInt(9999)}'; +} diff --git a/test/utils/test_client.dart b/test/utils/test_client.dart new file mode 100644 index 0000000..9e8e48b --- /dev/null +++ b/test/utils/test_client.dart @@ -0,0 +1,144 @@ +import 'package:collection/collection.dart'; +import 'package:dio/dio.dart'; +import 'package:meilisearch/meilisearch.dart'; + +class TestMeiliSearchClient extends MeiliSearchClient { + TestMeiliSearchClient( + String serverUrl, [ + String? apiKey, + Duration? connectTimeout, + HttpClientAdapter? adapter, + List? interceptors, + ]) : super( + serverUrl, + apiKey, + connectTimeout, + adapter, + interceptors, + ); + + factory TestMeiliSearchClient.withCustomDio( + String serverUrl, { + String? apiKey, + Duration? connectTimeout, + HttpClientAdapter? adapter, + List? interceptors, + }) => + TestMeiliSearchClient( + serverUrl, + apiKey, + connectTimeout, + adapter, + interceptors, + ); + + final usedIndexes = {}; + final usedKeys = {}; + + @override + MeiliSearchIndex index(String uid, {bool deleteWhenDone = true}) { + if (deleteWhenDone) { + usedIndexes.add(uid); + } + return super.index(uid); + } + + @override + Future createIndex(String uid, {String? primaryKey}) { + usedIndexes.add(uid); + return super.createIndex(uid, primaryKey: primaryKey); + } + + @override + Future deleteIndex(String uid) { + usedIndexes.remove(uid); + return super.deleteIndex(uid); + } + + @override + Future> getRawIndex( + String uid, { + bool deleteWhenDone = true, + }) { + return super.getRawIndex(uid).then((value) { + if (deleteWhenDone) { + usedIndexes.add(uid); + } + return value; + }).onError((error, stackTrace) { + usedIndexes.remove(uid); + throw error!; + }); + } + + @override + Future swapIndexes( + List param, { + bool deleteWhenDone = true, + }) { + if (deleteWhenDone) { + usedIndexes.addAll(param.map((e) => e.indexes).flattened); + } + return super.swapIndexes(param); + } + + @override + Future createKey({ + required List indexes, + required List actions, + DateTime? expiresAt, + String? description, + String? uid, + bool deleteWhenDone = true, + }) { + return super + .createKey( + expiresAt: expiresAt, + description: description, + uid: uid, + indexes: indexes, + actions: actions, + ) + .then((value) { + if (deleteWhenDone) { + usedKeys.add(value.key); + } + return value; + }); + } + + @override + Future deleteKey(String key) { + usedKeys.remove(key); + return super.deleteKey(key); + } + + Future disposeUsedResources() async { + final indexesCopy = usedIndexes.toList(); + await Future.wait([ + _deleteUsedIndexes(), + _deleteUsedKeys(), + ]); + if (indexesCopy.isNotEmpty) { + await _deleteTasksForDeletedIndexes(indexesCopy); + } + } + + Future _deleteUsedIndexes() async { + await Future.wait( + usedIndexes.toSet().map((e) => deleteIndex(e)), + ); + } + + Future _deleteUsedKeys() async { + await Future.wait( + usedKeys.toSet().map( + (e) => deleteKey(e).onError((error, stackTrace) => false), + ), + ); + } + + Future _deleteTasksForDeletedIndexes(List indexes) async { + await deleteTasks(params: DeleteTasksQuery(indexUids: indexes)); + } +} \ No newline at end of file diff --git a/test/utils/wait_for.dart b/test/utils/wait_for.dart new file mode 100644 index 0000000..4c73283 --- /dev/null +++ b/test/utils/wait_for.dart @@ -0,0 +1,113 @@ +import 'package:meilisearch/meilisearch.dart'; +import 'package:collection/collection.dart'; + +extension TaskWaiter on Task { + Future waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 5), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + var endingTime = DateTime.now().add(timeout); + + while (DateTime.now().isBefore(endingTime)) { + final task = await client.getTask(uid!); + + if (task.status != 'enqueued' && task.status != 'processing') { + if (throwFailed && task.status != 'succeeded') { + throw MeiliSearchApiException( + "Task ($uid) failed", + code: task.error?.code, + link: task.error?.link, + type: task.error?.type, + ); + } + return task; + } + + await Future.delayed(interval); + } + + throw Exception('The task $uid timed out.'); + } +} + +extension TaskWaiterForLists on Iterable { + Future> waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 20), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + final endingTime = DateTime.now().add(timeout); + final originalUids = toList(); + final remainingUids = map((e) => e.uid).whereNotNull().toList(); + final completedTasks = {}; + final statuses = ['enqueued', 'processing']; + + while (DateTime.now().isBefore(endingTime)) { + final taskRes = + await client.getTasks(params: TasksQuery(uids: remainingUids)); + final tasks = taskRes.results; + final completed = tasks.where((e) => !statuses.contains(e.status)); + if (throwFailed) { + final failed = completed + .firstWhereOrNull((element) => element.status != 'succeeded'); + if (failed != null) { + throw MeiliSearchApiException( + "Task (${failed.uid}) failed", + code: failed.error?.code, + link: failed.error?.link, + type: failed.error?.type, + ); + } + } + + completedTasks.addEntries(completed.map((e) => MapEntry(e.uid!, e))); + remainingUids + .removeWhere((element) => completedTasks.containsKey(element)); + + if (remainingUids.isEmpty) { + return originalUids + .map((e) => completedTasks[e.uid]) + .whereNotNull() + .toList(); + } + await Future.delayed(interval); + } + + throw Exception('The tasks $originalUids timed out.'); + } +} + +extension TaskWaiterForFutures on Future { + Future waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 5), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + return await (await this).waitFor( + timeout: timeout, + interval: interval, + client: client, + throwFailed: throwFailed, + ); + } +} + +extension TaskWaiterForFutureList on Future> { + Future> waitFor({ + required MeiliSearchClient client, + Duration timeout = const Duration(seconds: 20), + Duration interval = const Duration(milliseconds: 50), + bool throwFailed = true, + }) async { + return await (await this).waitFor( + timeout: timeout, + interval: interval, + client: client, + throwFailed: throwFailed, + ); + } +} diff --git a/test/utils_test.dart b/test/utils_test.dart new file mode 100644 index 0000000..89e0953 --- /dev/null +++ b/test/utils_test.dart @@ -0,0 +1,86 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meilisearch_ui/meilisearch_ui.dart'; + +void main() { + group('parseHighligtableString', () { + test('Empty string', () { + final parsed = parseHighligtableString( + text: '', + preTag: '(', + postTag: ')', + ); + + expect(parsed, hasLength(1)); + expect(parsed.first.text, ''); + expect(parsed.first.isHighlighted, false); + }); + + test('Same pre and post tags should throw', () { + expect( + () => parseHighligtableString( + text: '', + preTag: '(', + postTag: '(', + ), + throwsA(isA()), + ); + }); + + test("Entire string should return 1 item", () { + const testStr = 'hello world'; + final parsed = parseHighligtableString( + text: '($testStr)', + preTag: '(', + postTag: ')', + ); + + expect(parsed, hasLength(1)); + expect(parsed.first.text, testStr); + expect(parsed.first.isHighlighted, true); + }); + + test("duplicate end tags shouldn't affect result", () { + const testStr = 'hello world'; + final parsed = parseHighligtableString( + text: '($testStr))', + preTag: '(', + postTag: ')', + ); + + expect(parsed, hasLength(2)); + expect(parsed.first.text, testStr); + expect(parsed.first.isHighlighted, true); + expect(parsed.last.text, ')'); + expect(parsed.last.isHighlighted, false); + }); + + test("duplicate start tags will affect result", () { + const testStr = 'hello world'; + final parsed = parseHighligtableString( + text: '(($testStr)', + preTag: '(', + postTag: ')', + ); + + expect(parsed, hasLength(1)); + expect(parsed.first.text, '($testStr'); + expect(parsed.first.isHighlighted, true); + }); + + test("multiple highlights", () { + final parsed = parseHighligtableString( + text: '(hello) (world)', + preTag: '(', + postTag: ')', + ).toList(); + + expect(parsed, hasLength(3)); + expect(parsed[0].text, 'hello'); + expect(parsed[0].isHighlighted, true); + expect(parsed[1].text, ' '); + expect(parsed[1].isHighlighted, false); + expect(parsed[2].text, 'world'); + expect(parsed[2].isHighlighted, true); + }); + }); +}