expo-quietmark 0.0.0-stage → 0.1.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 +251 -2
- package/android/Vendor/consumer-rules.pro +9 -0
- package/android/Vendor/jniLibs/arm64-v8a/libquietmark_ffi.so +0 -0
- package/android/Vendor/jniLibs/armeabi-v7a/libquietmark_ffi.so +0 -0
- package/android/Vendor/jniLibs/x86_64/libquietmark_ffi.so +0 -0
- package/android/Vendor/kotlin/dev/quietmark/Cards.kt +301 -0
- package/android/Vendor/kotlin/dev/quietmark/Glyphs.kt +117 -0
- package/android/Vendor/kotlin/dev/quietmark/Paragraphs.kt +55 -0
- package/android/Vendor/kotlin/dev/quietmark/QuietmarkEditText.kt +1182 -0
- package/android/Vendor/kotlin/dev/quietmark/QuietmarkTheme.kt +111 -0
- package/android/Vendor/kotlin/dev/quietmark/Spans.kt +204 -0
- package/android/Vendor/kotlin/dev/quietmark/StyleContext.kt +182 -0
- package/android/Vendor/kotlin/dev/quietmark/StyledText.kt +119 -0
- package/android/Vendor/kotlin/dev/quietmark/Styler.kt +646 -0
- package/android/Vendor/kotlin/dev/quietmark/core/EditorModel.kt +222 -0
- package/android/Vendor/kotlin/dev/quietmark/core/Edits.kt +25 -0
- package/android/Vendor/kotlin/dev/quietmark/core/HidePlan.kt +102 -0
- package/android/Vendor/kotlin/dev/quietmark/core/Ranges.kt +71 -0
- package/android/Vendor/kotlin/dev/quietmark/ffi/quietmark_ffi.kt +4117 -0
- package/android/build.gradle +42 -0
- package/android/src/main/java/dev/quietmark/expo/QuietmarkEditorView.kt +418 -0
- package/android/src/main/java/dev/quietmark/expo/QuietmarkModule.kt +184 -0
- package/expo-module.config.json +9 -0
- package/ios/ExpoQuietmark.podspec +42 -0
- package/ios/QuietmarkEditorView.swift +315 -0
- package/ios/QuietmarkModule.swift +144 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/Info.plist +43 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64/QuietmarkFFI.framework/Headers/QuietmarkFFI.h +711 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64/QuietmarkFFI.framework/Info.plist +16 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64/QuietmarkFFI.framework/Modules/module.modulemap +4 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64/QuietmarkFFI.framework/QuietmarkFFI +0 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64/QuietmarkFFI.framework/_CodeSignature/CodeResources +124 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64-simulator/QuietmarkFFI.framework/Headers/QuietmarkFFI.h +711 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64-simulator/QuietmarkFFI.framework/Info.plist +16 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64-simulator/QuietmarkFFI.framework/Modules/module.modulemap +4 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64-simulator/QuietmarkFFI.framework/QuietmarkFFI +0 -0
- package/ios/Vendor/QuietmarkFFI.xcframework/ios-arm64-simulator/QuietmarkFFI.framework/_CodeSignature/CodeResources +124 -0
- package/ios/Vendor/Sources/Quietmark/Cards.swift +218 -0
- package/ios/Vendor/Sources/Quietmark/LayoutFragment.swift +297 -0
- package/ios/Vendor/Sources/Quietmark/Marks.swift +106 -0
- package/ios/Vendor/Sources/Quietmark/QuietmarkTextView.swift +804 -0
- package/ios/Vendor/Sources/Quietmark/Styler.swift +612 -0
- package/ios/Vendor/Sources/Quietmark/Theme.swift +119 -0
- package/ios/Vendor/Sources/QuietmarkCore/EditorModel.swift +216 -0
- package/ios/Vendor/Sources/QuietmarkCore/Edits.swift +25 -0
- package/ios/Vendor/Sources/QuietmarkCore/HidePlan.swift +90 -0
- package/ios/Vendor/Sources/QuietmarkCore/TextRange+Foundation.swift +66 -0
- package/ios/Vendor/Sources/QuietmarkCore/quietmark_ffi.swift +3446 -0
- package/package.json +43 -3
- package/src/QuietmarkEditor.tsx +138 -0
- package/src/index.ts +16 -0
- package/src/types.ts +175 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Max Boksem
|
|
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,252 @@
|
|
|
1
|
-
#
|
|
1
|
+
# expo-quietmark
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`QuietmarkEditor` is a native Markdown editor for React Native. Its text is
|
|
4
|
+
always the Markdown that was typed, byte for byte. Syntax hides while the
|
|
5
|
+
caret is away from it and shows again when the caret reaches it, and
|
|
6
|
+
tables, formulas and pictures draw as they will read.
|
|
7
|
+
|
|
8
|
+
The editor is a native view on the Quietmark Rust core. On iOS it wraps the
|
|
9
|
+
Swift editor in [`apple/`](https://github.com/MaxMB15/Quietmark/tree/main/apple), and on Android the Kotlin editor
|
|
10
|
+
in [`android/`](https://github.com/MaxMB15/Quietmark/tree/main/android). The props, events and ref methods below
|
|
11
|
+
are the same on both. [Platform differences](#platform-differences) lists
|
|
12
|
+
where the two behave differently.
|
|
13
|
+
|
|
14
|
+
## Requirements
|
|
15
|
+
|
|
16
|
+
- An Expo app with a development build. Expo Go can't load the native
|
|
17
|
+
code.
|
|
18
|
+
- React 19, since the component takes `ref` as a prop. The example app
|
|
19
|
+
uses Expo SDK 58 and React Native 0.88.
|
|
20
|
+
- iOS 16.4 or later, or Android 7.0 (API 24) or later.
|
|
21
|
+
|
|
22
|
+
## Installing
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npx expo install expo-quietmark
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Then make a development build, which compiles the native code into the
|
|
29
|
+
app:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
npx expo run:ios
|
|
33
|
+
npx expo run:android
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The package carries the native core already built for both platforms, so
|
|
37
|
+
the app that installs it needs no Rust.
|
|
38
|
+
|
|
39
|
+
### Working on the package
|
|
40
|
+
|
|
41
|
+
To work on the package itself, link the folder into an app instead and run
|
|
42
|
+
`pnpm vendor` in it, once and again after every change to the Rust core or
|
|
43
|
+
the Swift or Kotlin sources. The native builds read from `ios/Vendor` and
|
|
44
|
+
`android/Vendor`, which that command fills and git ignores.
|
|
45
|
+
`pnpm vendor --ios` or `pnpm vendor --android` fills only one. Building
|
|
46
|
+
both cores needs a Mac with Xcode and the Rust toolchain that
|
|
47
|
+
[apple/README.md](https://github.com/MaxMB15/Quietmark/blob/main/apple/README.md#building-the-core) lists, plus the
|
|
48
|
+
Android SDK, an NDK and the Rust targets that
|
|
49
|
+
[android/README.md](https://github.com/MaxMB15/Quietmark/blob/main/android/README.md#building-the-core) lists. The
|
|
50
|
+
iOS core builds only on a Mac, so elsewhere `pnpm vendor` fills
|
|
51
|
+
`android/Vendor` alone.
|
|
52
|
+
|
|
53
|
+
The example app in `example/` is set up this way:
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
cd packages/expo-quietmark/example
|
|
57
|
+
pnpm install
|
|
58
|
+
pnpm vendor
|
|
59
|
+
pnpm ios # or: pnpm android
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
To try a packed copy the way npm would install it, run `pnpm pack` in
|
|
63
|
+
`packages/expo-quietmark`, which builds the cores first, and install the
|
|
64
|
+
`.tgz` it writes into an app with `npm install path/to/expo-quietmark-0.1.0.tgz`.
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
A note editor that keeps its own text, and a message box the app controls:
|
|
69
|
+
|
|
70
|
+
```tsx
|
|
71
|
+
import { QuietmarkEditor, type QuietmarkEditorRef } from "expo-quietmark";
|
|
72
|
+
import { useRef, useState } from "react";
|
|
73
|
+
import { Button, View } from "react-native";
|
|
74
|
+
|
|
75
|
+
export function Note({ initial, onChange }: { initial: string; onChange: (text: string) => void }) {
|
|
76
|
+
const editor = useRef<QuietmarkEditorRef>(null);
|
|
77
|
+
return (
|
|
78
|
+
<View style={{ flex: 1 }}>
|
|
79
|
+
<QuietmarkEditor
|
|
80
|
+
ref={editor}
|
|
81
|
+
style={{ flex: 1 }}
|
|
82
|
+
defaultValue={initial}
|
|
83
|
+
placeholder="Write something"
|
|
84
|
+
contentInset={{ top: 8, left: 16, bottom: 24, right: 16 }}
|
|
85
|
+
onChangeText={onChange}
|
|
86
|
+
/>
|
|
87
|
+
<Button title="Bold" onPress={() => editor.current?.insertText("**bold**")} />
|
|
88
|
+
</View>
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function MessageBox({ onSend }: { onSend: (text: string) => void }) {
|
|
93
|
+
const [message, setMessage] = useState("");
|
|
94
|
+
const send = () => {
|
|
95
|
+
onSend(message);
|
|
96
|
+
setMessage("");
|
|
97
|
+
};
|
|
98
|
+
return (
|
|
99
|
+
<View style={{ flexDirection: "row", alignItems: "flex-end", gap: 8 }}>
|
|
100
|
+
<QuietmarkEditor
|
|
101
|
+
style={{ flex: 1, minHeight: 38 }}
|
|
102
|
+
value={message}
|
|
103
|
+
onChangeText={setMessage}
|
|
104
|
+
options="message"
|
|
105
|
+
theme={{ baseFontSize: 16 }}
|
|
106
|
+
scrollEnabled={false}
|
|
107
|
+
placeholder="Message"
|
|
108
|
+
contentInset={{ top: 8, left: 12, bottom: 8, right: 12 }}
|
|
109
|
+
/>
|
|
110
|
+
<Button title="Send" onPress={send} />
|
|
111
|
+
</View>
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Every offset, in a selection, a pressed block or `setSelection`, counts
|
|
117
|
+
UTF-16 code units, as a JavaScript string does. `text.slice(start, end)`
|
|
118
|
+
gives the selected text.
|
|
119
|
+
|
|
120
|
+
## Props
|
|
121
|
+
|
|
122
|
+
The editor also takes the usual view props, such as `style`.
|
|
123
|
+
|
|
124
|
+
| Prop | Type | Default | What it does |
|
|
125
|
+
| --- | --- | --- | --- |
|
|
126
|
+
| `defaultValue` | `string` | | The starting text, for an editor that keeps its own. |
|
|
127
|
+
| `value` | `string` | | The text, for an editor the app controls. See below. |
|
|
128
|
+
| `options` | `"note"`, `"message"` or `EditorOptions` | `"note"` | What the editor draws. See below. |
|
|
129
|
+
| `editable` | `boolean` | `true` | |
|
|
130
|
+
| `placeholder` | `string` | | Shown while the text is empty. |
|
|
131
|
+
| `autoFocus` | `boolean` | `false` | Focuses the editor once it's on screen. |
|
|
132
|
+
| `scrollEnabled` | `boolean` | `true` | Without scrolling, the editor grows to fit its text, as a message box does. |
|
|
133
|
+
| `contentInset` | `{ top, left, bottom, right }` | | Space around the text, inside the scrolling area. |
|
|
134
|
+
| `theme` | `QuietmarkTheme` | | Colors and sizes. See below. |
|
|
135
|
+
| `editBlockOnPress` | `boolean` | `true` | Whether pressing a card puts the caret in it to edit its source. |
|
|
136
|
+
| `imageBaseUrl` | `string` | | Where relative image addresses resolve from. |
|
|
137
|
+
| `allowedImageDirectories` | `string[]` | | Folders images may load from as files, as paths or `file://` addresses. Only https images load otherwise. |
|
|
138
|
+
|
|
139
|
+
A controlled editor takes `value` and sets it from `onChangeText`. If the
|
|
140
|
+
app keeps the old value, the editor goes back to it, so the app can turn a
|
|
141
|
+
change down. A value that arrives after newer typing is dropped, so a slow
|
|
142
|
+
render doesn't undo keystrokes.
|
|
143
|
+
|
|
144
|
+
### Options
|
|
145
|
+
|
|
146
|
+
`"note"` draws everything. `"message"` keeps every line where it is and
|
|
147
|
+
only hides markers: folding, bullets, tasks, images and HTML are off, and
|
|
148
|
+
math stays on. An object starts from its `preset`, `"note"` by default, and
|
|
149
|
+
changes the fields it names:
|
|
150
|
+
|
|
151
|
+
```tsx
|
|
152
|
+
<QuietmarkEditor
|
|
153
|
+
options={{ preset: "note", foldLines: false, blocks: [{ fence: "mermaid" }, { directive: "cloze" }] }}
|
|
154
|
+
/>
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
| Field | What it draws while the caret is off it |
|
|
158
|
+
| --- | --- |
|
|
159
|
+
| `foldLines` | A fence's own lines, a heading's underline and a table's delimiter row fold away. |
|
|
160
|
+
| `bullets` | A list's `-`, `*` or `+` draws as a bullet. |
|
|
161
|
+
| `tasks` | `[ ]` and `[x]` draw as boxes, which a tap ticks. |
|
|
162
|
+
| `math` | `$x$` in a sentence and `$$` blocks draw as formulas. |
|
|
163
|
+
| `images` | A picture on a line of its own draws. |
|
|
164
|
+
| `html` | Raw HTML blocks draw as cards. |
|
|
165
|
+
| `blocks` | Fences and `:::` containers that match a rule draw as cards and report presses. A list given here replaces the preset's, which is `[{ fence: "mermaid" }]`. |
|
|
166
|
+
|
|
167
|
+
### Theme
|
|
168
|
+
|
|
169
|
+
Anything left out keeps its default, and the defaults follow light and
|
|
170
|
+
dark mode. A plain color stays the same in both. For one that changes, pass
|
|
171
|
+
a `PlatformColor`, or a `DynamicColorIOS` on iOS. On Android a
|
|
172
|
+
`PlatformColor` names a resource or a theme attribute, such as
|
|
173
|
+
`PlatformColor("?attr/colorAccent")`, and the editor resolves it again when
|
|
174
|
+
the mode changes. Another way, on either platform, is to pass a different
|
|
175
|
+
theme when `useColorScheme()` changes.
|
|
176
|
+
|
|
177
|
+
```tsx
|
|
178
|
+
<QuietmarkEditor theme={{ baseFontSize: 16, accent: "#5b3fd9", calloutTints: { tip: "#1d8a52" } }} />
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`baseFontSize` is 17 by default, before the system's text size setting
|
|
182
|
+
scales it, and `lineHeightMultiple` is 1.3. The colors are `text`, `syntax`
|
|
183
|
+
for markers that show and list numbers, `secondaryText`, `placeholder`,
|
|
184
|
+
`link`, `accent` for ticked boxes and untinted callouts, `codeBackground`,
|
|
185
|
+
`inlineCodeBackground`, `quoteBar`, `rule`, `tableGrid`,
|
|
186
|
+
`tableHeaderBackground`, `cardBackground`, `cardBorder` and `highlight` for
|
|
187
|
+
`<mark>`. `calloutTints` maps a callout's kind to its tint, as in
|
|
188
|
+
`{ note: "#2f6fde" }`.
|
|
189
|
+
|
|
190
|
+
## Events
|
|
191
|
+
|
|
192
|
+
| Event | Argument | Fires when |
|
|
193
|
+
| --- | --- | --- |
|
|
194
|
+
| `onChangeText` | `text: string` | the text changed |
|
|
195
|
+
| `onSelectionChange` | `{ start, end }` | the selection moved |
|
|
196
|
+
| `onBlockPress` | `PressedBlock` | a card was pressed |
|
|
197
|
+
| `onLinkPress` | `{ url }` | a link was pressed |
|
|
198
|
+
| `onFocus` | | the editor took focus |
|
|
199
|
+
| `onBlur` | | the editor gave up focus |
|
|
200
|
+
| `onContentSizeChange` | `{ width, height }` | the text's size changed |
|
|
201
|
+
|
|
202
|
+
Without `onLinkPress`, web and mail links open in the system. With it, the
|
|
203
|
+
app decides what a link does.
|
|
204
|
+
|
|
205
|
+
A `PressedBlock` has the block's `source`, its `range` as
|
|
206
|
+
`{ start, end }`, its `first` and `last` lines counted from 0, and `caret`,
|
|
207
|
+
where the caret goes to edit it. Its `kind` says what it is and brings
|
|
208
|
+
fields of its own:
|
|
209
|
+
|
|
210
|
+
| `kind` | Markdown | Extra fields |
|
|
211
|
+
| --- | --- | --- |
|
|
212
|
+
| `"math"` | a `$$` block | |
|
|
213
|
+
| `"image"` | `` on a line of its own | `url`, `alt` |
|
|
214
|
+
| `"callout"` | `> [!NOTE]` and the other alerts | `callout` |
|
|
215
|
+
| `"html"` | an HTML block such as `<details>` | |
|
|
216
|
+
| `"fence"` | a fence that matches a `{ fence }` rule | `info` |
|
|
217
|
+
| `"directive"` | a `:::name` container that matches a `{ directive }` rule | `name`, `attributes` |
|
|
218
|
+
|
|
219
|
+
Only a block at the top level draws as a card. One inside a list or a
|
|
220
|
+
quote stays as text.
|
|
221
|
+
|
|
222
|
+
## Ref methods
|
|
223
|
+
|
|
224
|
+
Each method returns a promise that settles once the editor has done it.
|
|
225
|
+
|
|
226
|
+
| Method | What it does |
|
|
227
|
+
| --- | --- |
|
|
228
|
+
| `focus()` | Focuses the editor. |
|
|
229
|
+
| `blur()` | Drops focus. |
|
|
230
|
+
| `getText()` | Resolves to the text as it is now. |
|
|
231
|
+
| `setText(text)` | Replaces the text and clears undo. `onChangeText` reports it. |
|
|
232
|
+
| `insertText(text)` | Inserts at the selection the way typing does, so it undoes. |
|
|
233
|
+
| `setSelection(start, end?)` | Selects from `start` to `end`, or puts the caret at `start`. |
|
|
234
|
+
|
|
235
|
+
## Platform differences
|
|
236
|
+
|
|
237
|
+
Both editors run the same core against the same test corpus, so they hide,
|
|
238
|
+
show and edit the same Markdown. On Android:
|
|
239
|
+
|
|
240
|
+
- Changing `theme` or `options` sets the text again to restyle it, which
|
|
241
|
+
clears undo and restarts the keyboard's input. iOS restyles in place.
|
|
242
|
+
- Undo is the platform's, so one step takes back what the keyboard
|
|
243
|
+
grouped.
|
|
244
|
+
- While the keyboard is composing a word, Enter and Backspace go to the
|
|
245
|
+
keyboard, not to the core's list and task rules.
|
|
246
|
+
- A fenced code block's background reaches the right edge, and `<kbd>`
|
|
247
|
+
keys sit closer together.
|
|
248
|
+
- Inside a `ScrollView`, a drag on an editor whose text can scroll moves
|
|
249
|
+
the text. A drag on one whose text fits moves the `ScrollView`.
|
|
250
|
+
|
|
251
|
+
[android/README.md](https://github.com/MaxMB15/Quietmark/blob/main/android/README.md#differences-from-ios) has the
|
|
252
|
+
full list for the native view.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Max Boksem
|
|
3
|
+
#
|
|
4
|
+
# The bindings reach Rust through JNA, which finds classes, fields and
|
|
5
|
+
# methods by name at run time.
|
|
6
|
+
-keep class com.sun.jna.** { *; }
|
|
7
|
+
-keep class * implements com.sun.jna.** { *; }
|
|
8
|
+
-keep class dev.quietmark.ffi.** { *; }
|
|
9
|
+
-dontwarn java.awt.**
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Max Boksem
|
|
3
|
+
|
|
4
|
+
package dev.quietmark
|
|
5
|
+
|
|
6
|
+
import android.graphics.Bitmap
|
|
7
|
+
import android.graphics.BitmapFactory
|
|
8
|
+
import android.graphics.Canvas
|
|
9
|
+
import android.graphics.Paint
|
|
10
|
+
import android.graphics.Path
|
|
11
|
+
import android.graphics.RectF
|
|
12
|
+
import android.os.Handler
|
|
13
|
+
import android.os.Looper
|
|
14
|
+
import android.text.TextUtils
|
|
15
|
+
import android.util.LruCache
|
|
16
|
+
import dev.quietmark.ffi.BlockKind
|
|
17
|
+
import dev.quietmark.ffi.DrawnBlock
|
|
18
|
+
import java.io.ByteArrayOutputStream
|
|
19
|
+
import java.io.File
|
|
20
|
+
import java.io.InputStream
|
|
21
|
+
import java.net.HttpURLConnection
|
|
22
|
+
import java.net.URI
|
|
23
|
+
import java.util.concurrent.ExecutorService
|
|
24
|
+
import java.util.concurrent.Executors
|
|
25
|
+
import kotlin.math.ceil
|
|
26
|
+
import kotlin.math.max
|
|
27
|
+
import kotlin.math.min
|
|
28
|
+
|
|
29
|
+
/** A block that draws whole on its line, and the picture it shows, if any. */
|
|
30
|
+
internal class CardMark(val block: DrawnBlock, val height: Int, val image: Bitmap?)
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* How a block drawn whole looks while the caret is off it: a card that
|
|
34
|
+
* names its kind and shows the start of its source, or a picture.
|
|
35
|
+
*/
|
|
36
|
+
internal object Cards {
|
|
37
|
+
/** Space between a card and the lines above and below it, in dp. */
|
|
38
|
+
const val MARGIN = 4f
|
|
39
|
+
private const val PADDING = 10f
|
|
40
|
+
private const val GAP = 4f
|
|
41
|
+
private const val MAX_PREVIEW_LINES = 6
|
|
42
|
+
private const val MAX_IMAGE_HEIGHT = 320f
|
|
43
|
+
private const val IMAGE_PLACEHOLDER_HEIGHT = 72f
|
|
44
|
+
private const val RADIUS = 8f
|
|
45
|
+
|
|
46
|
+
/** The height the card's line takes, its margins included, in pixels. */
|
|
47
|
+
fun height(block: DrawnBlock, width: Float, context: StyleContext, image: Bitmap?): Int {
|
|
48
|
+
val margin = context.dp(MARGIN) * 2
|
|
49
|
+
if (block.kind is BlockKind.Image) {
|
|
50
|
+
if (image == null || image.width <= 0 || width <= 0f) {
|
|
51
|
+
return ceil(context.dp(IMAGE_PLACEHOLDER_HEIGHT) + margin).toInt()
|
|
52
|
+
}
|
|
53
|
+
// A picture's pixels count as dp, as an iOS picture's count as
|
|
54
|
+
// points.
|
|
55
|
+
val natural = image.width * context.density
|
|
56
|
+
val fitted = min(width, natural) * image.height / image.width
|
|
57
|
+
return (ceil(min(fitted, context.dp(MAX_IMAGE_HEIGHT))) + margin).toInt()
|
|
58
|
+
}
|
|
59
|
+
val lines = preview(block).size
|
|
60
|
+
val body = if (lines > 0) context.dp(GAP) + lines * context.lineHeightOf(previewFont(block, context)) else 0f
|
|
61
|
+
return (ceil(context.dp(PADDING) * 2 + context.lineHeightOf(context.small) + body) + margin).toInt()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
fun label(block: DrawnBlock): String = when (val kind = block.kind) {
|
|
65
|
+
is BlockKind.Math -> "Math"
|
|
66
|
+
is BlockKind.Image -> kind.alt.ifEmpty { "Image" }
|
|
67
|
+
is BlockKind.Callout -> kind.kind.replaceFirstChar { it.uppercase() }
|
|
68
|
+
is BlockKind.Html -> "HTML"
|
|
69
|
+
is BlockKind.Fence -> kind.info.ifEmpty { "Code" }
|
|
70
|
+
is BlockKind.Directive -> kind.name
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
fun preview(block: DrawnBlock): List<String> {
|
|
74
|
+
var lines = block.source.split("\n")
|
|
75
|
+
if (block.kind is BlockKind.Callout) lines = calloutBody(lines)
|
|
76
|
+
var from = 0
|
|
77
|
+
var to = lines.size
|
|
78
|
+
while (to > from && lines[to - 1].isBlank()) to--
|
|
79
|
+
while (from < to && lines[from].isBlank()) from++
|
|
80
|
+
return lines.subList(from, to).take(MAX_PREVIEW_LINES)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A callout's lines without their `>` and its `[!kind]` mark, which the
|
|
85
|
+
* card's label already says. A title after the mark stays.
|
|
86
|
+
*/
|
|
87
|
+
private fun calloutBody(lines: List<String>): List<String> {
|
|
88
|
+
val body = lines.map { line ->
|
|
89
|
+
var rest = line.trimStart(' ', '\t')
|
|
90
|
+
if (!rest.startsWith(">")) return@map rest
|
|
91
|
+
rest = rest.substring(1)
|
|
92
|
+
if (rest.startsWith(" ")) rest = rest.substring(1)
|
|
93
|
+
rest
|
|
94
|
+
}.toMutableList()
|
|
95
|
+
val first = body.firstOrNull() ?: return body
|
|
96
|
+
val close = first.indexOf(']')
|
|
97
|
+
if (first.startsWith("[!") && close >= 0) {
|
|
98
|
+
val title = first.substring(close + 1).trimStart('+', '-').trim(' ', '\t')
|
|
99
|
+
if (title.isEmpty()) body.removeAt(0) else body[0] = title
|
|
100
|
+
}
|
|
101
|
+
return body
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
fun previewFont(block: DrawnBlock, context: StyleContext): Font = when (block.kind) {
|
|
105
|
+
is BlockKind.Callout, is BlockKind.Directive -> context.small
|
|
106
|
+
is BlockKind.Math -> context.smallMono.copy(face = context.smallMono.face.copy(italic = true))
|
|
107
|
+
else -> context.smallMono
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fun tint(block: DrawnBlock, context: StyleContext): Int? =
|
|
111
|
+
(block.kind as? BlockKind.Callout)?.let { context.palette.calloutTint(it.kind) }
|
|
112
|
+
|
|
113
|
+
private val shape = Path()
|
|
114
|
+
private val bounds = RectF()
|
|
115
|
+
|
|
116
|
+
/** Draws a card in [rect], the line's box less its margins. */
|
|
117
|
+
fun draw(canvas: Canvas, card: CardMark, rect: RectF, context: StyleContext) {
|
|
118
|
+
val palette = context.palette
|
|
119
|
+
val radius = context.dp(RADIUS)
|
|
120
|
+
val padding = context.dp(PADDING)
|
|
121
|
+
val paint = context.fill
|
|
122
|
+
paint.reset()
|
|
123
|
+
paint.isAntiAlias = true
|
|
124
|
+
val kind = card.block.kind
|
|
125
|
+
if (kind is BlockKind.Image) {
|
|
126
|
+
val image = card.image
|
|
127
|
+
if (image != null && image.width > 0) {
|
|
128
|
+
val width = min(rect.width(), image.width * context.density)
|
|
129
|
+
val height = min(rect.height(), width * image.height / image.width)
|
|
130
|
+
bounds.set(rect.left, rect.top, rect.left + width, rect.top + height)
|
|
131
|
+
shape.rewind()
|
|
132
|
+
shape.addRoundRect(bounds, radius, radius, Path.Direction.CW)
|
|
133
|
+
canvas.save()
|
|
134
|
+
canvas.clipPath(shape)
|
|
135
|
+
paint.isFilterBitmap = true
|
|
136
|
+
canvas.drawBitmap(image, null, bounds, paint)
|
|
137
|
+
canvas.restore()
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
paint.color = palette.cardBackground
|
|
141
|
+
canvas.drawRoundRect(rect, radius, radius, paint)
|
|
142
|
+
val text = context.textPaint(context.small, palette.secondaryText)
|
|
143
|
+
val shown = TextUtils.ellipsize(kind.alt.ifEmpty { "Image" }, text, rect.width() - padding * 2, TextUtils.TruncateAt.END)
|
|
144
|
+
val fm = context.fontMetrics(context.small)
|
|
145
|
+
canvas.drawText(shown, 0, shown.length, rect.left + padding, rect.centerY() - (fm.ascent + fm.descent) / 2f, text)
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
val tint = tint(card.block, context)
|
|
150
|
+
if (tint != null) {
|
|
151
|
+
paint.color = StyleContext.withAlpha(tint, 0.1f)
|
|
152
|
+
canvas.drawRoundRect(rect, radius, radius, paint)
|
|
153
|
+
shape.rewind()
|
|
154
|
+
shape.addRoundRect(rect, radius, radius, Path.Direction.CW)
|
|
155
|
+
canvas.save()
|
|
156
|
+
canvas.clipPath(shape)
|
|
157
|
+
paint.color = tint
|
|
158
|
+
canvas.drawRect(rect.left, rect.top, rect.left + context.dp(3f), rect.bottom, paint)
|
|
159
|
+
canvas.restore()
|
|
160
|
+
} else {
|
|
161
|
+
paint.color = palette.cardBackground
|
|
162
|
+
canvas.drawRoundRect(rect, radius, radius, paint)
|
|
163
|
+
val line = context.hairline
|
|
164
|
+
bounds.set(rect)
|
|
165
|
+
bounds.inset(line / 2, line / 2)
|
|
166
|
+
paint.style = Paint.Style.STROKE
|
|
167
|
+
paint.strokeWidth = line
|
|
168
|
+
paint.color = palette.cardBorder
|
|
169
|
+
canvas.drawRoundRect(bounds, radius, radius, paint)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
val inner = rect.width() - padding * 2
|
|
173
|
+
if (inner <= 0f) return
|
|
174
|
+
var y = rect.top + padding
|
|
175
|
+
val labelFont = Font(context.small.face.copy(weight = 700), context.small.size)
|
|
176
|
+
drawLine(canvas, label(card.block), labelFont, tint ?: palette.secondaryText, rect.left + padding, y, inner, context)
|
|
177
|
+
y += context.lineHeightOf(context.small) + context.dp(GAP)
|
|
178
|
+
val font = previewFont(card.block, context)
|
|
179
|
+
val lineHeight = context.lineHeightOf(font)
|
|
180
|
+
for (line in preview(card.block)) {
|
|
181
|
+
drawLine(canvas, line, font, palette.text, rect.left + padding, y, inner, context)
|
|
182
|
+
y += lineHeight
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** One line of text whose top is at [y], cut short with an ellipsis. */
|
|
187
|
+
private fun drawLine(canvas: Canvas, line: String, font: Font, color: Int, x: Float, y: Float, width: Float, context: StyleContext) {
|
|
188
|
+
val paint = context.textPaint(font, color)
|
|
189
|
+
val shown = TextUtils.ellipsize(line.replace('\t', ' '), paint, width, TextUtils.TruncateAt.END)
|
|
190
|
+
canvas.drawText(shown, 0, shown.length, x, y + context.metrics(font).ascent, paint)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Loads pictures for image cards: over https, or from a file the app
|
|
196
|
+
* allows. Each is decoded and scaled down off the main thread, and kept
|
|
197
|
+
* while the cache has room.
|
|
198
|
+
*/
|
|
199
|
+
internal class ImageLoader {
|
|
200
|
+
private val cache = object : LruCache<String, Bitmap>(CACHE_BYTES) {
|
|
201
|
+
override fun sizeOf(key: String, value: Bitmap): Int = value.allocationByteCount
|
|
202
|
+
}
|
|
203
|
+
private val loading = HashSet<String>()
|
|
204
|
+
private val failed = HashSet<String>()
|
|
205
|
+
private val main = Handler(Looper.getMainLooper())
|
|
206
|
+
|
|
207
|
+
/** Called on the main thread once a picture is ready. */
|
|
208
|
+
var onLoad: ((String) -> Unit)? = null
|
|
209
|
+
|
|
210
|
+
/** The picture if it's ready; otherwise it starts loading and is null. */
|
|
211
|
+
fun image(url: String): Bitmap? {
|
|
212
|
+
cache.get(url)?.let { return it }
|
|
213
|
+
if (url in loading || url in failed) return null
|
|
214
|
+
loading.add(url)
|
|
215
|
+
executor.execute {
|
|
216
|
+
val image = try {
|
|
217
|
+
read(url)?.let(::decode)
|
|
218
|
+
} catch (_: Exception) {
|
|
219
|
+
null
|
|
220
|
+
} catch (_: OutOfMemoryError) {
|
|
221
|
+
null
|
|
222
|
+
}
|
|
223
|
+
main.post {
|
|
224
|
+
loading.remove(url)
|
|
225
|
+
if (image == null) {
|
|
226
|
+
failed.add(url)
|
|
227
|
+
} else {
|
|
228
|
+
cache.put(url, image)
|
|
229
|
+
onLoad?.invoke(url)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return null
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
fun forgetFailures() {
|
|
237
|
+
failed.clear()
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private fun read(url: String): ByteArray? {
|
|
241
|
+
val uri = URI(url)
|
|
242
|
+
if (uri.scheme.equals("file", ignoreCase = true)) return File(uri).inputStream().use(::readLimited)
|
|
243
|
+
val connection = uri.toURL().openConnection() as HttpURLConnection
|
|
244
|
+
try {
|
|
245
|
+
connection.connectTimeout = TIMEOUT
|
|
246
|
+
connection.readTimeout = TIMEOUT
|
|
247
|
+
connection.instanceFollowRedirects = true
|
|
248
|
+
if (connection.responseCode !in 200 until 300) return null
|
|
249
|
+
return connection.inputStream.use(::readLimited)
|
|
250
|
+
} finally {
|
|
251
|
+
connection.disconnect()
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private fun readLimited(input: InputStream): ByteArray? {
|
|
256
|
+
val out = ByteArrayOutputStream()
|
|
257
|
+
val buffer = ByteArray(64 * 1024)
|
|
258
|
+
while (true) {
|
|
259
|
+
val count = input.read(buffer)
|
|
260
|
+
if (count < 0) break
|
|
261
|
+
out.write(buffer, 0, count)
|
|
262
|
+
if (out.size() > MAX_BYTES) return null
|
|
263
|
+
}
|
|
264
|
+
return out.toByteArray()
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
companion object {
|
|
268
|
+
private const val CACHE_BYTES = 48 * 1024 * 1024
|
|
269
|
+
private const val MAX_BYTES = 40 * 1024 * 1024
|
|
270
|
+
private const val TIMEOUT = 20_000
|
|
271
|
+
private const val LONGEST = 1600
|
|
272
|
+
|
|
273
|
+
private val executor: ExecutorService = Executors.newFixedThreadPool(2) { runnable ->
|
|
274
|
+
Thread(runnable, "quietmark-images").apply { isDaemon = true }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Scales a picture down to at most 1600 pixels on its long side,
|
|
279
|
+
* which is more than a card shows, so a camera photo doesn't sit in
|
|
280
|
+
* memory whole.
|
|
281
|
+
*/
|
|
282
|
+
fun decode(data: ByteArray): Bitmap? {
|
|
283
|
+
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|
284
|
+
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
|
285
|
+
val longest = max(bounds.outWidth, bounds.outHeight)
|
|
286
|
+
if (longest <= 0) return null
|
|
287
|
+
var sample = 1
|
|
288
|
+
while (longest / (sample * 2) >= LONGEST) sample *= 2
|
|
289
|
+
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
|
290
|
+
val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, options) ?: return null
|
|
291
|
+
val side = max(bitmap.width, bitmap.height)
|
|
292
|
+
if (side <= LONGEST) return bitmap
|
|
293
|
+
val factor = LONGEST.toFloat() / side
|
|
294
|
+
val scaled = Bitmap.createScaledBitmap(
|
|
295
|
+
bitmap, max(1, (bitmap.width * factor).toInt()), max(1, (bitmap.height * factor).toInt()), true,
|
|
296
|
+
)
|
|
297
|
+
if (scaled !== bitmap) bitmap.recycle()
|
|
298
|
+
return scaled
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|