@trama-ui/react-native-system-drag 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/TramaSystemDrag.podspec +16 -0
- package/android/build.gradle +26 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/trama/systemdrag/TramaDragFiles.java +80 -0
- package/android/src/main/java/com/trama/systemdrag/TramaSystemDragPackage.java +20 -0
- package/android/src/main/java/com/trama/systemdrag/TramaSystemDragView.java +303 -0
- package/android/src/main/java/com/trama/systemdrag/TramaSystemDragViewManager.java +60 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/native.d.ts +1 -0
- package/dist/native.js +2 -0
- package/dist/specs/TramaSystemDragNativeComponent.d.ts +11 -0
- package/dist/specs/TramaSystemDragNativeComponent.js +2 -0
- package/ios/TramaDragImport.h +11 -0
- package/ios/TramaDragImport.m +186 -0
- package/ios/TramaSystemDragView.h +4 -0
- package/ios/TramaSystemDragView.mm +190 -0
- package/package.json +51 -4
- package/src/index.ts +3 -0
- package/src/native.ts +2 -0
- package/src/specs/TramaSystemDragNativeComponent.ts +9 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Trama UI contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Trama UI system drag for React Native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use the system drag companion to exchange text, HTTP(S) links and files
|
|
4
|
+
between applications. Trama treats each handoff as a copy. Apps keep ownership
|
|
5
|
+
of their source data and decide what to do with received content.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Run `bun run native:pack` in the Trama checkout. Copy both archives into the
|
|
10
|
+
app and install them together.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
bun add ./trama-ui-react-native-0.7.0.tgz ./trama-ui-react-native-system-drag-0.7.0.tgz
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Rebuild the app after installation. Expo uses a development build. React Native
|
|
17
|
+
CLI autolinks the Android library and the iOS pod. Install pods before building
|
|
18
|
+
the iOS app. The companion resolves to an undefined surface on Expo web, where
|
|
19
|
+
Trama's app-scoped drag and drop remains available.
|
|
20
|
+
|
|
21
|
+
## Pick a source and a destination
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import { useState } from 'react';
|
|
25
|
+
import { Text } from 'react-native';
|
|
26
|
+
import { Button, DragDropProvider, DragHandle, DropZone, Stack } from '@trama-ui/react-native';
|
|
27
|
+
import { SystemDragSurface } from '@trama-ui/react-native-system-drag';
|
|
28
|
+
|
|
29
|
+
const guide = 'https://example.com/guide';
|
|
30
|
+
|
|
31
|
+
export function ProjectHandoff() {
|
|
32
|
+
const [reference, setReference] = useState('');
|
|
33
|
+
return (
|
|
34
|
+
<DragDropProvider systemSurface={SystemDragSurface}>
|
|
35
|
+
<Stack>
|
|
36
|
+
<DragHandle item={{ id: 'guide' }} systemDrag={{ kind: 'url', value: guide }}>
|
|
37
|
+
Project guide
|
|
38
|
+
</DragHandle>
|
|
39
|
+
<Button onPress={() => setReference(guide)}>Use project guide</Button>
|
|
40
|
+
<DropZone id="reference" systemDrop={['text', 'url']} onSystemDrop={({ items }) => {
|
|
41
|
+
const first = items[0];
|
|
42
|
+
if (first && 'value' in first) setReference(first.value);
|
|
43
|
+
}}>
|
|
44
|
+
Drop a reference
|
|
45
|
+
</DropZone>
|
|
46
|
+
{reference && <Text>{reference}</Text>}
|
|
47
|
+
</Stack>
|
|
48
|
+
</DragDropProvider>
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
For files, use `systemDrop={['files']}` on a Drop Zone or `systemDrop` on a
|
|
54
|
+
File Upload inside the same provider. File Upload applies its existing type,
|
|
55
|
+
size, count and controlled-state rules. Supply `chooseFiles` to keep browsing
|
|
56
|
+
available alongside dragging.
|
|
57
|
+
|
|
58
|
+
Export file sources with `systemDrag={{ kind: 'files', files }}`. Supply
|
|
59
|
+
shareable `content://` URIs from the app's Android provider and app-readable
|
|
60
|
+
`file://` URLs on iOS. The companion stages received files in the receiving
|
|
61
|
+
app's private cache before releasing the platform grant. Persist files you
|
|
62
|
+
want to keep, since the OS may reclaim cached files. The transport accepts up
|
|
63
|
+
to 20 items per drop, with 64 MiB per file and 128 MiB per transfer. Native
|
|
64
|
+
hover reflects the platform's available type information. The actual contents
|
|
65
|
+
are checked at release.
|
|
66
|
+
|
|
67
|
+
`onSystemDropError` reports failed staging or transfer limits. The UI can retain
|
|
68
|
+
the user's existing selection and offer Browse again. The provider also reports
|
|
69
|
+
accepted system drops through `onSystemDrop`, with the destination ID. The
|
|
70
|
+
system event path carries source item ID and type when the OS identifies a
|
|
71
|
+
same-app drag. Use `MoveMenu` or a button for actions that should be available
|
|
72
|
+
without dragging.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
require 'json'
|
|
2
|
+
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
|
|
3
|
+
|
|
4
|
+
Pod::Spec.new do |s|
|
|
5
|
+
s.name = 'TramaSystemDrag'
|
|
6
|
+
s.version = package['version']
|
|
7
|
+
s.summary = package['description']
|
|
8
|
+
s.homepage = package['homepage']
|
|
9
|
+
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
|
10
|
+
s.author = 'Trama UI'
|
|
11
|
+
s.source = { :git => 'https://github.com/lopreiatodaniele/trama.git', :tag => "react-native-v#{s.version}" }
|
|
12
|
+
s.platforms = { :ios => min_ios_version_supported }
|
|
13
|
+
s.source_files = 'ios/**/*.{h,m,mm}'
|
|
14
|
+
s.frameworks = 'UIKit', 'UniformTypeIdentifiers'
|
|
15
|
+
install_modules_dependencies(s)
|
|
16
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
apply plugin: 'com.android.library'
|
|
2
|
+
apply plugin: 'com.facebook.react'
|
|
3
|
+
|
|
4
|
+
android {
|
|
5
|
+
namespace 'com.trama.systemdrag'
|
|
6
|
+
compileSdk(rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36)
|
|
7
|
+
|
|
8
|
+
defaultConfig {
|
|
9
|
+
minSdk(rootProject.ext.has('minSdkVersion') ? rootProject.ext.minSdkVersion : 24)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
compileOptions {
|
|
13
|
+
sourceCompatibility JavaVersion.VERSION_17
|
|
14
|
+
targetCompatibility JavaVersion.VERSION_17
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
dependencies {
|
|
19
|
+
implementation 'com.facebook.react:react-android'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
react {
|
|
23
|
+
jsRootDir = file('../src')
|
|
24
|
+
libraryName = 'TramaSystemDragSpec'
|
|
25
|
+
codegenJavaPackageName = 'com.trama.systemdrag'
|
|
26
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
package com.trama.systemdrag;
|
|
2
|
+
|
|
3
|
+
import android.content.ContentResolver;
|
|
4
|
+
import android.content.Context;
|
|
5
|
+
import android.database.Cursor;
|
|
6
|
+
import android.net.Uri;
|
|
7
|
+
import android.provider.OpenableColumns;
|
|
8
|
+
import java.io.File;
|
|
9
|
+
import java.io.FileOutputStream;
|
|
10
|
+
import java.io.IOException;
|
|
11
|
+
import java.io.InputStream;
|
|
12
|
+
import java.util.UUID;
|
|
13
|
+
import org.json.JSONException;
|
|
14
|
+
import org.json.JSONObject;
|
|
15
|
+
|
|
16
|
+
final class TramaDragFiles {
|
|
17
|
+
static final long FILE_LIMIT = 64L * 1024 * 1024;
|
|
18
|
+
static final long DROP_LIMIT = 2 * FILE_LIMIT;
|
|
19
|
+
private static final long CACHE_AGE = 24 * 60 * 60 * 1000L;
|
|
20
|
+
|
|
21
|
+
static final class Limit extends IOException {
|
|
22
|
+
Limit() {
|
|
23
|
+
super("Dropped files exceed the transfer limit.");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static File createBatch(Context context) throws IOException {
|
|
28
|
+
File root = new File(context.getCacheDir(), "trama-system-drag");
|
|
29
|
+
if (!root.isDirectory() && !root.mkdirs() && !root.isDirectory()) throw new IOException("Cache unavailable.");
|
|
30
|
+
File[] previous = root.listFiles();
|
|
31
|
+
long cutoff = System.currentTimeMillis() - CACHE_AGE;
|
|
32
|
+
if (previous != null) {
|
|
33
|
+
for (File entry : previous) if (entry.lastModified() < cutoff) discard(entry);
|
|
34
|
+
}
|
|
35
|
+
File batch = new File(root, UUID.randomUUID().toString());
|
|
36
|
+
if (!batch.mkdir()) throw new IOException("Could not stage dropped files.");
|
|
37
|
+
return batch;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static void discard(File batch) {
|
|
41
|
+
if (batch == null) return;
|
|
42
|
+
File[] files = batch.listFiles();
|
|
43
|
+
if (files != null) for (File file : files) file.delete();
|
|
44
|
+
batch.delete();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static JSONObject copy(ContentResolver resolver, Uri source, File batch, int index, long remaining)
|
|
48
|
+
throws IOException, JSONException {
|
|
49
|
+
String name = "Dropped file";
|
|
50
|
+
try (Cursor cursor = resolver.query(source, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null)) {
|
|
51
|
+
if (cursor != null && cursor.moveToFirst() && !cursor.isNull(0)) {
|
|
52
|
+
String display = cursor.getString(0);
|
|
53
|
+
if (display != null && !display.trim().isEmpty()) name = display;
|
|
54
|
+
}
|
|
55
|
+
} catch (RuntimeException ignored) {
|
|
56
|
+
// Some providers expose bytes without metadata.
|
|
57
|
+
}
|
|
58
|
+
name = name.replaceAll("[\\p{Cntrl}/\\\\]", "_").trim();
|
|
59
|
+
if (name.length() > 200) name = name.substring(0, 200);
|
|
60
|
+
if (name.isEmpty() || name.equals(".") || name.equals("..")) name = "Dropped file";
|
|
61
|
+
String suffix = name.lastIndexOf('.') >= 0 ? name.substring(name.lastIndexOf('.')) : "";
|
|
62
|
+
if (!suffix.matches("\\.[A-Za-z0-9]{1,12}")) suffix = "";
|
|
63
|
+
File destination = new File(batch, "item-" + index + suffix);
|
|
64
|
+
long size = 0;
|
|
65
|
+
try (InputStream input = resolver.openInputStream(source); FileOutputStream output = new FileOutputStream(destination)) {
|
|
66
|
+
if (input == null) throw new IOException("File stream unavailable.");
|
|
67
|
+
byte[] buffer = new byte[32 * 1024];
|
|
68
|
+
int count;
|
|
69
|
+
while ((count = input.read(buffer)) != -1) {
|
|
70
|
+
size += count;
|
|
71
|
+
if (size > FILE_LIMIT || size > remaining) throw new Limit();
|
|
72
|
+
output.write(buffer, 0, count);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return new JSONObject().put("kind", "file").put("uri", Uri.fromFile(destination).toString())
|
|
76
|
+
.put("name", name).put("type", resolver.getType(source)).put("size", size);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private TramaDragFiles() {}
|
|
80
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
package com.trama.systemdrag;
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.ReactPackage;
|
|
4
|
+
import com.facebook.react.bridge.NativeModule;
|
|
5
|
+
import com.facebook.react.bridge.ReactApplicationContext;
|
|
6
|
+
import com.facebook.react.uimanager.ViewManager;
|
|
7
|
+
import java.util.Collections;
|
|
8
|
+
import java.util.List;
|
|
9
|
+
|
|
10
|
+
public final class TramaSystemDragPackage implements ReactPackage {
|
|
11
|
+
@Override
|
|
12
|
+
public List<NativeModule> createNativeModules(ReactApplicationContext context) {
|
|
13
|
+
return Collections.emptyList();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
@Override
|
|
17
|
+
public List<ViewManager> createViewManagers(ReactApplicationContext context) {
|
|
18
|
+
return Collections.singletonList(new TramaSystemDragViewManager());
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
package com.trama.systemdrag;
|
|
2
|
+
|
|
3
|
+
import android.app.Activity;
|
|
4
|
+
import android.content.ClipData;
|
|
5
|
+
import android.content.ClipDescription;
|
|
6
|
+
import android.net.Uri;
|
|
7
|
+
import android.os.Handler;
|
|
8
|
+
import android.os.Looper;
|
|
9
|
+
import android.view.DragAndDropPermissions;
|
|
10
|
+
import android.view.DragEvent;
|
|
11
|
+
import android.view.GestureDetector;
|
|
12
|
+
import android.view.MotionEvent;
|
|
13
|
+
import com.facebook.react.bridge.Arguments;
|
|
14
|
+
import com.facebook.react.bridge.WritableMap;
|
|
15
|
+
import com.facebook.react.uimanager.ThemedReactContext;
|
|
16
|
+
import com.facebook.react.uimanager.UIManagerHelper;
|
|
17
|
+
import com.facebook.react.uimanager.events.Event;
|
|
18
|
+
import com.facebook.react.uimanager.events.EventDispatcher;
|
|
19
|
+
import com.facebook.react.views.view.ReactViewGroup;
|
|
20
|
+
import java.io.File;
|
|
21
|
+
import java.io.IOException;
|
|
22
|
+
import java.util.Arrays;
|
|
23
|
+
import java.util.Collections;
|
|
24
|
+
import java.util.HashSet;
|
|
25
|
+
import java.util.Set;
|
|
26
|
+
import java.util.concurrent.ExecutorService;
|
|
27
|
+
import java.util.concurrent.Executors;
|
|
28
|
+
import org.json.JSONArray;
|
|
29
|
+
import org.json.JSONException;
|
|
30
|
+
import org.json.JSONObject;
|
|
31
|
+
|
|
32
|
+
final class TramaSystemDragView extends ReactViewGroup {
|
|
33
|
+
private static final int ITEM_LIMIT = 20;
|
|
34
|
+
private static final int TEXT_LIMIT = 65_536;
|
|
35
|
+
private static final ExecutorService TRANSFERS = Executors.newSingleThreadExecutor();
|
|
36
|
+
private static final Handler MAIN = new Handler(Looper.getMainLooper());
|
|
37
|
+
private final ThemedReactContext reactContext;
|
|
38
|
+
private final GestureDetector gesture;
|
|
39
|
+
private ClipData source;
|
|
40
|
+
private LocalItem sourceItem;
|
|
41
|
+
private Set<String> kinds = Collections.emptySet();
|
|
42
|
+
private int generation;
|
|
43
|
+
private boolean hovered;
|
|
44
|
+
|
|
45
|
+
private static final class LocalItem {
|
|
46
|
+
final JSONObject value;
|
|
47
|
+
|
|
48
|
+
LocalItem(JSONObject value) {
|
|
49
|
+
this.value = value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
TramaSystemDragView(ThemedReactContext context) {
|
|
54
|
+
super(context);
|
|
55
|
+
reactContext = context;
|
|
56
|
+
gesture = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
|
|
57
|
+
@Override public boolean onDown(MotionEvent event) { return true; }
|
|
58
|
+
@Override public void onLongPress(MotionEvent event) { startSystemDrag(); }
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
void setDragPayload(String payload) {
|
|
63
|
+
source = null;
|
|
64
|
+
sourceItem = null;
|
|
65
|
+
if (payload == null || payload.isEmpty()) return;
|
|
66
|
+
try {
|
|
67
|
+
JSONObject model = new JSONObject(payload);
|
|
68
|
+
switch (model.optString("kind")) {
|
|
69
|
+
case "text":
|
|
70
|
+
source = ClipData.newPlainText("Text", model.getString("value"));
|
|
71
|
+
break;
|
|
72
|
+
case "url":
|
|
73
|
+
Uri link = Uri.parse(model.getString("value"));
|
|
74
|
+
if (isLink(link)) source = ClipData.newRawUri("Link", link);
|
|
75
|
+
break;
|
|
76
|
+
case "files":
|
|
77
|
+
source = fileClip(model.getJSONArray("files"));
|
|
78
|
+
break;
|
|
79
|
+
default:
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
JSONObject local = model.optJSONObject("localItem");
|
|
83
|
+
if (local != null) sourceItem = new LocalItem(local);
|
|
84
|
+
} catch (JSONException | RuntimeException ignored) {
|
|
85
|
+
source = null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private ClipData fileClip(JSONArray files) throws JSONException {
|
|
90
|
+
if (files.length() == 0 || files.length() > ITEM_LIMIT) return null;
|
|
91
|
+
Set<String> types = new HashSet<>();
|
|
92
|
+
types.add(ClipDescription.MIMETYPE_TEXT_URILIST);
|
|
93
|
+
Uri[] uris = new Uri[files.length()];
|
|
94
|
+
for (int i = 0; i < uris.length; i++) {
|
|
95
|
+
JSONObject entry = files.getJSONObject(i);
|
|
96
|
+
Uri uri = Uri.parse(entry.getString("uri"));
|
|
97
|
+
if (!ContentResolverScheme.isContent(uri)) return null;
|
|
98
|
+
uris[i] = uri;
|
|
99
|
+
String type = entry.optString("type");
|
|
100
|
+
if (type.isEmpty()) type = reactContext.getContentResolver().getType(uri);
|
|
101
|
+
if (type != null && type.contains("/")) types.add(type);
|
|
102
|
+
}
|
|
103
|
+
ClipData clip = new ClipData("Files", types.toArray(new String[0]), new ClipData.Item(uris[0]));
|
|
104
|
+
for (int i = 1; i < uris.length; i++) clip.addItem(new ClipData.Item(uris[i]));
|
|
105
|
+
return clip;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
void setDropKinds(String next) {
|
|
109
|
+
Set<String> accepted = next == null || next.isEmpty() ? Collections.emptySet() :
|
|
110
|
+
new HashSet<>(Arrays.asList(next.split(",")));
|
|
111
|
+
if (kinds.equals(accepted)) return;
|
|
112
|
+
kinds = accepted;
|
|
113
|
+
generation++;
|
|
114
|
+
hover(false);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
void resetTransport() {
|
|
118
|
+
source = null;
|
|
119
|
+
sourceItem = null;
|
|
120
|
+
kinds = Collections.emptySet();
|
|
121
|
+
hovered = false;
|
|
122
|
+
generation++;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@Override
|
|
126
|
+
public boolean dispatchTouchEvent(MotionEvent event) {
|
|
127
|
+
if (source != null) gesture.onTouchEvent(event);
|
|
128
|
+
return super.dispatchTouchEvent(event) || source != null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
@Override
|
|
132
|
+
protected void onDetachedFromWindow() {
|
|
133
|
+
generation++;
|
|
134
|
+
hovered = false;
|
|
135
|
+
super.onDetachedFromWindow();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private void startSystemDrag() {
|
|
139
|
+
if (source == null || !isAttachedToWindow()) return;
|
|
140
|
+
int flags = DRAG_FLAG_GLOBAL;
|
|
141
|
+
if (ContentResolverScheme.isContent(source.getItemAt(0).getUri())) flags |= DRAG_FLAG_GLOBAL_URI_READ;
|
|
142
|
+
try {
|
|
143
|
+
startDragAndDrop(source, new DragShadowBuilder(this), sourceItem, flags);
|
|
144
|
+
} catch (RuntimeException ignored) {
|
|
145
|
+
// The app may have lost the URI grant since configuring the handle.
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@Override
|
|
150
|
+
public boolean onDragEvent(DragEvent event) {
|
|
151
|
+
switch (event.getAction()) {
|
|
152
|
+
case DragEvent.ACTION_DRAG_STARTED:
|
|
153
|
+
return canReceive(event.getClipDescription());
|
|
154
|
+
case DragEvent.ACTION_DRAG_ENTERED:
|
|
155
|
+
hover(!kinds.isEmpty());
|
|
156
|
+
return !kinds.isEmpty();
|
|
157
|
+
case DragEvent.ACTION_DRAG_LOCATION:
|
|
158
|
+
return !kinds.isEmpty();
|
|
159
|
+
case DragEvent.ACTION_DRAG_EXITED:
|
|
160
|
+
case DragEvent.ACTION_DRAG_ENDED:
|
|
161
|
+
hover(false);
|
|
162
|
+
return true;
|
|
163
|
+
case DragEvent.ACTION_DROP:
|
|
164
|
+
hover(false);
|
|
165
|
+
return receive(event);
|
|
166
|
+
default:
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private boolean canReceive(ClipDescription description) {
|
|
172
|
+
if (description == null || kinds.isEmpty()) return false;
|
|
173
|
+
// At ACTION_DRAG_STARTED Android exposes MIME types only. Providers may advertise
|
|
174
|
+
// the same MIME type for a content URI and for a plain text item.
|
|
175
|
+
return kinds.contains("files") ||
|
|
176
|
+
(kinds.contains("text") && description.hasMimeType("text/*")) ||
|
|
177
|
+
(kinds.contains("url") && (description.hasMimeType("text/uri-list") || description.hasMimeType("text/plain")));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private boolean receive(DragEvent event) {
|
|
181
|
+
ClipData clip = event.getClipData();
|
|
182
|
+
if (clip == null || kinds.isEmpty()) return false;
|
|
183
|
+
if (clip.getItemCount() > ITEM_LIMIT) {
|
|
184
|
+
emit("error", "limit");
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
Set<String> accepted = kinds;
|
|
188
|
+
boolean file = false;
|
|
189
|
+
boolean matches = false;
|
|
190
|
+
for (int i = 0; i < clip.getItemCount(); i++) {
|
|
191
|
+
ClipData.Item item = clip.getItemAt(i);
|
|
192
|
+
file |= accepted.contains("files") && ContentResolverScheme.isContent(item.getUri());
|
|
193
|
+
matches |= matches(item, accepted);
|
|
194
|
+
}
|
|
195
|
+
if (!matches) return false;
|
|
196
|
+
final DragAndDropPermissions permission;
|
|
197
|
+
try {
|
|
198
|
+
Activity activity = reactContext.getCurrentActivity();
|
|
199
|
+
permission = file && activity != null ? activity.requestDragAndDropPermissions(event) : null;
|
|
200
|
+
} catch (RuntimeException denied) {
|
|
201
|
+
emit("error", "unavailable");
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
JSONObject local = event.getLocalState() instanceof LocalItem ? ((LocalItem) event.getLocalState()).value : null;
|
|
205
|
+
int token = generation;
|
|
206
|
+
TRANSFERS.execute(() -> stage(clip, accepted, local, permission, token));
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private void stage(ClipData clip, Set<String> accepted, JSONObject local, DragAndDropPermissions permission, int token) {
|
|
211
|
+
File batch = null;
|
|
212
|
+
try {
|
|
213
|
+
JSONArray received = new JSONArray();
|
|
214
|
+
long remaining = TramaDragFiles.DROP_LIMIT;
|
|
215
|
+
for (int i = 0; i < clip.getItemCount(); i++) {
|
|
216
|
+
ClipData.Item item = clip.getItemAt(i);
|
|
217
|
+
Uri uri = item.getUri();
|
|
218
|
+
if (accepted.contains("files") && ContentResolverScheme.isContent(uri)) {
|
|
219
|
+
if (batch == null) batch = TramaDragFiles.createBatch(reactContext);
|
|
220
|
+
JSONObject file = TramaDragFiles.copy(reactContext.getContentResolver(), uri, batch, i, remaining);
|
|
221
|
+
remaining -= file.getLong("size");
|
|
222
|
+
received.put(file);
|
|
223
|
+
} else if (accepted.contains("url") && isLink(uri)) {
|
|
224
|
+
received.put(new JSONObject().put("kind", "url").put("value", uri.toString()));
|
|
225
|
+
} else if (item.getText() != null) {
|
|
226
|
+
String text = item.getText().toString();
|
|
227
|
+
if (text.isEmpty()) continue;
|
|
228
|
+
if (accepted.contains("url") && isLink(Uri.parse(text))) {
|
|
229
|
+
if (text.length() > 8192) throw new TramaDragFiles.Limit();
|
|
230
|
+
received.put(new JSONObject().put("kind", "url").put("value", text));
|
|
231
|
+
} else if (accepted.contains("text")) {
|
|
232
|
+
if (text.length() > TEXT_LIMIT) throw new TramaDragFiles.Limit();
|
|
233
|
+
received.put(new JSONObject().put("kind", "text").put("value", text));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (received.length() == 0) throw new IOException("Empty drop.");
|
|
238
|
+
String payload = new JSONObject().put("items", received).put("localItem", local).toString();
|
|
239
|
+
File completed = batch;
|
|
240
|
+
MAIN.post(() -> {
|
|
241
|
+
if (generation == token && isAttachedToWindow()) emit("drop", payload);
|
|
242
|
+
else if (completed != null) TRANSFERS.execute(() -> TramaDragFiles.discard(completed));
|
|
243
|
+
});
|
|
244
|
+
} catch (IOException | JSONException | RuntimeException failure) {
|
|
245
|
+
TramaDragFiles.discard(batch);
|
|
246
|
+
MAIN.post(() -> {
|
|
247
|
+
if (generation == token && isAttachedToWindow()) emit("error", failure instanceof TramaDragFiles.Limit ? "limit" : "unavailable");
|
|
248
|
+
});
|
|
249
|
+
} finally {
|
|
250
|
+
if (permission != null) MAIN.post(permission::release);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private static boolean matches(ClipData.Item item, Set<String> accepted) {
|
|
255
|
+
Uri uri = item.getUri();
|
|
256
|
+
CharSequence text = item.getText();
|
|
257
|
+
return (accepted.contains("files") && ContentResolverScheme.isContent(uri)) ||
|
|
258
|
+
(accepted.contains("url") && (isLink(uri) || (text != null && isLink(Uri.parse(text.toString()))))) ||
|
|
259
|
+
(accepted.contains("text") && text != null && text.length() > 0);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private static boolean isLink(Uri uri) {
|
|
263
|
+
return uri != null && ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())) &&
|
|
264
|
+
uri.getHost() != null && !uri.getHost().isEmpty();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private void hover(boolean next) {
|
|
268
|
+
if (next == hovered) return;
|
|
269
|
+
hovered = next;
|
|
270
|
+
emit(next ? "enter" : "leave", "");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private void emit(String phase, String payload) {
|
|
274
|
+
EventDispatcher dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());
|
|
275
|
+
if (dispatcher != null) dispatcher.dispatchEvent(new SurfaceEvent(UIManagerHelper.getSurfaceId(this), getId(), phase, payload));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private static final class SurfaceEvent extends Event<SurfaceEvent> {
|
|
279
|
+
private final String phase;
|
|
280
|
+
private final String payload;
|
|
281
|
+
|
|
282
|
+
SurfaceEvent(int surface, int tag, String phase, String payload) {
|
|
283
|
+
super(surface, tag);
|
|
284
|
+
this.phase = phase;
|
|
285
|
+
this.payload = payload;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
@Override public String getEventName() { return "topTramaDragEvent"; }
|
|
289
|
+
@Override public boolean canCoalesce() { return false; }
|
|
290
|
+
@Override protected WritableMap getEventData() {
|
|
291
|
+
WritableMap data = Arguments.createMap();
|
|
292
|
+
data.putString("phase", phase);
|
|
293
|
+
data.putString("payload", payload);
|
|
294
|
+
return data;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private static final class ContentResolverScheme {
|
|
299
|
+
static boolean isContent(Uri uri) {
|
|
300
|
+
return uri != null && "content".equals(uri.getScheme()) && uri.getAuthority() != null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
package com.trama.systemdrag;
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.module.annotations.ReactModule;
|
|
4
|
+
import com.facebook.react.uimanager.ThemedReactContext;
|
|
5
|
+
import com.facebook.react.uimanager.ViewManagerDelegate;
|
|
6
|
+
import com.facebook.react.uimanager.annotations.ReactProp;
|
|
7
|
+
import com.facebook.react.viewmanagers.TramaSystemDragViewManagerDelegate;
|
|
8
|
+
import com.facebook.react.viewmanagers.TramaSystemDragViewManagerInterface;
|
|
9
|
+
import com.facebook.react.views.view.ReactViewGroup;
|
|
10
|
+
import com.facebook.react.views.view.ReactViewManager;
|
|
11
|
+
import java.util.Map;
|
|
12
|
+
|
|
13
|
+
@ReactModule(name = TramaSystemDragViewManager.NAME)
|
|
14
|
+
public final class TramaSystemDragViewManager extends ReactViewManager
|
|
15
|
+
implements TramaSystemDragViewManagerInterface<ReactViewGroup> {
|
|
16
|
+
public static final String NAME = "TramaSystemDragView";
|
|
17
|
+
private final ViewManagerDelegate<ReactViewGroup> delegate = new TramaSystemDragViewManagerDelegate<>(this);
|
|
18
|
+
|
|
19
|
+
@Override
|
|
20
|
+
public String getName() {
|
|
21
|
+
return NAME;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
@Override
|
|
25
|
+
public ViewManagerDelegate<ReactViewGroup> getDelegate() {
|
|
26
|
+
return delegate;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@Override
|
|
30
|
+
public ReactViewGroup createViewInstance(ThemedReactContext context) {
|
|
31
|
+
return new TramaSystemDragView(context);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@Override
|
|
35
|
+
@ReactProp(name = "dragPayload")
|
|
36
|
+
public void setDragPayload(ReactViewGroup view, String payload) {
|
|
37
|
+
((TramaSystemDragView) view).setDragPayload(payload);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
@Override
|
|
41
|
+
@ReactProp(name = "dropKinds")
|
|
42
|
+
public void setDropKinds(ReactViewGroup view, String kinds) {
|
|
43
|
+
((TramaSystemDragView) view).setDropKinds(kinds);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
@Override
|
|
47
|
+
public void onDropViewInstance(ReactViewGroup view) {
|
|
48
|
+
((TramaSystemDragView) view).resetTransport();
|
|
49
|
+
super.onDropViewInstance(view);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
@Override
|
|
53
|
+
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
|
|
54
|
+
Map<String, Object> events = new java.util.HashMap<>();
|
|
55
|
+
Map<String, Object> inherited = super.getExportedCustomDirectEventTypeConstants();
|
|
56
|
+
if (inherited != null) events.putAll(inherited);
|
|
57
|
+
events.put("topTramaDragEvent", Map.of("registrationName", "onTramaDragEvent"));
|
|
58
|
+
return events;
|
|
59
|
+
}
|
|
60
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SystemDragSurface = undefined;
|
package/dist/native.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default as SystemDragSurface } from './specs/TramaSystemDragNativeComponent';
|
package/dist/native.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type CodegenTypes, type HostComponent, type ViewProps } from 'react-native';
|
|
2
|
+
interface NativeProps extends ViewProps {
|
|
3
|
+
dragPayload?: string;
|
|
4
|
+
dropKinds?: string;
|
|
5
|
+
onTramaDragEvent?: CodegenTypes.DirectEventHandler<Readonly<{
|
|
6
|
+
phase: string;
|
|
7
|
+
payload: string;
|
|
8
|
+
}>>;
|
|
9
|
+
}
|
|
10
|
+
declare const _default: HostComponent<NativeProps>;
|
|
11
|
+
export default _default;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#import <UIKit/UIKit.h>
|
|
2
|
+
|
|
3
|
+
NS_ASSUME_NONNULL_BEGIN
|
|
4
|
+
|
|
5
|
+
BOOL TramaAcceptsDragItem(UIDragItem *item, NSSet<NSString *> *kinds);
|
|
6
|
+
void TramaImportDragItems(
|
|
7
|
+
NSArray<UIDragItem *> *items,
|
|
8
|
+
NSSet<NSString *> *kinds,
|
|
9
|
+
void (^completion)(NSArray<NSDictionary *> *_Nullable, NSURL *_Nullable, NSString *_Nullable));
|
|
10
|
+
|
|
11
|
+
NS_ASSUME_NONNULL_END
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#import "TramaDragImport.h"
|
|
2
|
+
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
|
3
|
+
|
|
4
|
+
static const NSUInteger TramaItemLimit = 20;
|
|
5
|
+
static const NSUInteger TramaTextLimit = 65536;
|
|
6
|
+
static const unsigned long long TramaFileLimit = 64ULL * 1024 * 1024;
|
|
7
|
+
static const unsigned long long TramaDropLimit = 2 * TramaFileLimit;
|
|
8
|
+
|
|
9
|
+
static BOOL TramaHTTPLink(NSURL *url) {
|
|
10
|
+
NSString *scheme = url.scheme.lowercaseString;
|
|
11
|
+
return ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]) && url.host.length > 0;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static NSString *TramaFileType(NSItemProvider *provider) {
|
|
15
|
+
BOOL fileURL = [provider hasItemConformingToTypeIdentifier:UTTypeFileURL.identifier];
|
|
16
|
+
for (NSString *identifier in provider.registeredTypeIdentifiers) {
|
|
17
|
+
UTType *type = [UTType typeWithIdentifier:identifier];
|
|
18
|
+
if (!type || [type conformsToType:UTTypeURL]) continue;
|
|
19
|
+
if (([type conformsToType:UTTypeData] && ![type conformsToType:UTTypeText]) ||
|
|
20
|
+
((fileURL || provider.suggestedName.pathExtension.length) && [type conformsToType:UTTypeData])) return identifier;
|
|
21
|
+
}
|
|
22
|
+
return fileURL ? UTTypeFileURL.identifier : nil;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static NSString *TramaKind(NSItemProvider *provider, NSSet<NSString *> *kinds) {
|
|
26
|
+
if ([kinds containsObject:@"files"] && TramaFileType(provider)) return @"file";
|
|
27
|
+
if ([kinds containsObject:@"url"] && [provider hasItemConformingToTypeIdentifier:UTTypeURL.identifier] &&
|
|
28
|
+
![provider hasItemConformingToTypeIdentifier:UTTypeFileURL.identifier]) return @"url";
|
|
29
|
+
if ([kinds containsObject:@"text"] && [provider canLoadObjectOfClass:NSString.class]) return @"text";
|
|
30
|
+
return nil;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
BOOL TramaAcceptsDragItem(UIDragItem *item, NSSet<NSString *> *kinds) {
|
|
34
|
+
return TramaKind(item.itemProvider, kinds) != nil;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static NSURL *TramaCacheBatch(void) {
|
|
38
|
+
NSFileManager *manager = NSFileManager.defaultManager;
|
|
39
|
+
NSURL *root = [[manager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject
|
|
40
|
+
URLByAppendingPathComponent:@"trama-system-drag" isDirectory:YES];
|
|
41
|
+
if (!root || ![manager createDirectoryAtURL:root withIntermediateDirectories:YES attributes:nil error:nil]) return nil;
|
|
42
|
+
NSArray<NSURL *> *previous = [manager contentsOfDirectoryAtURL:root
|
|
43
|
+
includingPropertiesForKeys:@[NSURLContentModificationDateKey]
|
|
44
|
+
options:0 error:nil];
|
|
45
|
+
NSDate *cutoff = [NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60];
|
|
46
|
+
for (NSURL *entry in previous) {
|
|
47
|
+
NSDate *changed = nil;
|
|
48
|
+
if ([entry getResourceValue:&changed forKey:NSURLContentModificationDateKey error:nil] &&
|
|
49
|
+
changed && [changed compare:cutoff] == NSOrderedAscending) [manager removeItemAtURL:entry error:nil];
|
|
50
|
+
}
|
|
51
|
+
NSURL *batch = [root URLByAppendingPathComponent:NSUUID.UUID.UUIDString isDirectory:YES];
|
|
52
|
+
return [manager createDirectoryAtURL:batch withIntermediateDirectories:NO attributes:nil error:nil] ? batch : nil;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
static NSString *TramaDisplayName(NSString *suggestion, NSURL *url) {
|
|
56
|
+
NSString *proposed = suggestion.length ? suggestion : url.lastPathComponent;
|
|
57
|
+
if (proposed.pathExtension.length == 0 && url.pathExtension.length) proposed = [proposed stringByAppendingPathExtension:url.pathExtension];
|
|
58
|
+
NSMutableCharacterSet *unsafe = [NSCharacterSet.controlCharacterSet mutableCopy];
|
|
59
|
+
[unsafe addCharactersInString:@"/\\"];
|
|
60
|
+
NSString *name = [[proposed componentsSeparatedByCharactersInSet:unsafe] componentsJoinedByString:@"_"];
|
|
61
|
+
name = [name stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
62
|
+
if (name.length > 200) name = [name substringToIndex:200];
|
|
63
|
+
return name.length && ![name isEqualToString:@"."] && ![name isEqualToString:@".."] ? name : @"Dropped file";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
static NSDictionary *TramaStageFile(NSURL *source, NSURL *batch, NSString *suggestion, NSString *identifier,
|
|
67
|
+
NSUInteger index, unsigned long long remaining, NSString **failure) {
|
|
68
|
+
if (!source.isFileURL || !batch) return nil;
|
|
69
|
+
NSNumber *regular = nil;
|
|
70
|
+
NSNumber *symbolic = nil;
|
|
71
|
+
if (![source getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil] || !regular.boolValue ||
|
|
72
|
+
([source getResourceValue:&symbolic forKey:NSURLIsSymbolicLinkKey error:nil] && symbolic.boolValue)) return nil;
|
|
73
|
+
NSString *name = TramaDisplayName(suggestion, source);
|
|
74
|
+
NSString *suffix = name.pathExtension;
|
|
75
|
+
if (suffix.length > 12 || [suffix rangeOfCharacterFromSet:NSCharacterSet.alphanumericCharacterSet.invertedSet].location != NSNotFound)
|
|
76
|
+
suffix = @"";
|
|
77
|
+
NSString *leaf = [NSString stringWithFormat:@"item-%lu", (unsigned long)index];
|
|
78
|
+
if (suffix.length) leaf = [leaf stringByAppendingPathExtension:suffix];
|
|
79
|
+
NSURL *output = [batch URLByAppendingPathComponent:leaf isDirectory:NO];
|
|
80
|
+
NSInputStream *input = [NSInputStream inputStreamWithURL:source];
|
|
81
|
+
NSOutputStream *destination = [NSOutputStream outputStreamWithURL:output append:NO];
|
|
82
|
+
if (!input || !destination) return nil;
|
|
83
|
+
[input open];
|
|
84
|
+
[destination open];
|
|
85
|
+
unsigned long long size = 0;
|
|
86
|
+
uint8_t bytes[32768];
|
|
87
|
+
NSInteger count;
|
|
88
|
+
BOOL valid = YES;
|
|
89
|
+
while ((count = [input read:bytes maxLength:sizeof(bytes)]) > 0) {
|
|
90
|
+
size += count;
|
|
91
|
+
if (size > TramaFileLimit || size > remaining) {
|
|
92
|
+
*failure = @"limit";
|
|
93
|
+
valid = NO;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
NSInteger written = 0;
|
|
97
|
+
while (written < count) {
|
|
98
|
+
NSInteger amount = [destination write:bytes + written maxLength:(NSUInteger)(count - written)];
|
|
99
|
+
if (amount <= 0) break;
|
|
100
|
+
written += amount;
|
|
101
|
+
}
|
|
102
|
+
if (written != count) { valid = NO; break; }
|
|
103
|
+
}
|
|
104
|
+
if (count < 0 || destination.streamError) valid = NO;
|
|
105
|
+
[input close];
|
|
106
|
+
[destination close];
|
|
107
|
+
if (!valid) return nil;
|
|
108
|
+
NSString *mime = [UTType typeWithIdentifier:identifier].preferredMIMEType;
|
|
109
|
+
if (!mime && suffix.length) mime = [UTType typeWithFilenameExtension:suffix].preferredMIMEType;
|
|
110
|
+
return @{ @"kind": @"file", @"uri": output.absoluteString, @"name": name,
|
|
111
|
+
@"type": mime ?: NSNull.null, @"size": @(size) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
typedef void (^TramaImportCompletion)(NSArray<NSDictionary *> *, NSURL *, NSString *);
|
|
115
|
+
|
|
116
|
+
static void TramaImportNext(NSArray<UIDragItem *> *items, NSUInteger index, NSSet<NSString *> *kinds,
|
|
117
|
+
NSMutableArray<NSDictionary *> *received, NSURL *batch, unsigned long long remaining,
|
|
118
|
+
TramaImportCompletion completion) {
|
|
119
|
+
if (index >= items.count) {
|
|
120
|
+
completion(received.count ? received.copy : nil, batch, received.count ? nil : @"unavailable");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
NSItemProvider *provider = items[index].itemProvider;
|
|
124
|
+
NSString *kind = TramaKind(provider, kinds);
|
|
125
|
+
if (!kind) {
|
|
126
|
+
TramaImportNext(items, index + 1, kinds, received, batch, remaining, completion);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
void (^advance)(NSDictionary *, NSString *) = ^(NSDictionary *item, NSString *error) {
|
|
130
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
131
|
+
if (!item) {
|
|
132
|
+
completion(nil, batch, error ?: @"unavailable");
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
[received addObject:item];
|
|
136
|
+
TramaImportNext(items, index + 1, kinds, received, batch,
|
|
137
|
+
remaining - [item[@"size"] unsignedLongLongValue], completion);
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if ([kind isEqualToString:@"file"]) {
|
|
142
|
+
NSString *identifier = TramaFileType(provider);
|
|
143
|
+
if (!batch || !identifier) { advance(nil, @"unavailable"); return; }
|
|
144
|
+
if ([identifier isEqualToString:UTTypeFileURL.identifier]) {
|
|
145
|
+
[provider loadItemForTypeIdentifier:identifier options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) {
|
|
146
|
+
if (error || ![item isKindOfClass:NSURL.class]) { advance(nil, @"unavailable"); return; }
|
|
147
|
+
NSURL *url = (NSURL *)item;
|
|
148
|
+
BOOL access = [url startAccessingSecurityScopedResource];
|
|
149
|
+
NSString *failure = nil;
|
|
150
|
+
NSDictionary *file = TramaStageFile(url, batch, provider.suggestedName, identifier, index, remaining, &failure);
|
|
151
|
+
if (access) [url stopAccessingSecurityScopedResource];
|
|
152
|
+
advance(file, failure);
|
|
153
|
+
}];
|
|
154
|
+
} else {
|
|
155
|
+
[provider loadFileRepresentationForTypeIdentifier:identifier completionHandler:^(NSURL *url, NSError *error) {
|
|
156
|
+
NSString *failure = nil;
|
|
157
|
+
NSDictionary *file = error ? nil : TramaStageFile(url, batch, provider.suggestedName, identifier, index, remaining, &failure);
|
|
158
|
+
advance(file, failure);
|
|
159
|
+
}];
|
|
160
|
+
}
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
BOOL link = [kind isEqualToString:@"url"];
|
|
165
|
+
[provider loadObjectOfClass:link ? NSURL.class : NSString.class completionHandler:^(id<NSItemProviderReading> item, NSError *error) {
|
|
166
|
+
if (error) { advance(nil, @"unavailable"); return; }
|
|
167
|
+
NSString *value = nil;
|
|
168
|
+
if (link && [item isKindOfClass:NSURL.class] && TramaHTTPLink((NSURL *)item)) value = ((NSURL *)item).absoluteString;
|
|
169
|
+
if (!link && [item isKindOfClass:NSString.class]) value = (NSString *)item;
|
|
170
|
+
if (!value.length) { advance(nil, @"unavailable"); return; }
|
|
171
|
+
if (value.length > (link ? 8192 : TramaTextLimit)) { advance(nil, @"limit"); return; }
|
|
172
|
+
advance(@{ @"kind": kind, @"value": value }, nil);
|
|
173
|
+
}];
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
void TramaImportDragItems(NSArray<UIDragItem *> *items, NSSet<NSString *> *kinds, TramaImportCompletion completion) {
|
|
177
|
+
if (items.count > TramaItemLimit) { completion(nil, nil, @"limit"); return; }
|
|
178
|
+
NSURL *batch = nil;
|
|
179
|
+
for (UIDragItem *item in items) {
|
|
180
|
+
if ([TramaKind(item.itemProvider, kinds) isEqualToString:@"file"]) {
|
|
181
|
+
batch = TramaCacheBatch();
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
TramaImportNext(items, 0, kinds, NSMutableArray.array, batch, TramaDropLimit, completion);
|
|
186
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
#import "TramaSystemDragView.h"
|
|
2
|
+
#import "TramaDragImport.h"
|
|
3
|
+
|
|
4
|
+
#import <react/renderer/components/TramaSystemDragSpec/ComponentDescriptors.h>
|
|
5
|
+
#import <react/renderer/components/TramaSystemDragSpec/EventEmitters.h>
|
|
6
|
+
#import <react/renderer/components/TramaSystemDragSpec/Props.h>
|
|
7
|
+
#import <react/renderer/components/TramaSystemDragSpec/RCTComponentViewHelpers.h>
|
|
8
|
+
|
|
9
|
+
using namespace facebook::react;
|
|
10
|
+
|
|
11
|
+
@interface TramaLocalDragItem : NSObject
|
|
12
|
+
@property (nonatomic, copy) NSDictionary *value;
|
|
13
|
+
@end
|
|
14
|
+
@implementation TramaLocalDragItem
|
|
15
|
+
@end
|
|
16
|
+
|
|
17
|
+
@interface TramaSystemDragView () <RCTTramaSystemDragViewViewProtocol, UIDragInteractionDelegate, UIDropInteractionDelegate>
|
|
18
|
+
@end
|
|
19
|
+
|
|
20
|
+
@implementation TramaSystemDragView {
|
|
21
|
+
UIDragInteraction *_drag;
|
|
22
|
+
UIDropInteraction *_drop;
|
|
23
|
+
NSDictionary *_source;
|
|
24
|
+
NSSet<NSString *> *_kinds;
|
|
25
|
+
NSUInteger _generation;
|
|
26
|
+
BOOL _hovered;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
+ (ComponentDescriptorProvider)componentDescriptorProvider {
|
|
30
|
+
return concreteComponentDescriptorProvider<TramaSystemDragViewComponentDescriptor>();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
- (instancetype)init {
|
|
34
|
+
if (self = [super init]) {
|
|
35
|
+
_props = std::make_shared<const TramaSystemDragViewProps>();
|
|
36
|
+
_kinds = NSSet.set;
|
|
37
|
+
_drag = [[UIDragInteraction alloc] initWithDelegate:self];
|
|
38
|
+
_drag.enabled = NO;
|
|
39
|
+
[self addInteraction:_drag];
|
|
40
|
+
_drop = [[UIDropInteraction alloc] initWithDelegate:self];
|
|
41
|
+
[self addInteraction:_drop];
|
|
42
|
+
}
|
|
43
|
+
return self;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps {
|
|
47
|
+
const auto &next = static_cast<const TramaSystemDragViewProps &>(*props);
|
|
48
|
+
const auto &previous = static_cast<const TramaSystemDragViewProps &>(*_props);
|
|
49
|
+
if (next.dragPayload != previous.dragPayload) {
|
|
50
|
+
NSData *encoded = [NSData dataWithBytes:next.dragPayload.data() length:next.dragPayload.size()];
|
|
51
|
+
id model = encoded.length ? [NSJSONSerialization JSONObjectWithData:encoded options:0 error:nullptr] : nil;
|
|
52
|
+
_source = [model isKindOfClass:NSDictionary.class] ? model : nil;
|
|
53
|
+
_drag.enabled = _source != nil;
|
|
54
|
+
}
|
|
55
|
+
if (next.dropKinds != previous.dropKinds) {
|
|
56
|
+
NSString *kinds = [[NSString alloc] initWithBytes:next.dropKinds.data() length:next.dropKinds.size() encoding:NSUTF8StringEncoding];
|
|
57
|
+
_kinds = kinds.length ? [NSSet setWithArray:[kinds componentsSeparatedByString:@","]] : NSSet.set;
|
|
58
|
+
++_generation;
|
|
59
|
+
[self setDragHovered:NO];
|
|
60
|
+
}
|
|
61
|
+
[super updateProps:props oldProps:oldProps];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
- (void)prepareForRecycle {
|
|
65
|
+
++_generation;
|
|
66
|
+
_source = nil;
|
|
67
|
+
_kinds = NSSet.set;
|
|
68
|
+
_drag.enabled = NO;
|
|
69
|
+
_hovered = NO;
|
|
70
|
+
[super prepareForRecycle];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
- (void)didMoveToWindow {
|
|
74
|
+
[super didMoveToWindow];
|
|
75
|
+
if (!self.window) {
|
|
76
|
+
++_generation;
|
|
77
|
+
_hovered = NO;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
- (NSArray<UIDragItem *> *)dragInteraction:(UIDragInteraction *)interaction itemsForBeginningSession:(id<UIDragSession>)session {
|
|
82
|
+
if (!_source) return @[];
|
|
83
|
+
NSString *kind = _source[@"kind"];
|
|
84
|
+
NSMutableArray<NSItemProvider *> *providers = NSMutableArray.array;
|
|
85
|
+
if ([kind isEqualToString:@"text"] && [_source[@"value"] isKindOfClass:NSString.class]) {
|
|
86
|
+
[providers addObject:[[NSItemProvider alloc] initWithObject:_source[@"value"]]];
|
|
87
|
+
} else if ([kind isEqualToString:@"url"] && [_source[@"value"] isKindOfClass:NSString.class]) {
|
|
88
|
+
NSURL *url = [NSURL URLWithString:_source[@"value"]];
|
|
89
|
+
NSString *scheme = url.scheme.lowercaseString;
|
|
90
|
+
if (url.host.length && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
|
|
91
|
+
[providers addObject:[[NSItemProvider alloc] initWithObject:url]];
|
|
92
|
+
} else if ([kind isEqualToString:@"files"] && [_source[@"files"] isKindOfClass:NSArray.class]) {
|
|
93
|
+
NSArray *files = _source[@"files"];
|
|
94
|
+
if (!files.count || files.count > 20) return @[];
|
|
95
|
+
for (NSDictionary *file in files) {
|
|
96
|
+
if (![file isKindOfClass:NSDictionary.class] || ![file[@"uri"] isKindOfClass:NSString.class]) return @[];
|
|
97
|
+
NSURL *url = [NSURL URLWithString:file[@"uri"]];
|
|
98
|
+
if (!url.isFileURL) return @[];
|
|
99
|
+
NSItemProvider *provider = [[NSItemProvider alloc] initWithContentsOfURL:url];
|
|
100
|
+
if (!provider) return @[];
|
|
101
|
+
provider.suggestedName = [file[@"name"] isKindOfClass:NSString.class] ? file[@"name"] : url.lastPathComponent;
|
|
102
|
+
[providers addObject:provider];
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
TramaLocalDragItem *local = nil;
|
|
106
|
+
if ([_source[@"localItem"] isKindOfClass:NSDictionary.class]) {
|
|
107
|
+
local = TramaLocalDragItem.new;
|
|
108
|
+
local.value = _source[@"localItem"];
|
|
109
|
+
}
|
|
110
|
+
NSMutableArray<UIDragItem *> *items = NSMutableArray.array;
|
|
111
|
+
for (NSItemProvider *provider in providers) {
|
|
112
|
+
UIDragItem *item = [[UIDragItem alloc] initWithItemProvider:provider];
|
|
113
|
+
item.localObject = local;
|
|
114
|
+
[items addObject:item];
|
|
115
|
+
}
|
|
116
|
+
return items;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
- (BOOL)dragInteraction:(UIDragInteraction *)interaction sessionAllowsMoveOperation:(id<UIDragSession>)session {
|
|
120
|
+
return NO;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
- (BOOL)dropInteraction:(UIDropInteraction *)interaction canHandleSession:(id<UIDropSession>)session {
|
|
124
|
+
for (UIDragItem *item in session.items) if (TramaAcceptsDragItem(item, _kinds)) return YES;
|
|
125
|
+
return NO;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidEnter:(id<UIDropSession>)session {
|
|
129
|
+
[self setDragHovered:[self dropInteraction:interaction canHandleSession:session]];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
- (UIDropProposal *)dropInteraction:(UIDropInteraction *)interaction sessionDidUpdate:(id<UIDropSession>)session {
|
|
133
|
+
BOOL allowed = [self dropInteraction:interaction canHandleSession:session];
|
|
134
|
+
[self setDragHovered:allowed];
|
|
135
|
+
return [[UIDropProposal alloc] initWithDropOperation:allowed ? UIDropOperationCopy : UIDropOperationCancel];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidExit:(id<UIDropSession>)session {
|
|
139
|
+
[self setDragHovered:NO];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidEnd:(id<UIDropSession>)session {
|
|
143
|
+
[self setDragHovered:NO];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
- (void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session {
|
|
147
|
+
[self setDragHovered:NO];
|
|
148
|
+
if (![self dropInteraction:interaction canHandleSession:session]) return;
|
|
149
|
+
NSDictionary *local = nil;
|
|
150
|
+
if (session.localDragSession) {
|
|
151
|
+
id source = session.items.firstObject.localObject;
|
|
152
|
+
if ([source isKindOfClass:TramaLocalDragItem.class]) local = ((TramaLocalDragItem *)source).value;
|
|
153
|
+
}
|
|
154
|
+
NSUInteger generation = _generation;
|
|
155
|
+
__weak TramaSystemDragView *weakView = self;
|
|
156
|
+
TramaImportDragItems(session.items, _kinds, ^(NSArray<NSDictionary *> *items, NSURL *batch, NSString *error) {
|
|
157
|
+
TramaSystemDragView *view = weakView;
|
|
158
|
+
if (!view || !view.window || view->_generation != generation || !items) {
|
|
159
|
+
if (batch) [NSFileManager.defaultManager removeItemAtURL:batch error:nullptr];
|
|
160
|
+
if (view && view.window && view->_generation == generation) [view emit:@"error" payload:error ?: @"unavailable"];
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
NSData *data = [NSJSONSerialization dataWithJSONObject:@{ @"items": items, @"localItem": local ?: NSNull.null }
|
|
164
|
+
options:0 error:nullptr];
|
|
165
|
+
NSString *payload = data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : nil;
|
|
166
|
+
if (payload) [view emit:@"drop" payload:payload];
|
|
167
|
+
else {
|
|
168
|
+
if (batch) [NSFileManager.defaultManager removeItemAtURL:batch error:nullptr];
|
|
169
|
+
[view emit:@"error" payload:@"unavailable"];
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
- (void)setDragHovered:(BOOL)hovered {
|
|
175
|
+
if (_hovered == hovered) return;
|
|
176
|
+
_hovered = hovered;
|
|
177
|
+
[self emit:hovered ? @"enter" : @"leave" payload:@""];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
- (void)emit:(NSString *)phase payload:(NSString *)payload {
|
|
181
|
+
if (!_eventEmitter) return;
|
|
182
|
+
auto emitter = std::static_pointer_cast<const TramaSystemDragViewEventEmitter>(_eventEmitter);
|
|
183
|
+
emitter->onTramaDragEvent({std::string(phase.UTF8String), std::string(payload.UTF8String)});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
@end
|
|
187
|
+
|
|
188
|
+
Class<RCTComponentViewProtocol> TramaSystemDragViewCls(void) {
|
|
189
|
+
return TramaSystemDragView.class;
|
|
190
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-ui/react-native-system-drag",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Native operating-system drag and drop for Trama UI",
|
|
5
|
+
"homepage": "https://trama.danielelopreiato.it/",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/lopreiatodaniele/trama.git",
|
|
10
|
+
"directory": "packages/react-native/system-drag"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"react-native": "./src/native.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"browser": "./dist/index.js",
|
|
20
|
+
"react-native": "./src/native.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": ["dist", "src", "android", "ios", "TramaSystemDrag.podspec", "README.md", "LICENSE"],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "bun --bun tsc -p tsconfig.build.json"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"react": "^19.2.3",
|
|
30
|
+
"react-native": ">=0.86 <0.89"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"react-native": "0.86.2"
|
|
34
|
+
},
|
|
35
|
+
"codegenConfig": {
|
|
36
|
+
"name": "TramaSystemDragSpec",
|
|
37
|
+
"type": "components",
|
|
38
|
+
"jsSrcsDir": "src/specs",
|
|
39
|
+
"android": {
|
|
40
|
+
"javaPackageName": "com.trama.systemdrag"
|
|
41
|
+
},
|
|
42
|
+
"ios": {
|
|
43
|
+
"componentProvider": {
|
|
44
|
+
"TramaSystemDragView": "TramaSystemDragView"
|
|
45
|
+
},
|
|
46
|
+
"components": {
|
|
47
|
+
"TramaSystemDragView": {
|
|
48
|
+
"className": "TramaSystemDragView"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/index.ts
ADDED
package/src/native.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type CodegenTypes, codegenNativeComponent, type HostComponent, type ViewProps } from 'react-native';
|
|
2
|
+
|
|
3
|
+
interface NativeProps extends ViewProps {
|
|
4
|
+
dragPayload?: string;
|
|
5
|
+
dropKinds?: string;
|
|
6
|
+
onTramaDragEvent?: CodegenTypes.DirectEventHandler<Readonly<{ phase: string; payload: string }>>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export default codegenNativeComponent<NativeProps>('TramaSystemDragView') as HostComponent<NativeProps>;
|