You've already forked joplin
mirror of
https://github.com/laurent22/joplin.git
synced 2025-12-26 23:38:08 +02:00
Compare commits
8 Commits
fix_publis
...
table_edit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b519d55abf | ||
|
|
5a862443d8 | ||
|
|
30e191663d | ||
|
|
70cd2395fb | ||
|
|
2f1b6fbee1 | ||
|
|
8c0d4a0f71 | ||
|
|
bc08c6dcc3 | ||
|
|
a06365039d |
@@ -421,6 +421,9 @@ packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/styles/index.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.js.map
|
||||
@@ -688,6 +691,9 @@ packages/app-desktop/gui/StyleSheets/StyleSheetContainer.js.map
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.d.ts
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.js
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.js.map
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.d.ts
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.js
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.js.map
|
||||
packages/app-desktop/gui/TagList.d.ts
|
||||
packages/app-desktop/gui/TagList.js
|
||||
packages/app-desktop/gui/TagList.js.map
|
||||
@@ -1489,9 +1495,6 @@ packages/lib/services/keychain/KeychainServiceDriver.node.js.map
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.d.ts
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.js
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.js.map
|
||||
packages/lib/services/plugins/BasePlatformImplementation.d.ts
|
||||
packages/lib/services/plugins/BasePlatformImplementation.js
|
||||
packages/lib/services/plugins/BasePlatformImplementation.js.map
|
||||
packages/lib/services/plugins/BasePluginRunner.d.ts
|
||||
packages/lib/services/plugins/BasePluginRunner.js
|
||||
packages/lib/services/plugins/BasePluginRunner.js.map
|
||||
@@ -1933,9 +1936,6 @@ packages/plugins/ToggleSidebars/api/types.js.map
|
||||
packages/plugins/ToggleSidebars/src/index.d.ts
|
||||
packages/plugins/ToggleSidebars/src/index.js
|
||||
packages/plugins/ToggleSidebars/src/index.js.map
|
||||
packages/react-native-saf-x/src/index.d.ts
|
||||
packages/react-native-saf-x/src/index.js
|
||||
packages/react-native-saf-x/src/index.js.map
|
||||
packages/renderer/HtmlToHtml.d.ts
|
||||
packages/renderer/HtmlToHtml.js
|
||||
packages/renderer/HtmlToHtml.js.map
|
||||
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -411,6 +411,9 @@ packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/styles/index.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/index.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/tables.js.map
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.d.ts
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.js
|
||||
packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/types.js.map
|
||||
@@ -678,6 +681,9 @@ packages/app-desktop/gui/StyleSheets/StyleSheetContainer.js.map
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.d.ts
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.js
|
||||
packages/app-desktop/gui/SyncWizard/Dialog.js.map
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.d.ts
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.js
|
||||
packages/app-desktop/gui/TableEditorDialog/Dialog.js.map
|
||||
packages/app-desktop/gui/TagList.d.ts
|
||||
packages/app-desktop/gui/TagList.js
|
||||
packages/app-desktop/gui/TagList.js.map
|
||||
@@ -1479,9 +1485,6 @@ packages/lib/services/keychain/KeychainServiceDriver.node.js.map
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.d.ts
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.js
|
||||
packages/lib/services/keychain/KeychainServiceDriverBase.js.map
|
||||
packages/lib/services/plugins/BasePlatformImplementation.d.ts
|
||||
packages/lib/services/plugins/BasePlatformImplementation.js
|
||||
packages/lib/services/plugins/BasePlatformImplementation.js.map
|
||||
packages/lib/services/plugins/BasePluginRunner.d.ts
|
||||
packages/lib/services/plugins/BasePluginRunner.js
|
||||
packages/lib/services/plugins/BasePluginRunner.js.map
|
||||
@@ -1923,9 +1926,6 @@ packages/plugins/ToggleSidebars/api/types.js.map
|
||||
packages/plugins/ToggleSidebars/src/index.d.ts
|
||||
packages/plugins/ToggleSidebars/src/index.js
|
||||
packages/plugins/ToggleSidebars/src/index.js.map
|
||||
packages/react-native-saf-x/src/index.d.ts
|
||||
packages/react-native-saf-x/src/index.js
|
||||
packages/react-native-saf-x/src/index.js.map
|
||||
packages/renderer/HtmlToHtml.d.ts
|
||||
packages/renderer/HtmlToHtml.js
|
||||
packages/renderer/HtmlToHtml.js.map
|
||||
|
||||
@@ -9,13 +9,11 @@ import PluginManager from 'tinymce/core/api/PluginManager';
|
||||
import * as Api from './api/Api';
|
||||
import * as Commands from './api/Commands';
|
||||
import * as Keyboard from './core/Keyboard';
|
||||
import * as Mouse from './core/Mouse'
|
||||
import * as Buttons from './ui/Buttons';
|
||||
|
||||
export default function () {
|
||||
PluginManager.add('joplinLists', function (editor) {
|
||||
Keyboard.setup(editor);
|
||||
Mouse.setup(editor);
|
||||
Buttons.register(editor);
|
||||
Commands.register(editor);
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { isJoplinChecklistItem } from '../listModel/JoplinListUtil';
|
||||
|
||||
|
||||
const setup = function (editor) {
|
||||
const editorClickHandler = (event) => {
|
||||
if (!isJoplinChecklistItem(event.target)) return;
|
||||
|
||||
// We only process the click if it's within the checkbox itself (and not the label).
|
||||
// That checkbox, based on
|
||||
// the current styling is in the negative margin, so offsetX is negative when clicking
|
||||
// on the checkbox itself, and positive when clicking on the label. This is strongly
|
||||
// dependent on how the checkbox is styled, so if the style is changed, this might need
|
||||
// to be updated too.
|
||||
// For the styling, see:
|
||||
// packages/renderer/MdToHtml/rules/checkbox.ts
|
||||
//
|
||||
// The previous solution was to use "pointer-event: none", which mostly work, however
|
||||
// it means that links are no longer clickable when they are within the checkbox label.
|
||||
if (event.offsetX >= 0) return;
|
||||
|
||||
editor.execCommand('ToggleJoplinChecklistItem', false, { element: event.target });
|
||||
}
|
||||
editor.on('click', editorClickHandler);
|
||||
};
|
||||
|
||||
export { setup };
|
||||
@@ -10,7 +10,7 @@ import * as Settings from '../api/Settings';
|
||||
import * as NodeType from '../core/NodeType';
|
||||
import Editor from 'tinymce/core/api/Editor';
|
||||
import { isCustomList } from '../core/Util';
|
||||
import { findContainerListTypeFromEvent } from '../listModel/JoplinListUtil';
|
||||
import { findContainerListTypeFromEvent, isJoplinChecklistItem } from '../listModel/JoplinListUtil';
|
||||
|
||||
const findIndex = function (list, predicate) {
|
||||
for (let index = 0; index < list.length; index++) {
|
||||
@@ -38,11 +38,37 @@ const listState = function (editor: Editor, listName, options:any = {}) {
|
||||
buttonApi.setActive(listType === options.listType && lists.length > 0 && lists[0].nodeName === listName && !isCustomList(lists[0]));
|
||||
};
|
||||
|
||||
const editorClickHandler = (event) => {
|
||||
if (!isJoplinChecklistItem(event.target)) return;
|
||||
|
||||
// We only process the click if it's within the checkbox itself (and not the label).
|
||||
// That checkbox, based on
|
||||
// the current styling is in the negative margin, so offsetX is negative when clicking
|
||||
// on the checkbox itself, and positive when clicking on the label. This is strongly
|
||||
// dependent on how the checkbox is styled, so if the style is changed, this might need
|
||||
// to be updated too.
|
||||
// For the styling, see:
|
||||
// packages/renderer/MdToHtml/rules/checkbox.ts
|
||||
//
|
||||
// The previous solution was to use "pointer-event: none", which mostly work, however
|
||||
// it means that links are no longer clickable when they are within the checkbox label.
|
||||
if (event.offsetX >= 0) return;
|
||||
|
||||
editor.execCommand('ToggleJoplinChecklistItem', false, { element: event.target });
|
||||
}
|
||||
|
||||
if (options.listType === 'joplinChecklist') {
|
||||
editor.on('click', editorClickHandler);
|
||||
}
|
||||
|
||||
editor.on('NodeChange', nodeChangeHandler);
|
||||
|
||||
return () => {
|
||||
if (options.listType === 'joplinChecklist') {
|
||||
editor.off('click', editorClickHandler);
|
||||
}
|
||||
editor.off('NodeChange', nodeChangeHandler);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
<!-- Monthly/Yearly plan A/B testing -->
|
||||
<!--
|
||||
<script src="https://www.googleoptimize.com/optimize.js?id=OPT-PW3ZPK3"></script>
|
||||
-->
|
||||
|
||||
<!-- Donate button A/B testing -->
|
||||
<!--
|
||||
|
||||
@@ -49,7 +49,7 @@ Coding style is enforced by a pre-commit hook that runs eslint. This hook is ins
|
||||
|
||||
For new React components, please use [React Hooks](https://reactjs.org/docs/hooks-intro.html). For new code in general, please use TypeScript. Even if you are modifying a file that was originally in JavaScript you should ideally convert it first to TypeScript before modifying it. Doing so is relatively easy and it helps maintain code quality.
|
||||
|
||||
For changes made to the Desktop and mobile clients that affect the user interface, refer to `packages/lib/theme.ts` for all styling information. The goal is to create a consistent user interface to allow for easy navigation of Joplin's various features and improve the overall user experience.
|
||||
For changes made to the Desktop client that affect the user interface, refer to `packages/app-desktop/theme.ts` for all styling information. The goal is to create a consistent user interface to allow for easy navigation of Joplin's various features and improve the overall user experience.
|
||||
|
||||
## Automated tests
|
||||
|
||||
|
||||
@@ -325,7 +325,6 @@
|
||||
"homenote",
|
||||
"hotfolder",
|
||||
"Howver",
|
||||
"hpagent",
|
||||
"Hrvatska",
|
||||
"htmlentities",
|
||||
"htmlfile",
|
||||
@@ -951,4 +950,4 @@
|
||||
"မြန်မာ",
|
||||
"កម្ពុជា"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ const Folder = require('@joplin/lib/models/Folder').default;
|
||||
const Tag = require('@joplin/lib/models/Tag').default;
|
||||
const BaseModel = require('@joplin/lib/BaseModel').default;
|
||||
const ListWidget = require('tkwidgets/ListWidget.js');
|
||||
const Setting = require('@joplin/lib/models/Setting').default;
|
||||
const _ = require('@joplin/lib/locale')._;
|
||||
|
||||
class FolderListWidget extends ListWidget {
|
||||
@@ -26,18 +25,6 @@ class FolderListWidget extends ListWidget {
|
||||
output.push('-'.repeat(this.innerWidth));
|
||||
} else if (item.type_ === Folder.modelType()) {
|
||||
output.push(' '.repeat(this.folderDepth(this.folders, item.id)) + Folder.displayTitle(item));
|
||||
if (Setting.value('showNoteCounts')) {
|
||||
let noteCount = item.note_count;
|
||||
// Subtract children note_count from parent folder.
|
||||
if (this.folderHasChildren_(this.folders,item.id)) {
|
||||
for (let i = 0; i < this.folders.length; i++) {
|
||||
if (this.folders[i].parent_id === item.id) {
|
||||
noteCount -= this.folders[i].note_count;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(noteCount);
|
||||
}
|
||||
} else if (item.type_ === Tag.modelType()) {
|
||||
output.push(`[${Folder.displayTitle(item)}]`);
|
||||
} else if (item.type_ === BaseModel.TYPE_SEARCH) {
|
||||
|
||||
@@ -26,7 +26,7 @@ const sharp = require('sharp');
|
||||
const { shimInit } = require('@joplin/lib/shim-init-node.js');
|
||||
const shim = require('@joplin/lib/shim').default;
|
||||
const { _ } = require('@joplin/lib/locale');
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
|
||||
const EncryptionService = require('@joplin/lib/services/e2ee/EncryptionService').default;
|
||||
const envFromArgs = require('@joplin/lib/envFromArgs');
|
||||
const nodeSqlite = require('sqlite3');
|
||||
|
||||
@@ -33,14 +33,14 @@
|
||||
],
|
||||
"owner": "Laurent Cozic"
|
||||
},
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"bin": "./main.js",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@joplin/lib": "~2.9",
|
||||
"@joplin/renderer": "~2.9",
|
||||
"@joplin/lib": "~2.8",
|
||||
"@joplin/renderer": "~2.8",
|
||||
"aws-sdk": "^2.588.0",
|
||||
"chalk": "^4.1.0",
|
||||
"compare-version": "^0.1.2",
|
||||
@@ -67,7 +67,7 @@
|
||||
"yargs-parser": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@joplin/tools": "~2.9",
|
||||
"@joplin/tools": "~2.8",
|
||||
"@types/fs-extra": "^9.0.6",
|
||||
"@types/jest": "^26.0.15",
|
||||
"@types/node": "^14.14.6",
|
||||
|
||||
@@ -32,15 +32,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function pageTitle() {
|
||||
const titleElements = document.getElementsByTagName('title');
|
||||
if (titleElements.length) return titleElements[0].text.trim();
|
||||
@@ -213,16 +204,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeName === 'embed') {
|
||||
const src = absoluteUrl(node.src);
|
||||
node.setAttribute('src', src);
|
||||
}
|
||||
|
||||
if (nodeName === 'object') {
|
||||
const data = absoluteUrl(node.data);
|
||||
node.setAttribute('data', data);
|
||||
}
|
||||
|
||||
cleanUpElement(convertToMarkup, node, imageSizes, imageIndexes);
|
||||
}
|
||||
}
|
||||
@@ -336,9 +317,6 @@
|
||||
}
|
||||
|
||||
function readabilityProcess() {
|
||||
|
||||
if (isPagePdf()) throw new Error('Could not parse PDF document with Readability');
|
||||
|
||||
// eslint-disable-next-line no-undef
|
||||
const readability = new Readability(documentForReadability());
|
||||
const article = readability.parse();
|
||||
@@ -351,14 +329,6 @@
|
||||
};
|
||||
}
|
||||
|
||||
function isPagePdf() {
|
||||
return document.contentType == 'application/pdf';
|
||||
}
|
||||
|
||||
function embedPageUrl() {
|
||||
return `<embed src="${escapeHtml(window.location.href)}" type="${escapeHtml(document.contentType)}" />`;
|
||||
}
|
||||
|
||||
async function prepareCommandResponse(command) {
|
||||
console.info(`Got command: ${command.name}`);
|
||||
const shouldSendToJoplin = !!command.shouldSendToJoplin;
|
||||
@@ -405,10 +375,6 @@
|
||||
|
||||
} else if (command.name === 'completePageHtml') {
|
||||
|
||||
if (isPagePdf()) {
|
||||
return clippedContentResponse(pageTitle(), embedPageUrl(), getImageSizes(document), getAnchorNames(document));
|
||||
}
|
||||
|
||||
hardcodePreStyles(document);
|
||||
addSvgClass(document);
|
||||
preProcessDocument(document);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 2,
|
||||
"name": "Joplin Web Clipper [DEV]",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"description": "Capture and save web pages and screenshots from your browser to Joplin.",
|
||||
"homepage_url": "https://joplinapp.org",
|
||||
"content_security_policy": "script-src 'self'; object-src 'self'",
|
||||
|
||||
@@ -38,6 +38,7 @@ import ErrorBoundary from '../../../ErrorBoundary';
|
||||
import { MarkupToHtmlOptions } from '../../utils/useMarkupToHtml';
|
||||
import eventManager from '@joplin/lib/eventManager';
|
||||
import { EditContextMenuFilterObject } from '@joplin/lib/services/plugins/api/JoplinWorkspace';
|
||||
import { checkTableIsUnderCursor, readTableAroundCursor } from './utils/tables';
|
||||
|
||||
const menuUtils = new MenuUtils(CommandService.instance());
|
||||
|
||||
@@ -706,8 +707,6 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
|
||||
return output;
|
||||
}, [styles.cellViewer, props.visiblePanes]);
|
||||
|
||||
const editorPaneVisible = props.visiblePanes.indexOf('editor') >= 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (!editorRef.current) return;
|
||||
|
||||
@@ -715,10 +714,10 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
|
||||
// we should focus the editor
|
||||
// The intuition is that a panel toggle (with editor in view) is the equivalent of
|
||||
// an editor interaction so users should expect the editor to be focused
|
||||
if (editorPaneVisible) {
|
||||
if (props.visiblePanes.indexOf('editor') >= 0) {
|
||||
editorRef.current.focus();
|
||||
}
|
||||
}, [editorPaneVisible]);
|
||||
}, [props.visiblePanes]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editorRef.current) return;
|
||||
@@ -755,7 +754,14 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
|
||||
|
||||
const menu = new Menu();
|
||||
|
||||
const hasSelectedText = editorRef.current && !!editorRef.current.getSelection() ;
|
||||
const cm = editorRef.current;
|
||||
|
||||
const hasSelectedText = cm && !!cm.getSelection() ;
|
||||
|
||||
const tableIsUnderCursor = checkTableIsUnderCursor(cm);
|
||||
let tableUnderCursor: string = null;
|
||||
|
||||
if (tableIsUnderCursor) tableUnderCursor = readTableAroundCursor(cm);
|
||||
|
||||
menu.append(
|
||||
new MenuItem({
|
||||
@@ -787,6 +793,27 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
|
||||
})
|
||||
);
|
||||
|
||||
if (tableUnderCursor) {
|
||||
menu.append(
|
||||
new MenuItem({ type: 'separator' })
|
||||
);
|
||||
|
||||
menu.append(
|
||||
new MenuItem({
|
||||
label: _('Edit table...'),
|
||||
click: async () => {
|
||||
props.dispatch({
|
||||
type: 'DIALOG_OPEN',
|
||||
name: 'tableEditor',
|
||||
props: {
|
||||
markdownTable: tableUnderCursor,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const spellCheckerMenuItems = SpellCheckerService.instance().contextMenuItems(params.misspelledWord, params.dictionarySuggestions);
|
||||
|
||||
for (const item of spellCheckerMenuItems) {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
function findElementWithClass(element: any, className: string): any {
|
||||
if (element.classList && element.classList.contains(className)) return element;
|
||||
|
||||
for (const child of element.childNodes) {
|
||||
const hasClass = findElementWithClass(child, className);
|
||||
if (hasClass) return hasClass;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const checkTableIsUnderCursor = (cm: any) => {
|
||||
if (!cm) return false;
|
||||
|
||||
const coords = cm.cursorCoords(cm.getCursor());
|
||||
const element = document.elementFromPoint(coords.left, coords.top);
|
||||
if (!element) return false;
|
||||
return !!findElementWithClass(element, 'cm-jn-table-item');
|
||||
};
|
||||
|
||||
export const readTableAroundCursor = (cm: any) => {
|
||||
const idxAtCursor = cm.doc.getCursor().line;
|
||||
const lineCount = cm.lineCount();
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
for (let i = idxAtCursor - 1; i >= 0; i--) {
|
||||
const line: string = cm.doc.getLine(i);
|
||||
if (line.startsWith('|')) {
|
||||
lines.splice(0, 0, line);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(cm.doc.getLine(idxAtCursor));
|
||||
|
||||
for (let i = idxAtCursor + 1; i < lineCount; i++) {
|
||||
const line: string = cm.doc.getLine(i);
|
||||
if (line.startsWith('|')) {
|
||||
lines.push(line);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
};
|
||||
@@ -165,6 +165,7 @@ export default function useJoplinMode(CodeMirror: any) {
|
||||
}
|
||||
|
||||
if (isMonospace) { token = `${token} jn-monospace`; }
|
||||
if (state.inTable) { token = `${token} jn-table-item`; }
|
||||
// //////// End Monospace //////////
|
||||
|
||||
return token;
|
||||
|
||||
@@ -2078,17 +2078,6 @@
|
||||
setup(editor);
|
||||
};
|
||||
|
||||
var setup$2 = function (editor) {
|
||||
var editorClickHandler = function (event) {
|
||||
if (!isJoplinChecklistItem(event.target))
|
||||
return;
|
||||
if (event.offsetX >= 0)
|
||||
return;
|
||||
editor.execCommand('ToggleJoplinChecklistItem', false, { element: event.target });
|
||||
};
|
||||
editor.on('click', editorClickHandler);
|
||||
};
|
||||
|
||||
var findIndex = function (list, predicate) {
|
||||
for (var index = 0; index < list.length; index++) {
|
||||
var element = list[index];
|
||||
@@ -2111,8 +2100,21 @@
|
||||
var listType = findContainerListTypeFromEvent(e);
|
||||
buttonApi.setActive(listType === options.listType && lists.length > 0 && lists[0].nodeName === listName && !isCustomList(lists[0]));
|
||||
};
|
||||
var editorClickHandler = function (event) {
|
||||
if (!isJoplinChecklistItem(event.target))
|
||||
return;
|
||||
if (event.offsetX >= 0)
|
||||
return;
|
||||
editor.execCommand('ToggleJoplinChecklistItem', false, { element: event.target });
|
||||
};
|
||||
if (options.listType === 'joplinChecklist') {
|
||||
editor.on('click', editorClickHandler);
|
||||
}
|
||||
editor.on('NodeChange', nodeChangeHandler);
|
||||
return function () {
|
||||
if (options.listType === 'joplinChecklist') {
|
||||
editor.off('click', editorClickHandler);
|
||||
}
|
||||
editor.off('NodeChange', nodeChangeHandler);
|
||||
};
|
||||
};
|
||||
@@ -2156,7 +2158,6 @@
|
||||
function Plugin () {
|
||||
PluginManager.add('joplinLists', function (editor) {
|
||||
setup$1(editor);
|
||||
setup$2(editor);
|
||||
register$1(editor);
|
||||
register(editor);
|
||||
return get(editor);
|
||||
|
||||
@@ -114,7 +114,7 @@ export default function useFormNote(dependencies: HookDependencies) {
|
||||
if (syncStarted) return () => {};
|
||||
if (formNote.hasChanged) return () => {};
|
||||
|
||||
reg.logger().info('Sync has finished and note has never been changed - reloading it');
|
||||
reg.logger().debug('Sync has finished and note has never been changed - reloading it');
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
|
||||
@@ -456,11 +456,6 @@ const NoteListComponent = (props: Props) => {
|
||||
useEffect(() => {
|
||||
// When a note list item is styled by userchrome.css, its height is reflected.
|
||||
// Ref. https://github.com/laurent22/joplin/pull/6542
|
||||
if (dragOverTargetNoteIndex !== null) {
|
||||
// When dragged, its height should not be considered.
|
||||
// Ref. https://github.com/laurent22/joplin/issues/6639
|
||||
return;
|
||||
}
|
||||
const noteItem = Object.values<any>(itemAnchorRefs_.current)[0]?.current;
|
||||
const actualItemHeight = noteItem?.getHeight() ?? 0;
|
||||
if (actualItemHeight >= 8) { // To avoid generating too many narrow items
|
||||
|
||||
@@ -22,6 +22,7 @@ import Dialog from './Dialog';
|
||||
import SyncWizardDialog from './SyncWizard/Dialog';
|
||||
import MasterPasswordDialog from './MasterPasswordDialog/Dialog';
|
||||
import EditFolderDialog from './EditFolderDialog/Dialog';
|
||||
import TableEditorDialog from './TableEditorDialog/Dialog';
|
||||
import StyleSheetContainer from './StyleSheets/StyleSheetContainer';
|
||||
const { ImportScreen } = require('./ImportScreen.min.js');
|
||||
const { ResourceScreen } = require('./ResourceScreen.js');
|
||||
@@ -38,6 +39,7 @@ interface Props {
|
||||
zoomFactor: number;
|
||||
needApiAuth: boolean;
|
||||
dialogs: AppStateDialog[];
|
||||
dialogContentMaxSize: Size;
|
||||
}
|
||||
|
||||
interface ModalDialogProps {
|
||||
@@ -51,6 +53,7 @@ interface RegisteredDialogProps {
|
||||
themeId: number;
|
||||
key: string;
|
||||
dispatch: Function;
|
||||
dialogContentMaxSize: Size;
|
||||
}
|
||||
|
||||
interface RegisteredDialog {
|
||||
@@ -60,19 +63,25 @@ interface RegisteredDialog {
|
||||
const registeredDialogs: Record<string, RegisteredDialog> = {
|
||||
syncWizard: {
|
||||
render: (props: RegisteredDialogProps, customProps: any) => {
|
||||
return <SyncWizardDialog key={props.key} dispatch={props.dispatch} themeId={props.themeId} {...customProps}/>;
|
||||
return <SyncWizardDialog key={props.key} dispatch={props.dispatch} dialogContentMaxSize={props.dialogContentMaxSize} themeId={props.themeId} {...customProps}/>;
|
||||
},
|
||||
},
|
||||
|
||||
masterPassword: {
|
||||
render: (props: RegisteredDialogProps, customProps: any) => {
|
||||
return <MasterPasswordDialog key={props.key} dispatch={props.dispatch} themeId={props.themeId} {...customProps}/>;
|
||||
return <MasterPasswordDialog key={props.key} dispatch={props.dispatch} dialogContentMaxSize={props.dialogContentMaxSize} themeId={props.themeId} {...customProps}/>;
|
||||
},
|
||||
},
|
||||
|
||||
editFolder: {
|
||||
render: (props: RegisteredDialogProps, customProps: any) => {
|
||||
return <EditFolderDialog key={props.key} dispatch={props.dispatch} themeId={props.themeId} {...customProps}/>;
|
||||
return <EditFolderDialog key={props.key} dispatch={props.dispatch} dialogContentMaxSize={props.dialogContentMaxSize} themeId={props.themeId} {...customProps}/>;
|
||||
},
|
||||
},
|
||||
|
||||
tableEditor: {
|
||||
render: (props: RegisteredDialogProps, customProps: any) => {
|
||||
return <TableEditorDialog key={props.key} dispatch={props.dispatch} dialogContentMaxSize={props.dialogContentMaxSize} themeId={props.themeId} {...customProps}/>;
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -195,10 +204,12 @@ class RootComponent extends React.Component<Props, any> {
|
||||
for (const dialog of props.dialogs) {
|
||||
const md = registeredDialogs[dialog.name];
|
||||
if (!md) throw new Error(`Unknown dialog: ${dialog.name}`);
|
||||
|
||||
output.push(md.render({
|
||||
key: dialog.name,
|
||||
themeId: props.themeId,
|
||||
dispatch: props.dispatch,
|
||||
dialogContentMaxSize: props.dialogContentMaxSize,
|
||||
}, dialog.props));
|
||||
}
|
||||
return output;
|
||||
@@ -245,6 +256,11 @@ const mapStateToProps = (state: AppState) => {
|
||||
themeId: state.settings.theme,
|
||||
needApiAuth: state.needApiAuth,
|
||||
dialogs: state.dialogs,
|
||||
dialogContentMaxSize: {
|
||||
// Minus padding, margins and dialog header and button bar.
|
||||
width: state.windowContentSize.width - 36 * 2,
|
||||
height: state.windowContentSize.height - 36 * 2 - 28 - 30 - 20,
|
||||
},
|
||||
profileConfigCurrentProfileId: state.profileConfig.currentProfileId,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -119,7 +119,9 @@ function SearchBar(props: Props) {
|
||||
}, [onExitSearch]);
|
||||
|
||||
const onSearchButtonClick = useCallback(() => {
|
||||
if (props.isFocused || searchStarted) {
|
||||
console.info('isFocused', props.isFocused);
|
||||
|
||||
if (props.isFocused) {
|
||||
void onExitSearch();
|
||||
} else {
|
||||
setSearchStarted(true);
|
||||
@@ -129,7 +131,7 @@ function SearchBar(props: Props) {
|
||||
field: 'globalSearch',
|
||||
});
|
||||
}
|
||||
}, [onExitSearch, props.isFocused, searchStarted]);
|
||||
}, [onExitSearch, props.isFocused]);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.notesParentType !== 'Search') {
|
||||
|
||||
101
packages/app-desktop/gui/TableEditorDialog/Dialog.tsx
Normal file
101
packages/app-desktop/gui/TableEditorDialog/Dialog.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import * as React from 'react';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { _ } from '@joplin/lib/locale';
|
||||
import DialogButtonRow, { ClickEvent } from '../DialogButtonRow';
|
||||
import Dialog from '../Dialog';
|
||||
import DialogTitle from '../DialogTitle';
|
||||
import { parseMarkdownTable } from '../../../lib/markdownUtils';
|
||||
import { Size } from '../ResizableLayout/utils/types';
|
||||
|
||||
interface Props {
|
||||
themeId: number;
|
||||
dispatch: Function;
|
||||
markdownTable: string;
|
||||
dialogContentMaxSize: Size;
|
||||
}
|
||||
|
||||
const markdownTableToObject = (markdownTable: string): any => {
|
||||
const table = parseMarkdownTable(markdownTable);
|
||||
|
||||
return {
|
||||
columns: table.headers.map(h => {
|
||||
return {
|
||||
title: h.label,
|
||||
field: h.name,
|
||||
hozAlign: h.justify,
|
||||
editor: 'input',
|
||||
};
|
||||
}),
|
||||
|
||||
data: table.rows.map(row => {
|
||||
return {
|
||||
...row,
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
export default function(props: Props) {
|
||||
const elementId = `tabulator_${Math.floor(Math.random() * 1000000)}`;
|
||||
|
||||
const onClose = useCallback(() => {
|
||||
props.dispatch({
|
||||
type: 'DIALOG_CLOSE',
|
||||
name: 'tableEditor',
|
||||
});
|
||||
}, [props.dispatch]);
|
||||
|
||||
const onButtonRowClick = useCallback(async (event: ClickEvent) => {
|
||||
if (event.buttonName === 'cancel') {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.buttonName === 'ok') {
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
}, [onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
const table = markdownTableToObject(props.markdownTable);
|
||||
const Tabulator = (window as any).Tabulator;
|
||||
|
||||
// TODO: probably doesn't need to be called every time
|
||||
// TODO: Load CSS/JS dynamically?
|
||||
// TODO: Clean up on exit
|
||||
Tabulator.extendModule('edit', 'editors', {});
|
||||
|
||||
new Tabulator(`#${elementId}`, {
|
||||
...table,
|
||||
height: props.dialogContentMaxSize.height,
|
||||
});
|
||||
}, []);
|
||||
|
||||
function renderContent() {
|
||||
return (
|
||||
<div className="dialog-content">
|
||||
<div id={elementId}></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderDialogWrapper() {
|
||||
return (
|
||||
<div className="dialog-root">
|
||||
<DialogTitle title={_('Edit table')}/>
|
||||
{renderContent()}
|
||||
<DialogButtonRow
|
||||
themeId={props.themeId}
|
||||
onClick={onButtonRowClick}
|
||||
okButtonLabel={_('Save')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog onClose={onClose} renderContent={renderDialogWrapper}/>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,10 @@
|
||||
uses 'eval'.
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline' 'unsafe-eval'">
|
||||
-->
|
||||
|
||||
<!--
|
||||
To add files below, then need to be in the "vendor" directory. To make this happen, use copyApplicationAssets.js
|
||||
-->
|
||||
<title>Joplin</title>
|
||||
<link rel="stylesheet" href="style.min.css">
|
||||
<link rel="stylesheet" href="style/icons/style.css">
|
||||
@@ -15,6 +19,9 @@
|
||||
<link rel="stylesheet" href="vendor/lib/smalltalk/css/smalltalk.css">
|
||||
<link rel="stylesheet" href="vendor/lib/roboto-fontface/css/roboto/roboto-fontface.css">
|
||||
<link rel="stylesheet" href="vendor/lib/codemirror/lib/codemirror.css">
|
||||
<link rel="stylesheet" href="vendor/lib/tabulator-tables/dist/css/tabulator.min.css">
|
||||
|
||||
<script type="text/javascript" src="vendor/lib/tabulator-tables/dist/js/tabulator.min.js"></script>
|
||||
|
||||
<style>
|
||||
.smalltalk {
|
||||
|
||||
@@ -26,7 +26,7 @@ const shim = require('@joplin/lib/shim').default;
|
||||
const { shimInit } = require('@joplin/lib/shim-init-node.js');
|
||||
const bridge = require('@electron/remote').require('./bridge').default;
|
||||
const EncryptionService = require('@joplin/lib/services/e2ee/EncryptionService').default;
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
|
||||
const React = require('react');
|
||||
const nodeSqlite = require('sqlite3');
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@joplin/app-desktop",
|
||||
"version": "2.9.1",
|
||||
"version": "2.8.8",
|
||||
"description": "Joplin for Desktop",
|
||||
"main": "main.js",
|
||||
"private": true,
|
||||
@@ -105,7 +105,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/laurent22/joplin#readme",
|
||||
"devDependencies": {
|
||||
"@joplin/tools": "~2.9",
|
||||
"@joplin/tools": "~2.8",
|
||||
"@testing-library/react-hooks": "^3.4.2",
|
||||
"@types/jest": "^26.0.15",
|
||||
"@types/node": "^14.14.6",
|
||||
@@ -137,8 +137,8 @@
|
||||
"@electron/remote": "^2.0.1",
|
||||
"@fortawesome/fontawesome-free": "^5.13.0",
|
||||
"@joeattardi/emoji-button": "^4.6.0",
|
||||
"@joplin/lib": "~2.9",
|
||||
"@joplin/renderer": "~2.9",
|
||||
"@joplin/lib": "~2.8",
|
||||
"@joplin/renderer": "~2.8",
|
||||
"async-mutex": "^0.1.3",
|
||||
"codemirror": "^5.56.0",
|
||||
"color": "^3.1.2",
|
||||
@@ -174,6 +174,7 @@
|
||||
"styled-components": "5.1.1",
|
||||
"styled-system": "5.1.5",
|
||||
"taboverride": "^4.0.3",
|
||||
"tabulator-tables": "^5.1.4",
|
||||
"tinymce": "^5.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import bridge from '../bridge';
|
||||
import { Implementation as WindowImplementation } from '@joplin/lib/services/plugins/api/JoplinWindow';
|
||||
import { injectCustomStyles } from '@joplin/lib/CssUtils';
|
||||
import { VersionInfo } from '@joplin/lib/services/plugins/api/types';
|
||||
import Setting from '@joplin/lib/models/Setting';
|
||||
import { reg } from '@joplin/lib/registry';
|
||||
import BasePlatformImplementation, { Joplin } from '@joplin/lib/services/plugins/BasePlatformImplementation';
|
||||
const { clipboard, nativeImage } = require('electron');
|
||||
const packageInfo = require('../../packageInfo');
|
||||
|
||||
interface JoplinViewsDialogs {
|
||||
showMessageBox(message: string): Promise<number>;
|
||||
}
|
||||
|
||||
interface JoplinViews {
|
||||
dialogs: JoplinViewsDialogs;
|
||||
}
|
||||
|
||||
interface Joplin {
|
||||
views: JoplinViews;
|
||||
}
|
||||
|
||||
interface Components {
|
||||
[key: string]: any;
|
||||
@@ -15,7 +22,7 @@ interface Components {
|
||||
// PlatformImplementation provides access to platform specific dependencies,
|
||||
// such as the clipboard, message dialog, etc. It allows having the same plugin
|
||||
// API for all platforms, but with different implementations.
|
||||
export default class PlatformImplementation extends BasePlatformImplementation {
|
||||
export default class PlatformImplementation {
|
||||
|
||||
private static instance_: PlatformImplementation;
|
||||
private joplin_: Joplin;
|
||||
@@ -26,14 +33,6 @@ export default class PlatformImplementation extends BasePlatformImplementation {
|
||||
return this.instance_;
|
||||
}
|
||||
|
||||
public get versionInfo(): VersionInfo {
|
||||
return {
|
||||
version: packageInfo.version,
|
||||
syncVersion: Setting.value('syncVersion'),
|
||||
profileVersion: reg.db().version(),
|
||||
};
|
||||
}
|
||||
|
||||
public get clipboard() {
|
||||
return clipboard;
|
||||
}
|
||||
@@ -49,8 +48,6 @@ export default class PlatformImplementation extends BasePlatformImplementation {
|
||||
}
|
||||
|
||||
public constructor() {
|
||||
super();
|
||||
|
||||
this.components_ = {};
|
||||
|
||||
this.joplin_ = {
|
||||
|
||||
@@ -83,6 +83,8 @@ async function main() {
|
||||
'codemirror/addon/dialog/dialog.css',
|
||||
'@joeattardi/emoji-button/dist/index.js',
|
||||
'mark.js/dist/mark.min.js',
|
||||
'tabulator-tables/dist/css/tabulator.min.css',
|
||||
'tabulator-tables/dist/js/tabulator.min.js',
|
||||
{
|
||||
src: resolve(__dirname, '../../lib/services/plugins/sandboxProxy.js'),
|
||||
dest: `${buildLibDir}/@joplin/lib/services/plugins/sandboxProxy.js`,
|
||||
|
||||
2
packages/app-mobile/.gitignore
vendored
2
packages/app-mobile/.gitignore
vendored
@@ -65,5 +65,3 @@ lib/rnInjectedJs/
|
||||
dist/
|
||||
components/NoteEditor/CodeMirror.bundle.js
|
||||
components/NoteEditor/CodeMirror.bundle.min.js
|
||||
|
||||
utils/fs-driver-android.js
|
||||
|
||||
@@ -147,7 +147,7 @@ android {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 2097668
|
||||
versionName "2.9.0"
|
||||
versionName "2.8.1"
|
||||
ndk {
|
||||
abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
|
||||
}
|
||||
|
||||
@@ -38,10 +38,9 @@ class Dropdown extends React.Component {
|
||||
const listTop = Math.min(maxListTop, this.state.headerSize.y + this.state.headerSize.height);
|
||||
|
||||
const wrapperStyle = {
|
||||
width: this.state.headerSize.width,
|
||||
height: listHeight + 2, // +2 for the border (otherwise it makes the scrollbar appear)
|
||||
marginTop: listTop,
|
||||
marginLeft: this.state.headerSize.x,
|
||||
alignSelf: 'center',
|
||||
};
|
||||
|
||||
const itemListStyle = Object.assign({}, this.props.itemListStyle ? this.props.itemListStyle : {}, {
|
||||
@@ -87,6 +86,7 @@ class Dropdown extends React.Component {
|
||||
if (this.props.labelTransform && this.props.labelTransform === 'trim') headerLabel = headerLabel.trim();
|
||||
|
||||
const closeList = () => {
|
||||
if (this.props.onClose) this.props.onClose();
|
||||
this.setState({ listVisible: false });
|
||||
};
|
||||
|
||||
@@ -116,6 +116,7 @@ class Dropdown extends React.Component {
|
||||
onPress={() => {
|
||||
this.updateHeaderCoordinates();
|
||||
this.setState({ listVisible: true });
|
||||
if (this.props.onOpen) this.props.onOpen();
|
||||
}}
|
||||
>
|
||||
<Text ellipsizeMode="tail" numberOfLines={1} style={headerStyle}>
|
||||
|
||||
@@ -10,25 +10,17 @@
|
||||
// from NoteEditor.tsx.
|
||||
|
||||
import { EditorState, Extension } from '@codemirror/state';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { highlightSelectionMatches, search } from '@codemirror/search';
|
||||
import { defaultHighlightStyle, syntaxHighlighting, HighlightStyle } from '@codemirror/language';
|
||||
import { tags } from '@lezer/highlight';
|
||||
import { EditorView, drawSelection, highlightSpecialChars, ViewUpdate } from '@codemirror/view';
|
||||
import { undo, redo, history, undoDepth, redoDepth } from '@codemirror/commands';
|
||||
|
||||
import { keymap } from '@codemirror/view';
|
||||
import { indentOnInput } from '@codemirror/language';
|
||||
import { searchKeymap } from '@codemirror/search';
|
||||
import { historyKeymap, defaultKeymap } from '@codemirror/commands';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { defaultHighlightStyle, HighlightStyle, tags } from '@codemirror/highlight';
|
||||
import { undo, redo, history, undoDepth, redoDepth } from '@codemirror/history';
|
||||
|
||||
interface CodeMirrorResult {
|
||||
editor: EditorView;
|
||||
undo: Function;
|
||||
redo: Function;
|
||||
select(anchor: number, head: number): void;
|
||||
scrollSelectionIntoView(): void;
|
||||
insertText(text: string): void;
|
||||
select: (anchor: number, head: number)=> void;
|
||||
insertText: (text: string)=> void;
|
||||
}
|
||||
|
||||
function postMessage(name: string, data: any) {
|
||||
@@ -54,7 +46,7 @@ function logMessage(...msg: any[]) {
|
||||
// the app is running. It seems that what appears as ".ͼ1" in the CSS is the
|
||||
// equivalent of "&" in the theme object. So to target ".ͼ1.cm-focused", you'd
|
||||
// use '&.cm-focused' in the theme.
|
||||
const createTheme = (theme: any): Extension[] => {
|
||||
const createTheme = (theme: any): Extension => {
|
||||
const isDarkTheme = theme.appearance === 'dark';
|
||||
|
||||
const baseGlobalStyle: Record<string, string> = {
|
||||
@@ -99,7 +91,7 @@ const createTheme = (theme: any): Extension[] => {
|
||||
fontFamily: theme.fontFamily,
|
||||
};
|
||||
|
||||
const highlightingStyle = HighlightStyle.define([
|
||||
const syntaxHighlighting = HighlightStyle.define([
|
||||
{
|
||||
tag: tags.strong,
|
||||
fontWeight: 'bold',
|
||||
@@ -148,11 +140,7 @@ const createTheme = (theme: any): Extension[] => {
|
||||
return [
|
||||
baseTheme,
|
||||
appearanceTheme,
|
||||
syntaxHighlighting(highlightingStyle),
|
||||
|
||||
// If we haven't defined highlighting for tags, fall back
|
||||
// to the default.
|
||||
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
|
||||
syntaxHighlighting,
|
||||
];
|
||||
};
|
||||
|
||||
@@ -180,20 +168,15 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a
|
||||
|
||||
const editor = new EditorView({
|
||||
state: EditorState.create({
|
||||
// See https://github.com/codemirror/basic-setup/blob/main/src/codemirror.ts
|
||||
// for a sample configuration.
|
||||
extensions: [
|
||||
markdown(),
|
||||
...createTheme(theme),
|
||||
createTheme(theme),
|
||||
history(),
|
||||
search(),
|
||||
drawSelection(),
|
||||
highlightSpecialChars(),
|
||||
highlightSelectionMatches(),
|
||||
indentOnInput(),
|
||||
|
||||
EditorView.lineWrapping,
|
||||
EditorView.contentAttributes.of({ autocapitalize: 'sentence' }),
|
||||
defaultHighlightStyle.fallback,
|
||||
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
|
||||
if (viewUpdate.docChanged) {
|
||||
postMessage('onChange', { value: editor.state.doc.toString() });
|
||||
@@ -207,9 +190,6 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a
|
||||
postMessage('onSelectionChange', { selection: { start: selStart, end: selEnd } });
|
||||
}
|
||||
}),
|
||||
keymap.of([
|
||||
...defaultKeymap, ...historyKeymap, ...searchKeymap,
|
||||
]),
|
||||
],
|
||||
doc: initialText,
|
||||
}),
|
||||
@@ -232,11 +212,6 @@ export function initCodeMirror(parentElement: any, initialText: string, theme: a
|
||||
scrollIntoView: true,
|
||||
}));
|
||||
},
|
||||
scrollSelectionIntoView: () => {
|
||||
editor.dispatch(editor.state.update({
|
||||
scrollIntoView: true,
|
||||
}));
|
||||
},
|
||||
insertText: (text: string) => {
|
||||
editor.dispatch(editor.state.replaceSelection(text));
|
||||
},
|
||||
|
||||
@@ -266,16 +266,11 @@ function NoteEditor(props: Props, ref: any) {
|
||||
|
||||
cm = codeMirrorBundle.initCodeMirror(parentElement, initialText, theme);
|
||||
${setInitialSelectionJS}
|
||||
|
||||
// Fixes https://github.com/laurent22/joplin/issues/5949
|
||||
window.onresize = () => {
|
||||
cm.scrollSelectionIntoView();
|
||||
};
|
||||
} catch (e) {
|
||||
window.ReactNativeWebView.postMessage("error:" + e.message + ": " + JSON.stringify(e))
|
||||
} finally {
|
||||
true;
|
||||
}
|
||||
|
||||
true;
|
||||
`;
|
||||
|
||||
const css = useCss(props.themeId);
|
||||
|
||||
@@ -60,31 +60,12 @@ class ActionButtonComponent extends React.Component {
|
||||
|
||||
renderIconMultiStates() {
|
||||
const button = this.props.buttons[this.state.buttonIndex];
|
||||
|
||||
return <Icon
|
||||
name={button.icon}
|
||||
style={styles.actionButtonIcon}
|
||||
accessibilityLabel={button.title}
|
||||
/>;
|
||||
return <Icon name={button.icon} style={styles.actionButtonIcon} />;
|
||||
}
|
||||
|
||||
renderIcon() {
|
||||
const mainButton = this.props.mainButton ? this.props.mainButton : {};
|
||||
const iconName = mainButton.icon ?? 'md-add';
|
||||
|
||||
// Icons don't have alt text by default. We need to add it:
|
||||
const iconTitle = mainButton.title ?? _('Add new');
|
||||
|
||||
// TODO: If the button toggles a sub-menu, state whether the submenu is open
|
||||
// or closed.
|
||||
|
||||
return (
|
||||
<Icon
|
||||
name={iconName}
|
||||
style={styles.actionButtonIcon}
|
||||
accessibilityLabel={iconTitle}
|
||||
/>
|
||||
);
|
||||
return mainButton.icon ? <Icon name={mainButton.icon} style={styles.actionButtonIcon} /> : <Icon name="md-add" style={styles.actionButtonIcon} />;
|
||||
}
|
||||
|
||||
render() {
|
||||
@@ -118,14 +99,8 @@ class ActionButtonComponent extends React.Component {
|
||||
const buttonTitle = button.title ? button.title : '';
|
||||
const key = `${buttonTitle.replace(/\s/g, '_')}_${button.icon}`;
|
||||
buttonComps.push(
|
||||
// TODO: By default, ReactNativeActionButton also adds a title, which is focusable
|
||||
// by the screen reader. As such, each item currently is double-focusable
|
||||
<ReactNativeActionButton.Item key={key} buttonColor={button.color} title={buttonTitle} onPress={button.onPress}>
|
||||
<Icon
|
||||
name={button.icon}
|
||||
style={styles.actionButtonIcon}
|
||||
accessibilityLabel={buttonTitle}
|
||||
/>
|
||||
<Icon name={button.icon} style={styles.actionButtonIcon} />
|
||||
</ReactNativeActionButton.Item>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,14 +61,7 @@ class Checkbox extends Component {
|
||||
// if (style.display) thStyle.display = style.display;
|
||||
|
||||
return (
|
||||
<TouchableHighlight
|
||||
onPress={() => this.onPress()}
|
||||
style={thStyle}
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityState={{
|
||||
checked: this.state.checked,
|
||||
}}
|
||||
accessibilityLabel={this.props.accessibilityLabel ?? ''}>
|
||||
<TouchableHighlight onPress={() => this.onPress()} style={thStyle}>
|
||||
<Icon name={iconName} style={checkboxIconStyle} />
|
||||
</TouchableHighlight>
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ const { Checkbox } = require('./checkbox.js');
|
||||
const Note = require('@joplin/lib/models/Note').default;
|
||||
const time = require('@joplin/lib/time').default;
|
||||
const { themeStyle } = require('./global-style.js');
|
||||
const { _ } = require('@joplin/lib/locale');
|
||||
|
||||
class NoteItemComponent extends Component {
|
||||
constructor() {
|
||||
@@ -129,20 +128,13 @@ class NoteItemComponent extends Component {
|
||||
|
||||
const selectionWrapperStyle = isSelected ? this.styles().selectionWrapperSelected : this.styles().selectionWrapper;
|
||||
|
||||
const noteTitle = Note.displayTitle(note);
|
||||
|
||||
return (
|
||||
<TouchableOpacity onPress={() => this.onPress()} onLongPress={() => this.onLongPress()} activeOpacity={0.5}>
|
||||
<View style={selectionWrapperStyle}>
|
||||
<View style={opacityStyle}>
|
||||
<View style={listItemStyle}>
|
||||
<Checkbox
|
||||
style={checkboxStyle}
|
||||
checked={checkboxChecked}
|
||||
onChange={checked => this.todoCheckbox_change(checked)}
|
||||
accessibilityLabel={_('to-do: %s', noteTitle)}
|
||||
/>
|
||||
<Text style={listItemTextStyle}>{noteTitle}</Text>
|
||||
<Checkbox style={checkboxStyle} checked={checkboxChecked} onChange={checked => this.todoCheckbox_change(checked)} />
|
||||
<Text style={listItemTextStyle}>{Note.displayTitle(note)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -29,8 +29,10 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
constructor() {
|
||||
super();
|
||||
this.styles_ = {};
|
||||
this.state = { showUndoRedoButtons: true };
|
||||
}
|
||||
|
||||
|
||||
styles() {
|
||||
const themeId = Setting.value('theme');
|
||||
if (this.styles_[themeId]) return this.styles_[themeId];
|
||||
@@ -225,12 +227,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
render() {
|
||||
function sideMenuButton(styles, onPress) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
|
||||
accessibilityLabel={_('Sidebar')}
|
||||
accessibilityHint={_('Show/hide the sidebar')}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress}>
|
||||
<View style={styles.sideMenuButton}>
|
||||
<Icon name="md-menu" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -240,18 +237,9 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function backButton(styles, onPress, disabled) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
disabled={disabled}
|
||||
|
||||
accessibilityLabel={_('Back')}
|
||||
accessibilityHint={_('Navigate to the previous view')}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress} disabled={disabled}>
|
||||
<View style={disabled ? styles.backButtonDisabled : styles.backButton}>
|
||||
<Icon
|
||||
name="md-arrow-back"
|
||||
style={styles.topIcon}
|
||||
/>
|
||||
<Icon name="md-arrow-back" style={styles.topIcon} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
@@ -263,31 +251,20 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
const icon = disabled ? <Icon name="md-checkmark" style={styles.savedButtonIcon} /> : <Image style={styles.saveButtonIcon} source={require('./SaveIcon.png')} />;
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
disabled={disabled}
|
||||
style={{ padding: 0 }}
|
||||
|
||||
accessibilityLabel={_('Save changes')}
|
||||
accessibilityHint={disabled ? _('Any changes have been saved') : null}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress} disabled={disabled} style={{ padding: 0 }}>
|
||||
<View style={disabled ? styles.saveButtonDisabled : styles.saveButton}>{icon}</View>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
}
|
||||
|
||||
const renderTopButton = (options) => {
|
||||
if (!options.visible) return null;
|
||||
if (!options.visible || !this.state.showUndoRedoButtons) return null;
|
||||
|
||||
const icon = <Icon name={options.iconName} style={this.styles().topIcon} />;
|
||||
const viewStyle = options.disabled ? this.styles().iconButtonDisabled : this.styles().iconButton;
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={options.onPress}
|
||||
style={{ padding: 0 }}
|
||||
disabled={!!options.disabled}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={options.onPress} style={{ padding: 0 }} disabled={!!options.disabled}>
|
||||
<View style={viewStyle}>{icon}</View>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
@@ -312,11 +289,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function selectAllButton(styles, onPress) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
|
||||
accessibilityLabel={_('Select all')}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress}>
|
||||
<View style={styles.iconButton}>
|
||||
<Icon name="md-checkmark-circle-outline" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -326,11 +299,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function searchButton(styles, onPress) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
|
||||
accessibilityLabel={_('Search')}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress}>
|
||||
<View style={styles.iconButton}>
|
||||
<Icon name="md-search" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -340,15 +309,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function deleteButton(styles, onPress, disabled) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
disabled={disabled}
|
||||
|
||||
accessibilityLabel={_('Delete')}
|
||||
accessibilityHint={
|
||||
disabled ? null : _('Delete selected notes')
|
||||
}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress} disabled={disabled}>
|
||||
<View style={disabled ? styles.iconButtonDisabled : styles.iconButton}>
|
||||
<Icon name="md-trash" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -358,15 +319,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function duplicateButton(styles, onPress, disabled) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
disabled={disabled}
|
||||
|
||||
accessibilityLabel={_('Duplicate')}
|
||||
accessibilityHint={
|
||||
disabled ? null : _('Duplicate selected notes')
|
||||
}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress} disabled={disabled}>
|
||||
<View style={disabled ? styles.iconButtonDisabled : styles.iconButton}>
|
||||
<Icon name="md-copy" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -376,11 +329,7 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
|
||||
function sortButton(styles, onPress) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={onPress}
|
||||
|
||||
accessibilityLabel={_('Sort notes by')}
|
||||
accessibilityRole="button">
|
||||
<TouchableOpacity onPress={onPress}>
|
||||
<View style={styles.iconButton}>
|
||||
<Icon name="filter-outline" style={styles.topIcon} />
|
||||
</View>
|
||||
@@ -475,6 +424,16 @@ class ScreenHeaderComponent extends React.PureComponent {
|
||||
color: theme.color,
|
||||
fontSize: theme.fontSize,
|
||||
}}
|
||||
onOpen={() => {
|
||||
this.setState({
|
||||
showUndoRedoButtons: false,
|
||||
});
|
||||
}}
|
||||
onClose={() => {
|
||||
this.setState({
|
||||
showUndoRedoButtons: true,
|
||||
});
|
||||
}}
|
||||
onValueChange={async (folderId, itemIndex) => {
|
||||
// If onValueChange is specified, use this as a callback, otherwise do the default
|
||||
// which is to take the selectedNoteIds from the state and move them to the
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
|
||||
import Slider from '@react-native-community/slider';
|
||||
const React = require('react');
|
||||
const { Platform, Linking, View, Switch, StyleSheet, ScrollView, Text, Button, TouchableOpacity, TextInput, Alert, PermissionsAndroid, TouchableNativeFeedback } = require('react-native');
|
||||
const { Platform, Linking, View, Switch, StyleSheet, ScrollView, Text, Button, TouchableOpacity, TextInput, Alert, PermissionsAndroid } = require('react-native');
|
||||
import Setting, { AppType } from '@joplin/lib/models/Setting';
|
||||
import NavService from '@joplin/lib/services/NavService';
|
||||
import ReportService from '@joplin/lib/services/ReportService';
|
||||
@@ -21,7 +20,6 @@ const { Dropdown } = require('../Dropdown.js');
|
||||
const { themeStyle } = require('../global-style.js');
|
||||
const shared = require('@joplin/lib/components/shared/config-shared.js');
|
||||
import SyncTargetRegistry from '@joplin/lib/SyncTargetRegistry';
|
||||
import { openDocumentTree } from '@joplin/react-native-saf-x';
|
||||
const RNFS = require('react-native-fs');
|
||||
|
||||
class ConfigScreenComponent extends BaseScreenComponent {
|
||||
@@ -39,27 +37,12 @@ class ConfigScreenComponent extends BaseScreenComponent {
|
||||
creatingReport: false,
|
||||
profileExportStatus: 'idle',
|
||||
profileExportPath: '',
|
||||
fileSystemSyncPath: Setting.value('sync.2.path'),
|
||||
};
|
||||
|
||||
this.scrollViewRef_ = React.createRef();
|
||||
|
||||
shared.init(this, reg);
|
||||
|
||||
this.selectDirectoryButtonPress = async () => {
|
||||
try {
|
||||
const doc = await openDocumentTree(true);
|
||||
if (doc?.uri) {
|
||||
this.setState({ fileSystemSyncPath: doc.uri });
|
||||
shared.updateSettingValue(this, 'sync.2.path', doc.uri);
|
||||
} else {
|
||||
throw new Error('User cancelled operation');
|
||||
}
|
||||
} catch (e) {
|
||||
reg.logger().info('Didn\'t pick sync dir: ', e);
|
||||
}
|
||||
};
|
||||
|
||||
this.checkSyncConfig_ = async () => {
|
||||
// to ignore TLS erros we need to chage the global state of the app, if the check fails we need to restore the original state
|
||||
// this call sets the new value and returns the previous one which we can use later to revert the change
|
||||
@@ -75,15 +58,8 @@ class ConfigScreenComponent extends BaseScreenComponent {
|
||||
};
|
||||
|
||||
this.saveButton_press = async () => {
|
||||
if (this.state.changedSettingKeys.includes('sync.target') && this.state.settings['sync.target'] === SyncTargetRegistry.nameToId('filesystem')) {
|
||||
if (Platform.OS === 'android') {
|
||||
if (Platform.Version < 29) {
|
||||
if (!(await this.checkFilesystemPermission())) {
|
||||
Alert.alert(_('Warning'), _('In order to use file system synchronisation your permission to write to external storage is required.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.state.changedSettingKeys.includes('sync.target') && this.state.settings['sync.target'] === SyncTargetRegistry.nameToId('filesystem') && !(await this.checkFilesystemPermission())) {
|
||||
Alert.alert(_('Warning'), _('In order to use file system synchronisation your permission to write to external storage is required.'));
|
||||
// Save settings anyway, even if permission has not been granted
|
||||
}
|
||||
|
||||
@@ -500,20 +476,6 @@ class ConfigScreenComponent extends BaseScreenComponent {
|
||||
</View>
|
||||
);
|
||||
} else if (md.type == Setting.TYPE_STRING) {
|
||||
if (md.key === 'sync.2.path' && Platform.OS === 'android' && Platform.Version > 28) {
|
||||
return (
|
||||
<TouchableNativeFeedback key={key} onPress={this.selectDirectoryButtonPress} style={this.styles().settingContainer}>
|
||||
<View style={this.styles().settingContainer}>
|
||||
<Text key="label" style={this.styles().settingText}>
|
||||
{md.label()}
|
||||
</Text>
|
||||
<Text style={this.styles().settingControl}>
|
||||
{this.state.fileSystemSyncPath}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableNativeFeedback>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View key={key} style={this.styles().settingContainer}>
|
||||
<Text key="label" style={this.styles().settingText}>
|
||||
|
||||
@@ -161,8 +161,8 @@ class NoteScreenComponent extends BaseScreenComponent {
|
||||
|
||||
this.onJoplinLinkClick_ = async (msg: string) => {
|
||||
try {
|
||||
const resourceUrlInfo = urlUtils.parseResourceUrl(msg);
|
||||
if (resourceUrlInfo) {
|
||||
if (msg.indexOf('joplin://') === 0) {
|
||||
const resourceUrlInfo = urlUtils.parseResourceUrl(msg);
|
||||
const itemId = resourceUrlInfo.itemId;
|
||||
const item = await BaseItem.loadItemById(itemId);
|
||||
if (!item) throw new Error(_('No item with ID %s', itemId));
|
||||
|
||||
@@ -250,8 +250,7 @@ class SideMenuContentComponent extends Component {
|
||||
|
||||
let iconWrapper = null;
|
||||
|
||||
const collapsed = this.props.collapsedFolderIds.indexOf(folder.id) >= 0;
|
||||
const iconName = collapsed ? 'chevron-down' : 'chevron-up';
|
||||
const iconName = this.props.collapsedFolderIds.indexOf(folder.id) >= 0 ? 'chevron-down' : 'chevron-up';
|
||||
const iconComp = <Icon name={iconName} style={this.styles().folderIcon} />;
|
||||
|
||||
iconWrapper = !hasChildren ? null : (
|
||||
@@ -261,9 +260,6 @@ class SideMenuContentComponent extends Component {
|
||||
onPress={() => {
|
||||
if (hasChildren) this.folder_togglePress(folder);
|
||||
}}
|
||||
|
||||
accessibilityLabel={collapsed ? _('Expand folder') : _('Collapse folder')}
|
||||
accessibilityRole="togglebutton"
|
||||
>
|
||||
{iconComp}
|
||||
</TouchableOpacity>
|
||||
|
||||
@@ -498,7 +498,7 @@
|
||||
INFOPLIST_FILE = Joplin/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
MARKETING_VERSION = 12.9.0;
|
||||
MARKETING_VERSION = 12.8.1;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
@@ -526,7 +526,7 @@
|
||||
INFOPLIST_FILE = Joplin/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
MARKETING_VERSION = 12.9.0;
|
||||
MARKETING_VERSION = 12.8.1;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
@@ -674,7 +674,7 @@
|
||||
INFOPLIST_FILE = ShareExtension/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
MARKETING_VERSION = 12.9.0;
|
||||
MARKETING_VERSION = 12.8.1;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.cozic.joplin.ShareExtension;
|
||||
@@ -705,7 +705,7 @@
|
||||
INFOPLIST_FILE = ShareExtension/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
MARKETING_VERSION = 12.9.0;
|
||||
MARKETING_VERSION = 12.8.1;
|
||||
MTL_FAST_MATH = YES;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.cozic.joplin.ShareExtension;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
|
||||
@@ -44,7 +44,6 @@ module.exports = {
|
||||
'@joplin/tools': path.resolve(__dirname, '../tools/'),
|
||||
'@joplin/fork-htmlparser2': path.resolve(__dirname, '../fork-htmlparser2/'),
|
||||
'@joplin/fork-uslug': path.resolve(__dirname, '../fork-uslug/'),
|
||||
'@joplin/react-native-saf-x': path.resolve(__dirname, '../react-native-saf-x/'),
|
||||
},
|
||||
{
|
||||
get: (target, name) => {
|
||||
@@ -63,6 +62,5 @@ module.exports = {
|
||||
path.resolve(__dirname, '../tools'),
|
||||
path.resolve(__dirname, '../fork-htmlparser2'),
|
||||
path.resolve(__dirname, '../fork-uslug'),
|
||||
path.resolve(__dirname, '../react-native-saf-x'),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
"name": "@joplin/app-mobile",
|
||||
"description": "Joplin for Mobile",
|
||||
"license": "MIT",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "react-native start --reset-cache",
|
||||
"android": "react-native run-android",
|
||||
"build": "gulp build",
|
||||
"tsc": "tsc --project tsconfig.json",
|
||||
"watch": "tsc --watch --preserveWatchOutput --project tsconfig.json",
|
||||
@@ -16,9 +15,8 @@
|
||||
"postinstall": "jetify && yarn run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@joplin/lib": "~2.9",
|
||||
"@joplin/react-native-saf-x": "~2.9",
|
||||
"@joplin/renderer": "~2.9",
|
||||
"@joplin/lib": "~2.8",
|
||||
"@joplin/renderer": "~2.8",
|
||||
"@react-native-community/clipboard": "^1.5.0",
|
||||
"@react-native-community/datetimepicker": "^3.0.3",
|
||||
"@react-native-community/geolocation": "^2.0.2",
|
||||
@@ -72,14 +70,12 @@
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.12.9",
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@codemirror/commands": "^6.0.0",
|
||||
"@codemirror/lang-markdown": "^6.0.0",
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/search": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.0.0",
|
||||
"@joplin/tools": "~2.9",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@codemirror/highlight": "^0.18.4",
|
||||
"@codemirror/history": "^0.18.1",
|
||||
"@codemirror/lang-markdown": "^0.18.4",
|
||||
"@codemirror/state": "^0.18.7",
|
||||
"@codemirror/view": "^0.18.19",
|
||||
"@joplin/tools": "~2.8",
|
||||
"@rollup/plugin-node-resolve": "^13.0.0",
|
||||
"@rollup/plugin-typescript": "^8.2.1",
|
||||
"@types/node": "^14.14.6",
|
||||
|
||||
@@ -70,7 +70,7 @@ const { SideMenuContentNote } = require('./components/side-menu-content-note.js'
|
||||
const { DatabaseDriverReactNative } = require('./utils/database-driver-react-native');
|
||||
import { reg } from '@joplin/lib/registry';
|
||||
const { defaultState } = require('@joplin/lib/reducer');
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js');
|
||||
import ResourceFetcher from '@joplin/lib/services/ResourceFetcher';
|
||||
import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine';
|
||||
const WelcomeUtils = require('@joplin/lib/WelcomeUtils');
|
||||
@@ -872,8 +872,7 @@ class AppComponent extends React.Component {
|
||||
Config: { screen: ConfigScreen },
|
||||
};
|
||||
|
||||
// const statusBarStyle = theme.appearance === 'light-content';
|
||||
const statusBarStyle = 'light-content';
|
||||
const statusBarStyle = theme.appearance === 'light' ? 'dark-content' : 'light-content';
|
||||
|
||||
return (
|
||||
<View style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
|
||||
@@ -890,8 +889,7 @@ class AppComponent extends React.Component {
|
||||
}}
|
||||
>
|
||||
<StatusBar barStyle={statusBarStyle} />
|
||||
<MenuContext style={{ flex: 1 }}>
|
||||
<SafeAreaView style={{ flex: 0, backgroundColor: theme.backgroundColor2 }}/>
|
||||
<MenuContext style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
|
||||
<SafeAreaView style={{ flex: 1 }}>
|
||||
<View style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
|
||||
<AppNav screens={appNavInit} />
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import FsDriverBase, { ReadDirStatsOptions } from '@joplin/lib/fs-driver-base';
|
||||
import FsDriverBase from '@joplin/lib/fs-driver-base';
|
||||
const RNFetchBlob = require('rn-fetch-blob').default;
|
||||
const RNFS = require('react-native-fs');
|
||||
import RNSAF, { Encoding, DocumentFileDetail } from '@joplin/react-native-saf-x';
|
||||
|
||||
const ANDROID_URI_PREFIX = 'content://';
|
||||
|
||||
function isScopedUri(path: string) {
|
||||
return path.includes(ANDROID_URI_PREFIX);
|
||||
}
|
||||
|
||||
export default class FsDriverRN extends FsDriverBase {
|
||||
public appendFileSync() {
|
||||
@@ -16,17 +9,11 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
|
||||
// Encoding can be either "utf8" or "base64"
|
||||
public appendFile(path: string, content: any, encoding = 'base64') {
|
||||
if (isScopedUri(path)) {
|
||||
return RNSAF.writeFile(path, content, { encoding: encoding as Encoding, append: true });
|
||||
}
|
||||
return RNFS.appendFile(path, content, encoding);
|
||||
}
|
||||
|
||||
// Encoding can be either "utf8" or "base64"
|
||||
public writeFile(path: string, content: any, encoding = 'base64') {
|
||||
if (isScopedUri(path)) {
|
||||
return RNSAF.writeFile(path, content, { encoding: encoding as Encoding });
|
||||
}
|
||||
// We need to use rn-fetch-blob here due to this bug:
|
||||
// https://github.com/itinance/react-native-fs/issues/700
|
||||
return RNFetchBlob.fs.writeFile(path, content, encoding);
|
||||
@@ -39,105 +26,52 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
|
||||
// Returns a format compatible with Node.js format
|
||||
private rnfsStatToStd_(stat: any, path: string) {
|
||||
let birthtime;
|
||||
const mtime = stat.lastModified ? new Date(stat.lastModified) : stat.mtime;
|
||||
if (stat.lastModified) {
|
||||
birthtime = new Date(stat.lastModified);
|
||||
} else if (stat.ctime) {
|
||||
// Confusingly, "ctime" normally means "change time" but here it's used as "creation time". Also sometimes it is null
|
||||
birthtime = stat.ctime;
|
||||
} else {
|
||||
birthtime = stat.mtime;
|
||||
}
|
||||
return {
|
||||
birthtime,
|
||||
mtime,
|
||||
isDirectory: () => stat.type ? stat.type === 'directory' : stat.isDirectory(),
|
||||
birthtime: stat.ctime ? stat.ctime : stat.mtime, // Confusingly, "ctime" normally means "change time" but here it's used as "creation time". Also sometimes it is null
|
||||
mtime: stat.mtime,
|
||||
isDirectory: () => stat.isDirectory(),
|
||||
path: path,
|
||||
size: stat.size,
|
||||
};
|
||||
}
|
||||
|
||||
public async isDirectory(path: string): Promise<boolean> {
|
||||
return (await this.stat(path)).isDirectory();
|
||||
}
|
||||
|
||||
public async readDirStats(path: string, options: any = null) {
|
||||
if (!options) options = {};
|
||||
if (!('recursive' in options)) options.recursive = false;
|
||||
|
||||
const isScoped = isScopedUri(path);
|
||||
|
||||
let stats = [];
|
||||
let items = [];
|
||||
try {
|
||||
if (isScoped) {
|
||||
stats = await RNSAF.listFiles(path);
|
||||
} else {
|
||||
stats = await RNFS.readDir(path);
|
||||
}
|
||||
items = await RNFS.readDir(path);
|
||||
} catch (error) {
|
||||
throw new Error(`Could not read directory: ${path}: ${error.message}`);
|
||||
}
|
||||
|
||||
let output: any[] = [];
|
||||
for (let i = 0; i < stats.length; i++) {
|
||||
const stat = stats[i];
|
||||
const relativePath = (isScoped ? stat.uri : stat.path).substr(path.length + 1);
|
||||
output.push(this.rnfsStatToStd_(stat, relativePath));
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const relativePath = item.path.substr(path.length + 1);
|
||||
output.push(this.rnfsStatToStd_(item, relativePath));
|
||||
|
||||
if (isScoped) {
|
||||
output = await this.readUriDirStatsHandleRecursion_(stat, output, options);
|
||||
} else {
|
||||
output = await this.readDirStatsHandleRecursion_(path, stat, output, options);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
protected async readUriDirStatsHandleRecursion_(stat: DocumentFileDetail, output: DocumentFileDetail[], options: ReadDirStatsOptions) {
|
||||
if (options.recursive && stat.type === 'directory') {
|
||||
const subStats = await this.readDirStats(stat.uri, options);
|
||||
for (let j = 0; j < subStats.length; j++) {
|
||||
const subStat = subStats[j];
|
||||
output.push(subStat);
|
||||
}
|
||||
output = await this.readDirStatsHandleRecursion_(path, item, output, options);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public async move(source: string, dest: string) {
|
||||
if (isScopedUri(source) && isScopedUri(dest)) {
|
||||
await RNSAF.moveFile(source, dest, { replaceIfDestinationExists: true });
|
||||
} else if (isScopedUri(source) || isScopedUri(dest)) {
|
||||
throw new Error('Move between different storage types not supported');
|
||||
}
|
||||
return RNFS.moveFile(source, dest);
|
||||
}
|
||||
|
||||
public async exists(path: string) {
|
||||
if (isScopedUri(path)) {
|
||||
return RNSAF.exists(path);
|
||||
}
|
||||
return RNFS.exists(path);
|
||||
}
|
||||
|
||||
public async mkdir(path: string) {
|
||||
if (isScopedUri(path)) {
|
||||
await RNSAF.mkdir(path);
|
||||
return;
|
||||
}
|
||||
return RNFS.mkdir(path);
|
||||
}
|
||||
|
||||
public async stat(path: string) {
|
||||
try {
|
||||
let r;
|
||||
if (isScopedUri(path)) {
|
||||
r = await RNSAF.stat(path);
|
||||
} else {
|
||||
r = await RNFS.stat(path);
|
||||
}
|
||||
const r = await RNFS.stat(path);
|
||||
return this.rnfsStatToStd_(r, path);
|
||||
} catch (error) {
|
||||
if (error && ((error.message && error.message.indexOf('exist') >= 0) || error.code === 'ENOENT')) {
|
||||
@@ -159,9 +93,6 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
}
|
||||
|
||||
public async open(path: string, mode: number) {
|
||||
if (isScopedUri(path)) {
|
||||
throw new Error('open() not implemented in FsDriverAndroid');
|
||||
}
|
||||
// Note: RNFS.read() doesn't provide any way to know if the end of file has been reached.
|
||||
// So instead we stat the file here and use stat.size to manually check for end of file.
|
||||
// Bug: https://github.com/itinance/react-native-fs/issues/342
|
||||
@@ -181,9 +112,6 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
|
||||
public readFile(path: string, encoding = 'utf8') {
|
||||
if (encoding === 'Buffer') throw new Error('Raw buffer output not supported for FsDriverRN.readFile');
|
||||
if (isScopedUri(path)) {
|
||||
return RNSAF.readFile(path, { encoding: encoding as Encoding });
|
||||
}
|
||||
return RNFS.readFile(path, encoding);
|
||||
}
|
||||
|
||||
@@ -191,12 +119,6 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
public async copy(source: string, dest: string) {
|
||||
let retry = false;
|
||||
try {
|
||||
if (isScopedUri(source) && isScopedUri(dest)) {
|
||||
await RNSAF.copyFile(source, dest, { replaceIfDestinationExists: true });
|
||||
return;
|
||||
} else if (isScopedUri(source) || isScopedUri(dest)) {
|
||||
throw new Error('Move between different storage types not supported');
|
||||
}
|
||||
await RNFS.copyFile(source, dest);
|
||||
} catch (error) {
|
||||
// On iOS it will throw an error if the file already exist
|
||||
@@ -209,10 +131,6 @@ export default class FsDriverRN extends FsDriverBase {
|
||||
|
||||
public async unlink(path: string) {
|
||||
try {
|
||||
if (isScopedUri(path)) {
|
||||
await RNSAF.unlink(path);
|
||||
return;
|
||||
}
|
||||
await RNFS.unlink(path);
|
||||
} catch (error) {
|
||||
if (error && ((error.message && error.message.indexOf('exist') >= 0) || error.code === 'ENOENT')) {
|
||||
|
||||
@@ -22,9 +22,7 @@ function shimInit() {
|
||||
shim.sjclModule = require('@joplin/lib/vendor/sjcl-rn.js');
|
||||
|
||||
shim.fsDriver = () => {
|
||||
if (!shim.fsDriver_) {
|
||||
shim.fsDriver_ = new FsDriverRN();
|
||||
}
|
||||
if (!shim.fsDriver_) shim.fsDriver_ = new FsDriverRN();
|
||||
return shim.fsDriver_;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 1,
|
||||
"id": "<%= pluginId %>",
|
||||
"app_min_version": "2.9",
|
||||
"app_min_version": "2.8",
|
||||
"version": "1.0.0",
|
||||
"name": "<%= pluginName %>",
|
||||
"description": "<%= pluginDescription %>",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "generator-joplin",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"description": "Scaffolds out a new Joplin plugin",
|
||||
"homepage": "https://github.com/laurent22/joplin/tree/dev/packages/generator-joplin",
|
||||
"author": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@joplin/htmlpack",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"description": "Pack an HTML file and all its linked resources into a single HTML file",
|
||||
"main": "dist/index.js",
|
||||
"types": "src/index.ts",
|
||||
|
||||
2
packages/lib/.gitignore
vendored
2
packages/lib/.gitignore
vendored
@@ -1,2 +1,2 @@
|
||||
plugin_types/
|
||||
markdownUtils.test.js
|
||||
markdownUtils.test.js
|
||||
@@ -1,7 +1,6 @@
|
||||
import Setting, { Env } from './models/Setting';
|
||||
import Logger, { TargetType, LoggerWrapper } from './Logger';
|
||||
import shim from './shim';
|
||||
const { setupProxySettings } = require('./shim-init-node');
|
||||
import BaseService from './services/BaseService';
|
||||
import reducer, { setStore } from './reducer';
|
||||
import KeychainServiceDriver from './services/keychain/KeychainServiceDriver.node';
|
||||
@@ -457,14 +456,6 @@ export default class BaseApplication {
|
||||
syswidecas.addCAs(f);
|
||||
}
|
||||
},
|
||||
'net.proxyEnabled': async () => {
|
||||
setupProxySettings({
|
||||
maxConcurrentConnections: Setting.value('sync.maxConcurrentConnections'),
|
||||
proxyTimeout: Setting.value('net.proxyTimeout'),
|
||||
proxyEnabled: Setting.value('net.proxyEnabled'),
|
||||
proxyUrl: Setting.value('net.proxyUrl'),
|
||||
});
|
||||
},
|
||||
|
||||
// Note: this used to run when "encryption.enabled" was changed, but
|
||||
// now we run it anytime any property of the sync target info is
|
||||
@@ -500,9 +491,6 @@ export default class BaseApplication {
|
||||
sideEffects['locale'] = sideEffects['dateFormat'];
|
||||
sideEffects['encryption.passwordCache'] = sideEffects['syncInfoCache'];
|
||||
sideEffects['encryption.masterPassword'] = sideEffects['syncInfoCache'];
|
||||
sideEffects['sync.maxConcurrentConnections'] = sideEffects['net.proxyEnabled'];
|
||||
sideEffects['sync.proxyTimeout'] = sideEffects['net.proxyEnabled'];
|
||||
sideEffects['sync.proxyUrl'] = sideEffects['net.proxyEnabled'];
|
||||
|
||||
if (action) {
|
||||
const effect = sideEffects[action.key];
|
||||
|
||||
@@ -2,20 +2,17 @@ const TurndownService = require('@joplin/turndown');
|
||||
const turndownPluginGfm = require('@joplin/turndown-plugin-gfm').gfm;
|
||||
import markdownUtils from './markdownUtils';
|
||||
|
||||
const pdfUrlRegex = /[\s\S]*?\.pdf$/i;
|
||||
|
||||
export interface ParseOptions {
|
||||
anchorNames?: string[];
|
||||
preserveImageTagsWithSize?: boolean;
|
||||
baseUrl?: string;
|
||||
disableEscapeContent?: boolean;
|
||||
convertEmbeddedPdfsToLinks?: boolean;
|
||||
}
|
||||
|
||||
export default class HtmlToMd {
|
||||
|
||||
public parse(html: string, options: ParseOptions = {}) {
|
||||
const turndownOpts: any = {
|
||||
const turndown = new TurndownService({
|
||||
headingStyle: 'atx',
|
||||
anchorNames: options.anchorNames ? options.anchorNames.map(n => n.trim().toLowerCase()) : [],
|
||||
codeBlockStyle: 'fenced',
|
||||
@@ -25,36 +22,10 @@ export default class HtmlToMd {
|
||||
strongDelimiter: '**',
|
||||
br: '',
|
||||
disableEscapeContent: 'disableEscapeContent' in options ? options.disableEscapeContent : false,
|
||||
};
|
||||
if (options.convertEmbeddedPdfsToLinks) {
|
||||
// Turndown ignores empty <object> tags, so we need to handle this case seperately
|
||||
// https://github.com/mixmark-io/turndown/issues/293#issuecomment-588984202
|
||||
turndownOpts.blankReplacement = (content: string, node: any) => {
|
||||
if (node.matches('object')) {
|
||||
return pdfRule.replacement(content, node, {});
|
||||
}
|
||||
return '\n\n';
|
||||
};
|
||||
}
|
||||
const turndown = new TurndownService(turndownOpts);
|
||||
});
|
||||
turndown.use(turndownPluginGfm);
|
||||
turndown.remove('script');
|
||||
turndown.remove('style');
|
||||
const pdfRule = {
|
||||
filter: ['embed', 'object'],
|
||||
replacement: function(_content: string, node: any, _options: any) {
|
||||
// We are setting embedded_pdf as name so that we can later distingish them from normal links and create resources for them.
|
||||
if (node.matches('embed') && node.getAttribute('src') && pdfUrlRegex.test(node.getAttribute('src'))) {
|
||||
return `[embedded_pdf](${node.getAttribute('src')})`;
|
||||
} else if (node.matches('object') && node.getAttribute('data') && pdfUrlRegex.test(node.getAttribute('data'))) {
|
||||
return `[embedded_pdf](${node.getAttribute('data')})`;
|
||||
}
|
||||
return '';
|
||||
},
|
||||
};
|
||||
if (options.convertEmbeddedPdfsToLinks) {
|
||||
turndown.addRule('pdf', pdfRule);
|
||||
}
|
||||
let md = turndown.turndown(html);
|
||||
if (options.baseUrl) md = markdownUtils.prependBaseUrl(md, options.baseUrl);
|
||||
return md;
|
||||
|
||||
@@ -351,7 +351,7 @@ export default class JoplinDatabase extends Database {
|
||||
// must be set in the synchronizer too.
|
||||
|
||||
// Note: v16 and v17 don't do anything. They were used to debug an issue.
|
||||
const existingDatabaseVersions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42];
|
||||
const existingDatabaseVersions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41];
|
||||
|
||||
let currentVersionIndex = existingDatabaseVersions.indexOf(fromVersion);
|
||||
|
||||
@@ -910,10 +910,6 @@ export default class JoplinDatabase extends Database {
|
||||
queries.push('ALTER TABLE `folders` ADD COLUMN icon TEXT NOT NULL DEFAULT ""');
|
||||
}
|
||||
|
||||
if (targetVersion == 42) {
|
||||
queries.push('ALTER TABLE `notes` ADD COLUMN is_shared_recursive INT NOT NULL DEFAULT 0');
|
||||
}
|
||||
|
||||
const updateVersionQuery = { sql: 'UPDATE version SET version = ?', params: [targetVersion] };
|
||||
|
||||
queries.push(updateVersionQuery);
|
||||
|
||||
@@ -2,7 +2,7 @@ const BaseSyncTarget = require('./BaseSyncTarget').default;
|
||||
const { _ } = require('./locale');
|
||||
const Setting = require('./models/Setting').default;
|
||||
const { FileApi } = require('./file-api.js');
|
||||
const { FileApiDriverLocal } = require('./file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('./file-api-driver-local.js');
|
||||
const Synchronizer = require('./Synchronizer').default;
|
||||
|
||||
class SyncTargetFilesystem extends BaseSyncTarget {
|
||||
|
||||
@@ -23,7 +23,7 @@ class FileApiDriverLocal {
|
||||
}
|
||||
|
||||
fsDriver() {
|
||||
if (!FileApiDriverLocal.fsDriver_) { throw new Error('FileApiDriverLocal.fsDriver_ not set!'); }
|
||||
if (!FileApiDriverLocal.fsDriver_) throw new Error('FileApiDriverLocal.fsDriver_ not set!');
|
||||
return FileApiDriverLocal.fsDriver_;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,6 @@ class FileApiDriverLocal {
|
||||
}
|
||||
|
||||
async get(path, options) {
|
||||
if (!options) options = {};
|
||||
let output = null;
|
||||
|
||||
try {
|
||||
@@ -152,6 +151,7 @@ class FileApiDriverLocal {
|
||||
} catch (error) {
|
||||
throw this.fsErrorToJsError_(error, path);
|
||||
}
|
||||
|
||||
// if (!options) options = {};
|
||||
|
||||
// if (options.source === 'file') content = await fs.readFile(options.path);
|
||||
@@ -223,15 +223,8 @@ class FileApiDriverLocal {
|
||||
}
|
||||
|
||||
async clearRoot(baseDir) {
|
||||
if (baseDir.startsWith('content://')) {
|
||||
const result = await this.list(baseDir);
|
||||
for (const item of result.items) {
|
||||
await this.fsDriver().remove(item.path);
|
||||
}
|
||||
} else {
|
||||
await this.fsDriver().remove(baseDir);
|
||||
await this.fsDriver().mkdir(baseDir);
|
||||
}
|
||||
await this.fsDriver().remove(baseDir);
|
||||
await this.fsDriver().mkdir(baseDir);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,6 @@ const { escapeHtml } = require('./string-utils.js');
|
||||
// https://stackoverflow.com/a/16119722/561309
|
||||
const imageRegex = /<img([\s\S]*?)src=["']([\s\S]*?)["']([\s\S]*?)>/gi;
|
||||
const anchorRegex = /<a([\s\S]*?)href=["']([\s\S]*?)["']([\s\S]*?)>/gi;
|
||||
const embedRegex = /<embed([\s\S]*?)src=["']([\s\S]*?)["']([\s\S]*?)>/gi;
|
||||
const objectRegex = /<object([\s\S]*?)data=["']([\s\S]*?)["']([\s\S]*?)>/gi;
|
||||
const pdfUrlRegex = /[\s\S]*?\.pdf$/i;
|
||||
|
||||
const selfClosingElements = [
|
||||
'area',
|
||||
@@ -64,11 +61,6 @@ class HtmlUtils {
|
||||
return this.extractUrls(imageRegex, html);
|
||||
}
|
||||
|
||||
// Returns the **encoded** URLs, so to be useful they should be decoded again before use.
|
||||
public extractPdfUrls(html: string) {
|
||||
return [...this.extractUrls(embedRegex, html), ...this.extractUrls(objectRegex, html)].filter(url => pdfUrlRegex.test(url));
|
||||
}
|
||||
|
||||
// Returns the **encoded** URLs, so to be useful they should be decoded again before use.
|
||||
public extractAnchorUrls(html: string) {
|
||||
return this.extractUrls(anchorRegex, html);
|
||||
@@ -95,27 +87,6 @@ class HtmlUtils {
|
||||
});
|
||||
}
|
||||
|
||||
public replaceEmbedUrls(html: string, callback: Function) {
|
||||
if (!html) return '';
|
||||
// We are adding the link as <a> since joplin disabled <embed>, <object> tags due to security reasons.
|
||||
// See: CVE-2020-15930
|
||||
html = html.replace(embedRegex, (_v: string, _before: string, src: string, _after: string) => {
|
||||
const link = callback(src);
|
||||
return `<a href="${link}">${escapeHtml(src)}</a>`;
|
||||
});
|
||||
html = html.replace(objectRegex, (_v: string, _before: string, src: string, _after: string) => {
|
||||
const link = callback(src);
|
||||
return `<a href="${link}">${escapeHtml(src)}</a>`;
|
||||
});
|
||||
return html;
|
||||
}
|
||||
|
||||
public replaceMediaUrls(html: string, callback: Function) {
|
||||
html = this.replaceImageUrls(html, callback);
|
||||
html = this.replaceEmbedUrls(html, callback);
|
||||
return html;
|
||||
}
|
||||
|
||||
// Note that the URLs provided by this function are URL-encoded, which is
|
||||
// usually what you want for web URLs. But if they are file:// URLs and the
|
||||
// file path is going to be used, it will need to be unescaped first. The
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import markdownUtils from './markdownUtils';
|
||||
import markdownUtils, { parseMarkdownTable } from './markdownUtils';
|
||||
|
||||
describe('Should detect list items', () => {
|
||||
test('should detect `- lorem ipsum` as list item ', () => {
|
||||
@@ -91,4 +91,51 @@ describe('Should detect list items', () => {
|
||||
expect(markdownUtils.isEmptyListItem('+ [x]')).toBe(false);
|
||||
});
|
||||
|
||||
test('should parse a Markdown table', () => {
|
||||
const table = parseMarkdownTable(`
|
||||
| Name | Town | Comment |
|
||||
|----------:|:-------:|----|
|
||||
| John | London | None |
|
||||
| Paul | Liverpool | **test bold** |
|
||||
| Ringo | Sheffield | <a href="#">link</a>  |
|
||||
`.trim().split('\n').map(l => l.trim()).join('\n'));
|
||||
|
||||
expect(table).toEqual({
|
||||
'headers': [
|
||||
{
|
||||
'label': 'Name',
|
||||
'name': 'c0',
|
||||
'justify': 'right',
|
||||
},
|
||||
{
|
||||
'label': 'Town',
|
||||
'name': 'c1',
|
||||
'justify': 'center',
|
||||
},
|
||||
{
|
||||
'label': 'Comment',
|
||||
'name': 'c2',
|
||||
'justify': 'left',
|
||||
},
|
||||
],
|
||||
'rows': [
|
||||
{
|
||||
'c0': 'John',
|
||||
'c1': 'London',
|
||||
'c2': 'None',
|
||||
},
|
||||
{
|
||||
'c0': 'Paul',
|
||||
'c1': 'Liverpool',
|
||||
'c2': '**test bold**',
|
||||
},
|
||||
{
|
||||
'c0': 'Ringo',
|
||||
'c1': 'Sheffield',
|
||||
'c2': '<a href="#">link</a> ',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ const emptyListRegex = /^(\s*)([*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s+)$/;
|
||||
export enum MarkdownTableJustify {
|
||||
Left = 'left',
|
||||
Center = 'center',
|
||||
Right = 'right,',
|
||||
Right = 'right',
|
||||
}
|
||||
|
||||
export interface MarkdownTableHeader {
|
||||
@@ -25,6 +25,11 @@ export interface MarkdownTableRow {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export interface MarkdownTable {
|
||||
headers: MarkdownTableHeader[];
|
||||
rows: MarkdownTableRow[];
|
||||
}
|
||||
|
||||
const markdownUtils = {
|
||||
// Titles for markdown links only need escaping for [ and ]
|
||||
escapeTitleText(text: string) {
|
||||
@@ -69,7 +74,7 @@ const markdownUtils = {
|
||||
},
|
||||
|
||||
// Returns the **encoded** URLs, so to be useful they should be decoded again before use.
|
||||
extractFileUrls(md: string, onlyType: string = null): Array<string> {
|
||||
extractFileUrls(md: string, onlyImage: boolean = false): Array<string> {
|
||||
const markdownIt = new MarkdownIt();
|
||||
markdownIt.validateLink = validateLinks; // Necessary to support file:/// links
|
||||
|
||||
@@ -77,16 +82,10 @@ const markdownUtils = {
|
||||
const tokens = markdownIt.parse(md, env);
|
||||
const output: string[] = [];
|
||||
|
||||
let linkType = onlyType;
|
||||
if (linkType === 'pdf') linkType = 'link_open';
|
||||
|
||||
const searchUrls = (tokens: any[]) => {
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if ((!onlyType && (token.type === 'link_open' || token.type === 'image')) || (!!onlyType && token.type === onlyType) || (onlyType == 'pdf' && token.type === 'link_open')) {
|
||||
// Pdf embeds are a special case, they are represented as 'link_open' tokens but are marked with 'embedded_pdf' as link name by the parser
|
||||
// We are making sure if its in the proper pdf link format, only then we add it to the list
|
||||
if (onlyType === 'pdf' && !(tokens.length > i + 1 && tokens[i + 1].type === 'text' && tokens[i + 1].content === 'embedded_pdf')) continue;
|
||||
if ((onlyImage === true && token.type === 'image') || (onlyImage === false && (token.type === 'image' || token.type === 'link_open'))) {
|
||||
for (let j = 0; j < token.attrs.length; j++) {
|
||||
const a = token.attrs[j];
|
||||
if ((a[0] === 'src' || a[0] === 'href') && a.length >= 2 && a[1]) {
|
||||
@@ -113,11 +112,7 @@ const markdownUtils = {
|
||||
},
|
||||
|
||||
extractImageUrls(md: string) {
|
||||
return markdownUtils.extractFileUrls(md, 'image');
|
||||
},
|
||||
|
||||
extractPdfUrls(md: string) {
|
||||
return markdownUtils.extractFileUrls(md, 'pdf');
|
||||
return markdownUtils.extractFileUrls(md,true);
|
||||
},
|
||||
|
||||
// The match results has 5 items
|
||||
@@ -216,4 +211,95 @@ const markdownUtils = {
|
||||
},
|
||||
};
|
||||
|
||||
export const parseMarkdownTable = (tableMarkdown: string): MarkdownTable => {
|
||||
interface Token {
|
||||
type: string;
|
||||
content: string;
|
||||
attrGet: (name: string)=> string;
|
||||
}
|
||||
|
||||
const getJustifyFromStyle = (token: Token): MarkdownTableJustify => {
|
||||
const style = token.attrGet('style');
|
||||
if (!style) return MarkdownTableJustify.Left;
|
||||
if (style.includes('text-align:right')) return MarkdownTableJustify.Right;
|
||||
if (style.includes('text-align:left')) return MarkdownTableJustify.Left;
|
||||
if (style.includes('text-align:center')) return MarkdownTableJustify.Center;
|
||||
return MarkdownTableJustify.Left;
|
||||
};
|
||||
|
||||
const env = {};
|
||||
const markdownIt = new MarkdownIt();
|
||||
const tokens: Token[] = markdownIt.parse(tableMarkdown, env);
|
||||
const headers: MarkdownTableHeader[] = [];
|
||||
const rows: MarkdownTableRow[] = [];
|
||||
|
||||
let state = 'start';
|
||||
let headerIndex = 0;
|
||||
let rowIndex = -1;
|
||||
|
||||
for (const token of tokens) {
|
||||
if (state === 'start') {
|
||||
if (token.type !== 'table_open') {
|
||||
throw new Error('Expected table_open token');
|
||||
} else {
|
||||
state = 'open';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.type === 'thead_open') {
|
||||
state = 'header';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (state === 'header') {
|
||||
if (token.type === 'th_open') {
|
||||
headers.push({
|
||||
label: '',
|
||||
name: `c${headerIndex}`,
|
||||
justify: getJustifyFromStyle(token),
|
||||
});
|
||||
}
|
||||
|
||||
if (token.type === 'inline') {
|
||||
headers[headerIndex].label += token.content;
|
||||
}
|
||||
|
||||
if (token.type === 'th_close') {
|
||||
headerIndex++;
|
||||
}
|
||||
|
||||
if (token.type === 'thead_close') {
|
||||
state = 'content';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (state === 'content') {
|
||||
if (token.type === 'tr_open') {
|
||||
state = 'row';
|
||||
rows.push({});
|
||||
rowIndex++;
|
||||
headerIndex = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (state === 'row') {
|
||||
if (token.type === 'inline') {
|
||||
rows[rowIndex][`c${headerIndex}`] = token.content;
|
||||
headerIndex++;
|
||||
}
|
||||
|
||||
if (token.type === 'tr_close') {
|
||||
state = 'content';
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return { headers, rows };
|
||||
};
|
||||
|
||||
export default markdownUtils;
|
||||
|
||||
@@ -28,17 +28,6 @@ export class MarkupLanguageUtils {
|
||||
return urls;
|
||||
}
|
||||
|
||||
public extractPdfUrls(language: MarkupLanguage, text: string): string[] {
|
||||
let urls: string[] = [];
|
||||
if (language === MarkupLanguage.Any) {
|
||||
urls = urls.concat(this.lib_(MarkupLanguage.Markdown).extractPdfUrls(text));
|
||||
urls = urls.concat(this.lib_(MarkupLanguage.Html).extractPdfUrls(text));
|
||||
} else {
|
||||
urls = this.lib_(language).extractPdfUrls(text);
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
// Create a new MarkupToHtml instance while injecting options specific to Joplin
|
||||
// desktop and mobile applications.
|
||||
public newMarkupToHtml(_plugins: PluginStates = null, options: Options = null) {
|
||||
|
||||
@@ -418,7 +418,7 @@ export default class BaseItem extends BaseModel {
|
||||
const share = item.share_id ? await this.shareService().shareById(item.share_id) : null;
|
||||
const serialized = await ItemClass.serialize(item, shownKeys);
|
||||
|
||||
if (!getEncryptionEnabled() || !ItemClass.encryptionSupported() || !itemCanBeEncrypted(item, share)) {
|
||||
if (!getEncryptionEnabled() || !ItemClass.encryptionSupported() || !itemCanBeEncrypted(item)) {
|
||||
// Normally not possible since itemsThatNeedSync should only return decrypted items
|
||||
if (item.encryption_applied) throw new JoplinError('Item is encrypted but encryption is currently disabled', 'cannotSyncEncrypted');
|
||||
return serialized;
|
||||
|
||||
@@ -348,55 +348,24 @@ export default class Folder extends BaseItem {
|
||||
}
|
||||
|
||||
public static async updateNoteShareIds() {
|
||||
{
|
||||
// Find all the notes where the share_id is not the same as the
|
||||
// parent share_id because we only need to update those.
|
||||
const rows = await this.db().selectAll(`
|
||||
SELECT notes.id, folders.share_id, notes.parent_id
|
||||
FROM notes
|
||||
LEFT JOIN folders ON notes.parent_id = folders.id
|
||||
WHERE notes.share_id != folders.share_id
|
||||
`);
|
||||
// Find all the notes where the share_id is not the same as the
|
||||
// parent share_id because we only need to update those.
|
||||
const rows = await this.db().selectAll(`
|
||||
SELECT notes.id, folders.share_id, notes.parent_id
|
||||
FROM notes
|
||||
LEFT JOIN folders ON notes.parent_id = folders.id
|
||||
WHERE notes.share_id != folders.share_id
|
||||
`);
|
||||
|
||||
logger.debug('updateNoteShareIds: notes to update:', rows.length);
|
||||
logger.debug('updateNoteShareIds: notes to update:', rows.length);
|
||||
|
||||
for (const row of rows) {
|
||||
await Note.save({
|
||||
id: row.id,
|
||||
share_id: row.share_id || '',
|
||||
parent_id: row.parent_id,
|
||||
updated_time: Date.now(),
|
||||
}, { autoTimestamp: false });
|
||||
}
|
||||
}
|
||||
|
||||
// Also applies recursively published notes
|
||||
{
|
||||
// Find all the notes where the share_id is not the same as the
|
||||
// parent share_id because we only need to update those.
|
||||
const rows = await this.db().selectAll(`
|
||||
SELECT notes.id, folders.share_id, notes.parent_id, notes.body
|
||||
FROM notes
|
||||
WHERE notes.is_shared = 1 AND notes.is_shared_recursive = 1
|
||||
`);
|
||||
|
||||
logger.debug('updateNoteShareIds: notes recursively published:', rows.length);
|
||||
|
||||
// for (const row of rows) {
|
||||
|
||||
// // await Note.save({
|
||||
// // id: row.id,
|
||||
// // share_id: row.share_id || '',
|
||||
// // parent_id: row.parent_id,
|
||||
// // updated_time: Date.now(),
|
||||
// // }, { autoTimestamp: false });
|
||||
// }
|
||||
|
||||
// TODO: should start from root notes - don't set is_recursive on children?
|
||||
// TODO: when a child note is moved out of parent, how to know that is_shared should be cleared? - need share_root prop?
|
||||
// or based on Share API objects? (passed to this function?)
|
||||
// TODO: also unshare notes that have been unlinked (is_shared != parent.is_shared)
|
||||
// TODO: avoid infinite loops
|
||||
for (const row of rows) {
|
||||
await Note.save({
|
||||
id: row.id,
|
||||
share_id: row.share_id || '',
|
||||
parent_id: row.parent_id,
|
||||
updated_time: Date.now(),
|
||||
}, { autoTimestamp: false });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -656,7 +625,7 @@ export default class Folder extends BaseItem {
|
||||
rootFolders.push(folder);
|
||||
} else {
|
||||
if (!idToFolders[folder.parent_id]) {
|
||||
// It means the notebook is referring a folder that doesn't exist. In theory it shouldn't happen
|
||||
// It means the notebook is refering a folder that doesn't exist. In theory it shouldn't happen
|
||||
// but sometimes does - https://github.com/laurent22/joplin/issues/1068#issuecomment-450594708
|
||||
rootFolders.push(folder);
|
||||
} else {
|
||||
|
||||
@@ -411,37 +411,3 @@ describe('models/Note', function() {
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
describe('models/Note_replacePaths', function() {
|
||||
|
||||
function testResourceReplacment(body: string, pathsToTry: string[], expected: string) {
|
||||
expect(Note['replaceResourceExternalToInternalLinks_'](pathsToTry, body)).toBe(expected);
|
||||
}
|
||||
test('Basic replacement', () => {
|
||||
const body = '';
|
||||
const pathsToTry = ['file:///C:Users/Username/resources'];
|
||||
const expected = '';
|
||||
testResourceReplacment(body, pathsToTry, expected);
|
||||
});
|
||||
|
||||
test('Replacement with spaces', () => {
|
||||
const body = '';
|
||||
const pathsToTry = ['file:///C:Users/Username with spaces/resources'];
|
||||
const expected = '';
|
||||
testResourceReplacment(body, pathsToTry, expected);
|
||||
});
|
||||
|
||||
test('Replacement with Non-ASCII', () => {
|
||||
const body = '';
|
||||
const pathsToTry = ['file:///C:Users/UsernameWithéàö/resources'];
|
||||
const expected = '';
|
||||
testResourceReplacment(body, pathsToTry, expected);
|
||||
});
|
||||
|
||||
test('Replacement with Non-ASCII and spaces', () => {
|
||||
const body = '';
|
||||
const pathsToTry = ['file:///C:Users/Username With éàö/resources'];
|
||||
const expected = '';
|
||||
testResourceReplacment(body, pathsToTry, expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,7 +182,7 @@ export default class Note extends BaseItem {
|
||||
|
||||
const resourceDir = toForwardSlashes(Setting.value('resourceDir'));
|
||||
|
||||
const pathsToTry = [];
|
||||
let pathsToTry = [];
|
||||
if (options.useAbsolutePaths) {
|
||||
pathsToTry.push(`file://${resourceDir}`);
|
||||
pathsToTry.push(`file:///${resourceDir}`);
|
||||
@@ -192,13 +192,6 @@ export default class Note extends BaseItem {
|
||||
pathsToTry.push(Resource.baseRelativeDirectoryPath());
|
||||
}
|
||||
|
||||
body = Note.replaceResourceExternalToInternalLinks_(pathsToTry, body);
|
||||
return body;
|
||||
}
|
||||
|
||||
private static replaceResourceExternalToInternalLinks_(pathsToTry: string[], body: string) {
|
||||
// This is a moved to a separate function for the purpose of testing only
|
||||
|
||||
// We support both the escaped and unescaped versions because both
|
||||
// of those paths are valid:
|
||||
//
|
||||
@@ -209,7 +202,7 @@ export default class Note extends BaseItem {
|
||||
const temp = [];
|
||||
for (const p of pathsToTry) {
|
||||
temp.push(p);
|
||||
temp.push(encodeURI(p));
|
||||
temp.push(markdownUtils.escapeLinkUrl(p));
|
||||
}
|
||||
|
||||
pathsToTry = temp;
|
||||
@@ -234,6 +227,7 @@ export default class Note extends BaseItem {
|
||||
// Handles joplin://af0edffa4a60496bba1b0ba06b8fb39a
|
||||
body = body.replace(/\(joplin:\/\/([a-zA-Z0-9]{32})\)/g, '(:/$1)');
|
||||
}
|
||||
|
||||
// this.logger().debug('replaceResourceExternalToInternalLinks result', body);
|
||||
|
||||
return body;
|
||||
|
||||
@@ -207,7 +207,7 @@ export default class Resource extends BaseItem {
|
||||
|
||||
const share = resource.share_id ? await this.shareService().shareById(resource.share_id) : null;
|
||||
|
||||
if (!getEncryptionEnabled() || !itemCanBeEncrypted(resource as any, share)) {
|
||||
if (!getEncryptionEnabled() || !itemCanBeEncrypted(resource as any)) {
|
||||
// Normally not possible since itemsThatNeedSync should only return decrypted items
|
||||
if (resource.encryption_blob_encrypted) throw new Error('Trying to access encrypted resource but encryption is currently disabled');
|
||||
return { path: plainTextPath, resource: resource };
|
||||
|
||||
@@ -864,7 +864,7 @@ class Setting extends BaseModel {
|
||||
public: false,
|
||||
},
|
||||
|
||||
showNoteCounts: { value: true, type: SettingItemType.Bool, storage: SettingStorage.File, isGlobal: true, public: false, advanced: true, appTypes: [AppType.Desktop,AppType.Cli], label: () => _('Show note counts') },
|
||||
showNoteCounts: { value: true, type: SettingItemType.Bool, storage: SettingStorage.File, isGlobal: true, public: false, advanced: true, appTypes: [AppType.Desktop], label: () => _('Show note counts') },
|
||||
|
||||
layoutButtonSequence: {
|
||||
value: Setting.LAYOUT_ALL,
|
||||
@@ -1384,37 +1384,7 @@ class Setting extends BaseModel {
|
||||
label: () => _('Ignore TLS certificate errors'),
|
||||
storage: SettingStorage.File,
|
||||
},
|
||||
'net.proxyEnabled': {
|
||||
value: false,
|
||||
type: SettingItemType.Bool,
|
||||
advanced: true,
|
||||
section: 'sync',
|
||||
isGlobal: true,
|
||||
public: true,
|
||||
label: () => _('Proxy enabled (beta)'),
|
||||
storage: SettingStorage.File,
|
||||
},
|
||||
'net.proxyUrl': {
|
||||
value: '',
|
||||
type: SettingItemType.String,
|
||||
advanced: true,
|
||||
section: 'sync',
|
||||
isGlobal: true,
|
||||
public: true,
|
||||
label: () => _('Proxy URL (beta)'),
|
||||
description: () => _('e.g "http://my.proxy.com:80". You can also set via environment variables'),
|
||||
storage: SettingStorage.File,
|
||||
},
|
||||
'net.proxyTimeout': {
|
||||
value: 1,
|
||||
type: SettingItemType.Int,
|
||||
advanced: true,
|
||||
section: 'sync',
|
||||
isGlobal: true,
|
||||
public: true,
|
||||
label: () => _('proxy timeout (seconds) (beta)'),
|
||||
storage: SettingStorage.File,
|
||||
},
|
||||
|
||||
'sync.wipeOutFailSafe': {
|
||||
value: true,
|
||||
type: SettingItemType.Bool,
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
import { BaseItemEntity } from '../../services/database/types';
|
||||
import { StateShare } from '../../services/share/reducer';
|
||||
|
||||
export default function(item: BaseItemEntity, share: StateShare): boolean {
|
||||
// Note has been published - currently we don't encrypt
|
||||
if (item.is_shared) return false;
|
||||
|
||||
// Item has been shared with user, but sharee is not encrypting his notes,
|
||||
// so we shouldn't encrypt it either. Otherwise sharee will not be able to
|
||||
// view the note anymore. https://github.com/laurent22/joplin/issues/6645
|
||||
if (item.share_id && (!share || !share.master_key_id)) return false;
|
||||
|
||||
return true;
|
||||
export default function(resource: BaseItemEntity): boolean {
|
||||
return !resource.is_shared;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@joplin/lib",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"description": "Joplin Core library",
|
||||
"author": "Laurent Cozic",
|
||||
"homepage": "",
|
||||
@@ -33,8 +33,8 @@
|
||||
"@joplin/fork-htmlparser2": "^4.1.40",
|
||||
"@joplin/fork-sax": "^1.2.44",
|
||||
"@joplin/fork-uslug": "^1.0.5",
|
||||
"@joplin/htmlpack": "~2.9",
|
||||
"@joplin/renderer": "~2.9",
|
||||
"@joplin/htmlpack": "^2.8.1",
|
||||
"@joplin/renderer": "^2.8.1",
|
||||
"@joplin/turndown": "^4.0.62",
|
||||
"@joplin/turndown-plugin-gfm": "^1.0.44",
|
||||
"@types/nanoid": "^3.0.0",
|
||||
@@ -53,7 +53,6 @@
|
||||
"follow-redirects": "^1.2.4",
|
||||
"form-data": "^2.1.4",
|
||||
"fs-extra": "^5.0.0",
|
||||
"hpagent": "^1.0.0",
|
||||
"html-entities": "^1.2.1",
|
||||
"html-minifier": "^3.5.15",
|
||||
"image-data-uri": "^2.0.0",
|
||||
|
||||
@@ -52,10 +52,6 @@ export const defaultFolderIcon = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// AUTO-GENERATED BY packages/tools/generate-database-types.js
|
||||
|
||||
/*
|
||||
@@ -63,226 +59,225 @@ export const defaultFolderIcon = () => {
|
||||
* Rerun sql-ts to regenerate this file.
|
||||
*/
|
||||
export interface AlarmEntity {
|
||||
'id'?: number | null;
|
||||
'note_id'?: string;
|
||||
'trigger_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"note_id"?: string
|
||||
"trigger_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface DeletedItemEntity {
|
||||
'id'?: number | null;
|
||||
'item_type'?: number;
|
||||
'item_id'?: string;
|
||||
'deleted_time'?: number;
|
||||
'sync_target'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"item_type"?: number
|
||||
"item_id"?: string
|
||||
"deleted_time"?: number
|
||||
"sync_target"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface FolderEntity {
|
||||
'id'?: string | null;
|
||||
'title'?: string;
|
||||
'created_time'?: number;
|
||||
'updated_time'?: number;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'parent_id'?: string;
|
||||
'is_shared'?: number;
|
||||
'share_id'?: string;
|
||||
'master_key_id'?: string;
|
||||
'icon'?: string;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"title"?: string
|
||||
"created_time"?: number
|
||||
"updated_time"?: number
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"parent_id"?: string
|
||||
"is_shared"?: number
|
||||
"share_id"?: string
|
||||
"master_key_id"?: string
|
||||
"icon"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface ItemChangeEntity {
|
||||
'id'?: number | null;
|
||||
'item_type'?: number;
|
||||
'item_id'?: string;
|
||||
'type'?: number;
|
||||
'created_time'?: number;
|
||||
'source'?: number;
|
||||
'before_change_item'?: string;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"item_type"?: number
|
||||
"item_id"?: string
|
||||
"type"?: number
|
||||
"created_time"?: number
|
||||
"source"?: number
|
||||
"before_change_item"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface KeyValueEntity {
|
||||
'id'?: number | null;
|
||||
'key'?: string;
|
||||
'value'?: string;
|
||||
'type'?: number;
|
||||
'updated_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"key"?: string
|
||||
"value"?: string
|
||||
"type"?: number
|
||||
"updated_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface MigrationEntity {
|
||||
'id'?: number | null;
|
||||
'number'?: number;
|
||||
'updated_time'?: number;
|
||||
'created_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"number"?: number
|
||||
"updated_time"?: number
|
||||
"created_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface NoteResourceEntity {
|
||||
'id'?: number | null;
|
||||
'note_id'?: string;
|
||||
'resource_id'?: string;
|
||||
'is_associated'?: number;
|
||||
'last_seen_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"note_id"?: string
|
||||
"resource_id"?: string
|
||||
"is_associated"?: number
|
||||
"last_seen_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface NoteTagEntity {
|
||||
'id'?: string | null;
|
||||
'note_id'?: string;
|
||||
'tag_id'?: string;
|
||||
'created_time'?: number;
|
||||
'updated_time'?: number;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'is_shared'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"note_id"?: string
|
||||
"tag_id"?: string
|
||||
"created_time"?: number
|
||||
"updated_time"?: number
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"is_shared"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface NoteEntity {
|
||||
'id'?: string | null;
|
||||
'parent_id'?: string;
|
||||
'title'?: string;
|
||||
'body'?: string;
|
||||
'created_time'?: number;
|
||||
'updated_time'?: number;
|
||||
'is_conflict'?: number;
|
||||
'latitude'?: number;
|
||||
'longitude'?: number;
|
||||
'altitude'?: number;
|
||||
'author'?: string;
|
||||
'source_url'?: string;
|
||||
'is_todo'?: number;
|
||||
'todo_due'?: number;
|
||||
'todo_completed'?: number;
|
||||
'source'?: string;
|
||||
'source_application'?: string;
|
||||
'application_data'?: string;
|
||||
'order'?: number;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'markup_language'?: number;
|
||||
'is_shared'?: number;
|
||||
'share_id'?: string;
|
||||
'conflict_original_id'?: string;
|
||||
'master_key_id'?: string;
|
||||
'is_shared_recursive'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"parent_id"?: string
|
||||
"title"?: string
|
||||
"body"?: string
|
||||
"created_time"?: number
|
||||
"updated_time"?: number
|
||||
"is_conflict"?: number
|
||||
"latitude"?: number
|
||||
"longitude"?: number
|
||||
"altitude"?: number
|
||||
"author"?: string
|
||||
"source_url"?: string
|
||||
"is_todo"?: number
|
||||
"todo_due"?: number
|
||||
"todo_completed"?: number
|
||||
"source"?: string
|
||||
"source_application"?: string
|
||||
"application_data"?: string
|
||||
"order"?: number
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"markup_language"?: number
|
||||
"is_shared"?: number
|
||||
"share_id"?: string
|
||||
"conflict_original_id"?: string
|
||||
"master_key_id"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface NotesNormalizedEntity {
|
||||
'id'?: string;
|
||||
'title'?: string;
|
||||
'body'?: string;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'is_todo'?: number;
|
||||
'todo_completed'?: number;
|
||||
'parent_id'?: string;
|
||||
'latitude'?: number;
|
||||
'longitude'?: number;
|
||||
'altitude'?: number;
|
||||
'source_url'?: string;
|
||||
'todo_due'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: string
|
||||
"title"?: string
|
||||
"body"?: string
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"is_todo"?: number
|
||||
"todo_completed"?: number
|
||||
"parent_id"?: string
|
||||
"latitude"?: number
|
||||
"longitude"?: number
|
||||
"altitude"?: number
|
||||
"source_url"?: string
|
||||
"todo_due"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface ResourceLocalStateEntity {
|
||||
'id'?: number | null;
|
||||
'resource_id'?: string;
|
||||
'fetch_status'?: number;
|
||||
'fetch_error'?: string;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"resource_id"?: string
|
||||
"fetch_status"?: number
|
||||
"fetch_error"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface ResourceEntity {
|
||||
'id'?: string | null;
|
||||
'title'?: string;
|
||||
'mime'?: string;
|
||||
'filename'?: string;
|
||||
'created_time'?: number;
|
||||
'updated_time'?: number;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'file_extension'?: string;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'encryption_blob_encrypted'?: number;
|
||||
'size'?: number;
|
||||
'is_shared'?: number;
|
||||
'share_id'?: string;
|
||||
'master_key_id'?: string;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"title"?: string
|
||||
"mime"?: string
|
||||
"filename"?: string
|
||||
"created_time"?: number
|
||||
"updated_time"?: number
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"file_extension"?: string
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"encryption_blob_encrypted"?: number
|
||||
"size"?: number
|
||||
"is_shared"?: number
|
||||
"share_id"?: string
|
||||
"master_key_id"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface ResourcesToDownloadEntity {
|
||||
'id'?: number | null;
|
||||
'resource_id'?: string;
|
||||
'updated_time'?: number;
|
||||
'created_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"resource_id"?: string
|
||||
"updated_time"?: number
|
||||
"created_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface RevisionEntity {
|
||||
'id'?: string | null;
|
||||
'parent_id'?: string;
|
||||
'item_type'?: number;
|
||||
'item_id'?: string;
|
||||
'item_updated_time'?: number;
|
||||
'title_diff'?: string;
|
||||
'body_diff'?: string;
|
||||
'metadata_diff'?: string;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'updated_time'?: number;
|
||||
'created_time'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"parent_id"?: string
|
||||
"item_type"?: number
|
||||
"item_id"?: string
|
||||
"item_updated_time"?: number
|
||||
"title_diff"?: string
|
||||
"body_diff"?: string
|
||||
"metadata_diff"?: string
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"updated_time"?: number
|
||||
"created_time"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface SettingEntity {
|
||||
'key'?: string | null;
|
||||
'value'?: string | null;
|
||||
'type_'?: number;
|
||||
"key"?: string | null
|
||||
"value"?: string | null
|
||||
"type_"?: number
|
||||
}
|
||||
export interface SyncItemEntity {
|
||||
'id'?: number | null;
|
||||
'sync_target'?: number;
|
||||
'sync_time'?: number;
|
||||
'item_type'?: number;
|
||||
'item_id'?: string;
|
||||
'sync_disabled'?: number;
|
||||
'sync_disabled_reason'?: string;
|
||||
'force_sync'?: number;
|
||||
'item_location'?: number;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"sync_target"?: number
|
||||
"sync_time"?: number
|
||||
"item_type"?: number
|
||||
"item_id"?: string
|
||||
"sync_disabled"?: number
|
||||
"sync_disabled_reason"?: string
|
||||
"force_sync"?: number
|
||||
"item_location"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
export interface TableFieldEntity {
|
||||
'id'?: number | null;
|
||||
'table_name'?: string;
|
||||
'field_name'?: string;
|
||||
'field_type'?: number;
|
||||
'field_default'?: string | null;
|
||||
'type_'?: number;
|
||||
"id"?: number | null
|
||||
"table_name"?: string
|
||||
"field_name"?: string
|
||||
"field_type"?: number
|
||||
"field_default"?: string | null
|
||||
"type_"?: number
|
||||
}
|
||||
export interface TagEntity {
|
||||
'id'?: string | null;
|
||||
'title'?: string;
|
||||
'created_time'?: number;
|
||||
'updated_time'?: number;
|
||||
'user_created_time'?: number;
|
||||
'user_updated_time'?: number;
|
||||
'encryption_cipher_text'?: string;
|
||||
'encryption_applied'?: number;
|
||||
'is_shared'?: number;
|
||||
'parent_id'?: string;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"title"?: string
|
||||
"created_time"?: number
|
||||
"updated_time"?: number
|
||||
"user_created_time"?: number
|
||||
"user_updated_time"?: number
|
||||
"encryption_cipher_text"?: string
|
||||
"encryption_applied"?: number
|
||||
"is_shared"?: number
|
||||
"parent_id"?: string
|
||||
"type_"?: number
|
||||
}
|
||||
export interface TagsWithNoteCountEntity {
|
||||
'id'?: string | null;
|
||||
'title'?: string | null;
|
||||
'created_time'?: number | null;
|
||||
'updated_time'?: number | null;
|
||||
'note_count'?: any | null;
|
||||
'todo_completed_count'?: any | null;
|
||||
'type_'?: number;
|
||||
"id"?: string | null
|
||||
"title"?: string | null
|
||||
"created_time"?: number | null
|
||||
"updated_time"?: number | null
|
||||
"note_count"?: any | null
|
||||
"todo_completed_count"?: any | null
|
||||
"type_"?: number
|
||||
}
|
||||
export interface VersionEntity {
|
||||
'version'?: number;
|
||||
'table_fields_version'?: number;
|
||||
'type_'?: number;
|
||||
"version"?: number
|
||||
"table_fields_version"?: number
|
||||
"type_"?: number
|
||||
}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// PlatformImplementation provides access to platform specific dependencies,
|
||||
// such as the clipboard, message dialog, etc. It allows having the same plugin
|
||||
|
||||
import { VersionInfo } from './api/types';
|
||||
import { Implementation as WindowImplementation } from './api/JoplinWindow';
|
||||
|
||||
export interface JoplinViewsDialogs {
|
||||
showMessageBox(message: string): Promise<number>;
|
||||
}
|
||||
|
||||
export interface JoplinViews {
|
||||
dialogs: JoplinViewsDialogs;
|
||||
}
|
||||
|
||||
export interface Joplin {
|
||||
views: JoplinViews;
|
||||
}
|
||||
|
||||
// API for all platforms, but with different implementations.
|
||||
export default class BasePlatformImplementation {
|
||||
|
||||
public get versionInfo(): VersionInfo {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public get clipboard(): any {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public get nativeImage(): any {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public get window(): WindowImplementation {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public registerComponent(_name: string, _component: any) {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public unregisterComponent(_name: string) {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
public get joplin(): Joplin {
|
||||
throw new Error('Not implemented');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import JoplinSettings from './JoplinSettings';
|
||||
import JoplinContentScripts from './JoplinContentScripts';
|
||||
import JoplinClipboard from './JoplinClipboard';
|
||||
import JoplinWindow from './JoplinWindow';
|
||||
import BasePlatformImplementation from '../BasePlatformImplementation';
|
||||
|
||||
/**
|
||||
* This is the main entry point to the Joplin API. You can access various services using the provided accessors.
|
||||
@@ -37,10 +36,8 @@ export default class Joplin {
|
||||
private contentScripts_: JoplinContentScripts = null;
|
||||
private clipboard_: JoplinClipboard = null;
|
||||
private window_: JoplinWindow = null;
|
||||
private implementation_: BasePlatformImplementation = null;
|
||||
|
||||
public constructor(implementation: BasePlatformImplementation, plugin: Plugin, store: any) {
|
||||
this.implementation_ = implementation;
|
||||
public constructor(implementation: any, plugin: Plugin, store: any) {
|
||||
this.data_ = new JoplinData();
|
||||
this.plugins_ = new JoplinPlugins(plugin);
|
||||
this.workspace_ = new JoplinWorkspace(store);
|
||||
@@ -120,8 +117,4 @@ export default class Joplin {
|
||||
// Just a stub. Implementation has to be done within plugin process, in plugin_index.js
|
||||
}
|
||||
|
||||
public async versionInfo() {
|
||||
return this.implementation_.versionInfo;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -221,12 +221,6 @@ export enum ModelType {
|
||||
Command = 16,
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
version: string;
|
||||
profileVersion: number;
|
||||
syncVersion: number;
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Menu types
|
||||
// =================================================================
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { PaginationOrderDir } from '../../models/utils/types';
|
||||
import Api, { RequestMethod } from '../../services/rest/Api';
|
||||
import { extractMediaUrls } from './routes/notes';
|
||||
import shim from '../../shim';
|
||||
import { setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, db, msleep, supportDir } from '../../testing/test-utils';
|
||||
import Folder from '../../models/Folder';
|
||||
@@ -10,7 +9,6 @@ import Tag from '../../models/Tag';
|
||||
import NoteTag from '../../models/NoteTag';
|
||||
import ResourceService from '../../services/ResourceService';
|
||||
import SearchEngine from '../../services/searchengine/SearchEngine';
|
||||
const { MarkupToHtml } = require('@joplin/renderer');
|
||||
import { ResourceEntity } from '../database/types';
|
||||
|
||||
const createFolderForPagination = async (num: number, time: number) => {
|
||||
@@ -454,47 +452,6 @@ describe('services_rest_Api', function() {
|
||||
expect(response.body).toBe('**Bold text**');
|
||||
}));
|
||||
|
||||
it('should extract media urls from body', (() => {
|
||||
const tests = [
|
||||
{
|
||||
language: MarkupToHtml.MARKUP_LANGUAGE_HTML,
|
||||
body: '<div> <img src="https://example.com/img.png" /> <embed src="https://example.com/sample.pdf"/> <object data="https://example.com/file.PDF"></object> </div>',
|
||||
result: ['https://example.com/img.png', 'https://example.com/sample.pdf', 'https://example.com/file.PDF'],
|
||||
},
|
||||
{
|
||||
language: MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN,
|
||||
body: 'test text \n  [embedded_pdf](https://example.com/sample1.pdf) [embedded_pdf](https://example.com/file.PDF)',
|
||||
result: ['https://example.com/img1.png', 'https://example.com/sample1.pdf', 'https://example.com/file.PDF'],
|
||||
},
|
||||
{
|
||||
language: MarkupToHtml.MARKUP_LANGUAGE_HTML,
|
||||
body: '<div> <embed src="https://example.com/sample"/> <embed /> <object data="https://example.com/file.pdfff"></object> <a href="https://test.com/file.pdf">Link</a> </div>',
|
||||
result: [],
|
||||
},
|
||||
];
|
||||
tests.forEach((test) => {
|
||||
const urls = extractMediaUrls(test.language, test.body);
|
||||
expect(urls).toEqual(test.result);
|
||||
});
|
||||
}));
|
||||
|
||||
it('should create notes with pdf embeds', (async () => {
|
||||
let response = null;
|
||||
const f = await Folder.save({ title: 'pdf test1' });
|
||||
|
||||
response = await api.route(RequestMethod.POST, 'notes', null, JSON.stringify({
|
||||
title: 'testing PDF embeds',
|
||||
parent_id: f.id,
|
||||
body_html: `<div> <embed src="file://${supportDir}/welcome.pdf" type="application/pdf" /> </div>`,
|
||||
}));
|
||||
|
||||
const resources = await Resource.all();
|
||||
expect(resources.length).toBe(1);
|
||||
|
||||
const resource = resources[0];
|
||||
expect(response.body.indexOf(resource.id) >= 0).toBe(true);
|
||||
}));
|
||||
|
||||
it('should handle tokens', (async () => {
|
||||
api = new Api('mytoken');
|
||||
|
||||
|
||||
@@ -89,7 +89,6 @@ async function requestNoteToNote(requestNote: any) {
|
||||
output.body = await htmlToMdParser().parse(`<div>${requestNote.body_html}</div>`, {
|
||||
baseUrl: baseUrl,
|
||||
anchorNames: requestNote.anchor_names ? requestNote.anchor_names : [],
|
||||
convertEmbeddedPdfsToLinks: true,
|
||||
});
|
||||
output.markup_language = MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN;
|
||||
}
|
||||
@@ -144,20 +143,19 @@ async function buildNoteStyleSheet(stylesheets: any[]) {
|
||||
return output;
|
||||
}
|
||||
|
||||
async function tryToGuessExtFromMimeType(response: any, mediaPath: string) {
|
||||
async function tryToGuessImageExtFromMimeType(response: any, imagePath: string) {
|
||||
const mimeType = mimeTypeFromHeaders(response.headers);
|
||||
if (!mimeType) return mediaPath;
|
||||
if (!mimeType) return imagePath;
|
||||
|
||||
const newExt = mimeUtils.toFileExtension(mimeType);
|
||||
if (!newExt) return mediaPath;
|
||||
if (!newExt) return imagePath;
|
||||
|
||||
const newMediaPath = `${mediaPath}.${newExt}`;
|
||||
await shim.fsDriver().move(mediaPath, newMediaPath);
|
||||
return newMediaPath;
|
||||
const newImagePath = `${imagePath}.${newExt}`;
|
||||
await shim.fsDriver().move(imagePath, newImagePath);
|
||||
return newImagePath;
|
||||
}
|
||||
|
||||
async function downloadMediaFile(url: string /* , allowFileProtocolImages */) {
|
||||
|
||||
async function downloadImage(url: string /* , allowFileProtocolImages */) {
|
||||
const tempDir = Setting.value('tempDir');
|
||||
|
||||
// The URL we get to download have been extracted from the Markdown document
|
||||
@@ -165,12 +163,6 @@ async function downloadMediaFile(url: string /* , allowFileProtocolImages */) {
|
||||
|
||||
const isDataUrl = url && url.toLowerCase().indexOf('data:') === 0;
|
||||
|
||||
// PDFs and other heavy resoucres are often served as seperate files insted of data urls, its very unlikely to encounter a pdf as a data url
|
||||
if (isDataUrl && !url.toLowerCase().startsWith('data:image/')) {
|
||||
reg.logger().warn(`Resources in data URL format is only supported for images ${url}`);
|
||||
return '';
|
||||
}
|
||||
|
||||
const name = isDataUrl ? md5(`${Math.random()}_${Date.now()}`) : filename(url);
|
||||
let fileExt = isDataUrl ? mimeUtils.toFileExtension(mimeUtils.fromDataUrl(url)) : safeFileExtension(fileExtension(url).toLowerCase());
|
||||
if (!mimeUtils.fromFileExtension(fileExt)) fileExt = ''; // If the file extension is unknown - clear it.
|
||||
@@ -178,38 +170,38 @@ async function downloadMediaFile(url: string /* , allowFileProtocolImages */) {
|
||||
|
||||
// Append a UUID because simply checking if the file exists is not enough since
|
||||
// multiple resources can be downloaded at the same time (race condition).
|
||||
let mediaPath = `${tempDir}/${safeFilename(name)}_${uuid.create()}${fileExt}`;
|
||||
let imagePath = `${tempDir}/${safeFilename(name)}_${uuid.create()}${fileExt}`;
|
||||
|
||||
try {
|
||||
if (isDataUrl) {
|
||||
await shim.imageFromDataUrl(url, mediaPath);
|
||||
await shim.imageFromDataUrl(url, imagePath);
|
||||
} else if (urlUtils.urlProtocol(url).toLowerCase() === 'file:') {
|
||||
// Can't think of any reason to disallow this at this point
|
||||
// if (!allowFileProtocolImages) throw new Error('For security reasons, this URL with file:// protocol cannot be downloaded');
|
||||
const localPath = fileUriToPath(url);
|
||||
await shim.fsDriver().copy(localPath, mediaPath);
|
||||
await shim.fsDriver().copy(localPath, imagePath);
|
||||
} else {
|
||||
const response = await shim.fetchBlob(url, { path: mediaPath, maxRetry: 1 });
|
||||
const response = await shim.fetchBlob(url, { path: imagePath, maxRetry: 1 });
|
||||
|
||||
// If we could not find the file extension from the URL, try to get it
|
||||
// now based on the Content-Type header.
|
||||
if (!fileExt) mediaPath = await tryToGuessExtFromMimeType(response, mediaPath);
|
||||
if (!fileExt) imagePath = await tryToGuessImageExtFromMimeType(response, imagePath);
|
||||
}
|
||||
return mediaPath;
|
||||
return imagePath;
|
||||
} catch (error) {
|
||||
reg.logger().warn(`Cannot download image at ${url}`, error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadMediaFiles(urls: string[] /* , allowFileProtocolImages:boolean */) {
|
||||
async function downloadImages(urls: string[] /* , allowFileProtocolImages:boolean */) {
|
||||
const PromisePool = require('es6-promise-pool');
|
||||
|
||||
const output: any = {};
|
||||
|
||||
const downloadOne = async (url: string) => {
|
||||
const mediaPath = await downloadMediaFile(url); // , allowFileProtocolImages);
|
||||
if (mediaPath) output[url] = { path: mediaPath, originalUrl: url };
|
||||
const imagePath = await downloadImage(url); // , allowFileProtocolImages);
|
||||
if (imagePath) output[url] = { path: imagePath, originalUrl: url };
|
||||
};
|
||||
|
||||
let urlIndex = 0;
|
||||
@@ -253,38 +245,27 @@ async function removeTempFiles(urls: string[]) {
|
||||
}
|
||||
}
|
||||
|
||||
function replaceUrlsByResources(markupLanguage: number, md: string, urls: any, imageSizes: any) {
|
||||
function replaceImageUrlsByResources(markupLanguage: number, md: string, urls: any, imageSizes: any) {
|
||||
const imageSizesIndexes: any = {};
|
||||
|
||||
if (markupLanguage === MarkupToHtml.MARKUP_LANGUAGE_HTML) {
|
||||
return htmlUtils.replaceMediaUrls(md, (url: string) => {
|
||||
const urlInfo: any = urls[url];
|
||||
if (!urlInfo || !urlInfo.resource) return url;
|
||||
return htmlUtils.replaceImageUrls(md, (imageUrl: string) => {
|
||||
const urlInfo: any = urls[imageUrl];
|
||||
if (!urlInfo || !urlInfo.resource) return imageUrl;
|
||||
return Resource.internalUrl(urlInfo.resource);
|
||||
});
|
||||
} else {
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
return md.replace(/(!?\[.*?\]\()([^\s\)]+)(.*?\))/g, (_match: any, before: string, url: string, after: string) => {
|
||||
let type = 'link';
|
||||
if (before.startsWith('[embedded_pdf]')) {
|
||||
type = 'pdf';
|
||||
} else if (before.startsWith('![')) {
|
||||
type = 'image';
|
||||
}
|
||||
|
||||
const urlInfo = urls[url];
|
||||
if (type === 'link' || !urlInfo || !urlInfo.resource) return before + url + after;
|
||||
return md.replace(/(!\[.*?\]\()([^\s\)]+)(.*?\))/g, (_match: any, before: string, imageUrl: string, after: string) => {
|
||||
const urlInfo = urls[imageUrl];
|
||||
if (!urlInfo || !urlInfo.resource) return before + imageUrl + after;
|
||||
if (!(urlInfo.originalUrl in imageSizesIndexes)) imageSizesIndexes[urlInfo.originalUrl] = 0;
|
||||
|
||||
const resourceUrl = Resource.internalUrl(urlInfo.resource);
|
||||
if (type === 'pdf') {
|
||||
return `[${markdownUtils.escapeLinkUrl(url)}](${resourceUrl}${after}`;
|
||||
}
|
||||
|
||||
if (!(urlInfo.originalUrl in imageSizesIndexes)) imageSizesIndexes[urlInfo.originalUrl] = 0;
|
||||
const imageSizesCollection = imageSizes[urlInfo.originalUrl];
|
||||
|
||||
if (!imageSizesCollection) {
|
||||
// Either its not an image or we don't know the size of the image
|
||||
// In some cases, we won't find the image size information for that particular image URL. Normally
|
||||
// In some cases, we won't find the image size information for that particular URL. Normally
|
||||
// it will only happen when using the "Clip simplified page" feature, which can modify the
|
||||
// image URLs (for example it will select a smaller size resolution). In that case, it's
|
||||
// fine to return the image as-is because it has already good dimensions.
|
||||
@@ -303,13 +284,6 @@ function replaceUrlsByResources(markupLanguage: number, md: string, urls: any, i
|
||||
}
|
||||
}
|
||||
|
||||
export function extractMediaUrls(markupLanguage: number, text: string): string[] {
|
||||
const urls: string[] = [];
|
||||
urls.push(...ArrayUtils.unique(markupLanguageUtils.extractImageUrls(markupLanguage, text)));
|
||||
urls.push(...ArrayUtils.unique(markupLanguageUtils.extractPdfUrls(markupLanguage, text)));
|
||||
return urls;
|
||||
}
|
||||
|
||||
// Note must have been saved first
|
||||
async function attachImageFromDataUrl(note: any, imageDataUrl: string, cropRect: any) {
|
||||
const tempDir = Setting.value('tempDir');
|
||||
@@ -354,17 +328,17 @@ export default async function(request: Request, id: string = null, link: string
|
||||
|
||||
let note: any = await requestNoteToNote(requestNote);
|
||||
|
||||
const mediaUrls = extractMediaUrls(note.markup_language, note.body);
|
||||
const imageUrls = ArrayUtils.unique(markupLanguageUtils.extractImageUrls(note.markup_language, note.body));
|
||||
|
||||
reg.logger().info(`Request (${requestId}): Downloading media files: ${mediaUrls.length}`);
|
||||
reg.logger().info(`Request (${requestId}): Downloading images: ${imageUrls.length}`);
|
||||
|
||||
let result = await downloadMediaFiles(mediaUrls); // , allowFileProtocolImages);
|
||||
let result = await downloadImages(imageUrls); // , allowFileProtocolImages);
|
||||
|
||||
reg.logger().info(`Request (${requestId}): Creating resources from paths: ${Object.getOwnPropertyNames(result).length}`);
|
||||
|
||||
result = await createResourcesFromPaths(result);
|
||||
await removeTempFiles(result);
|
||||
note.body = replaceUrlsByResources(note.markup_language, note.body, result, imageSizes);
|
||||
note.body = replaceImageUrlsByResources(note.markup_language, note.body, result, imageSizes);
|
||||
|
||||
reg.logger().info(`Request (${requestId}): Saving note...`);
|
||||
|
||||
|
||||
@@ -140,7 +140,6 @@ describe('ShareService', function() {
|
||||
expect(await MasterKey.count()).toBe(1);
|
||||
|
||||
let { folder, note, resource } = await testShareFolder(shareService);
|
||||
await Folder.updateAllShareIds(resourceService());
|
||||
|
||||
// The share service should automatically create a new encryption key
|
||||
// specifically for that shared folder
|
||||
|
||||
@@ -241,7 +241,6 @@ export default class ShareService {
|
||||
id: note.id,
|
||||
parent_id: note.parent_id,
|
||||
is_shared: 1,
|
||||
is_shared_recursive: recursive ? 1 : 0,
|
||||
updated_time: Date.now(),
|
||||
}, {
|
||||
autoTimestamp: false,
|
||||
|
||||
@@ -27,7 +27,6 @@ export interface StateShare {
|
||||
folder_id: string;
|
||||
note_id: string;
|
||||
master_key_id: string;
|
||||
recursive: number;
|
||||
user?: StateShareUserUser;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const fs = require('fs-extra');
|
||||
const shim = require('./shim').default;
|
||||
const GeolocationNode = require('./geolocation-node').default;
|
||||
const { FileApiDriverLocal } = require('./file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('./file-api-driver-local.js');
|
||||
const { setLocale, defaultLocale, closestSupportedLocale } = require('./locale');
|
||||
const FsDriverNode = require('./fs-driver-node').default;
|
||||
const mimeUtils = require('./mime-utils.js').mime;
|
||||
@@ -13,15 +13,12 @@ const urlValidator = require('valid-url');
|
||||
const { _ } = require('./locale');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent');
|
||||
const toRelative = require('relative');
|
||||
const timers = require('timers');
|
||||
const zlib = require('zlib');
|
||||
const dgram = require('dgram');
|
||||
const { basename, fileExtension, safeFileExtension } = require('./path-utils');
|
||||
|
||||
const proxySettings = {};
|
||||
|
||||
function fileExists(filePath) {
|
||||
try {
|
||||
return fs.statSync(filePath).isFile();
|
||||
@@ -30,20 +27,6 @@ function fileExists(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
function isUrlHttps(url) {
|
||||
return url.startsWith('https');
|
||||
}
|
||||
|
||||
function resolveProxyUrl(proxyUrl) {
|
||||
return (
|
||||
proxyUrl ||
|
||||
process.env['http_proxy'] ||
|
||||
process.env['https_proxy'] ||
|
||||
process.env['HTTP_PROXY'] ||
|
||||
process.env['HTTPS_PROXY']
|
||||
);
|
||||
}
|
||||
|
||||
// https://github.com/sindresorhus/callsites/blob/main/index.js
|
||||
function callsites() {
|
||||
const _prepareStackTrace = Error.prepareStackTrace;
|
||||
@@ -81,13 +64,6 @@ const gunzipFile = function(source, destination) {
|
||||
});
|
||||
};
|
||||
|
||||
function setupProxySettings(options) {
|
||||
proxySettings.maxConcurrentConnections = options.maxConcurrentConnections;
|
||||
proxySettings.proxyTimeout = options.proxyTimeout;
|
||||
proxySettings.proxyEnabled = options.proxyEnabled;
|
||||
proxySettings.proxyUrl = options.proxyUrl;
|
||||
}
|
||||
|
||||
function shimInit(options = null) {
|
||||
options = {
|
||||
sharp: null,
|
||||
@@ -103,7 +79,6 @@ function shimInit(options = null) {
|
||||
const keytar = (shim.isWindows() || shim.isMac()) && !shim.isPortable() ? options.keytar : null;
|
||||
const appVersion = options.appVersion;
|
||||
|
||||
|
||||
shim.setNodeSqlite(options.nodeSqlite);
|
||||
|
||||
shim.fsDriver = () => {
|
||||
@@ -445,11 +420,10 @@ function shimInit(options = null) {
|
||||
return new Buffer(data).toString('base64');
|
||||
};
|
||||
|
||||
shim.fetch = async function(url, options = {}) {
|
||||
shim.fetch = async function(url, options = null) {
|
||||
const validatedUrl = urlValidator.isUri(url);
|
||||
if (!validatedUrl) throw new Error(`Not a valid URL: ${url}`);
|
||||
const resolvedProxyUrl = resolveProxyUrl(proxySettings.proxyUrl);
|
||||
options.agent = (resolvedProxyUrl && proxySettings.proxyEnabled) ? shim.proxyAgent(url, resolvedProxyUrl) : null;
|
||||
|
||||
return shim.fetchWithRetry(() => {
|
||||
return nodeFetch(url, options);
|
||||
}, options);
|
||||
@@ -492,9 +466,6 @@ function shimInit(options = null) {
|
||||
headers: headers,
|
||||
};
|
||||
|
||||
const resolvedProxyUrl = resolveProxyUrl(proxySettings.proxyUrl);
|
||||
requestOptions.agent = (resolvedProxyUrl && proxySettings.proxyEnabled) ? shim.proxyAgent(url, resolvedProxyUrl) : null;
|
||||
|
||||
const doFetchOperation = async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
let file = null;
|
||||
@@ -601,27 +572,6 @@ function shimInit(options = null) {
|
||||
return url.startsWith('https') ? shim.httpAgent_.https : shim.httpAgent_.http;
|
||||
};
|
||||
|
||||
shim.proxyAgent = (serverUrl, proxyUrl) => {
|
||||
const proxyAgentConfig = {
|
||||
keepAlive: true,
|
||||
maxSockets: proxySettings.maxConcurrentConnections,
|
||||
keepAliveMsecs: 5000,
|
||||
proxy: proxyUrl,
|
||||
timeout: proxySettings.proxyTimeout * 1000,
|
||||
};
|
||||
|
||||
// Based on https://github.com/delvedor/hpagent#usage
|
||||
if (!isUrlHttps(proxyUrl) && !isUrlHttps(serverUrl)) {
|
||||
return new HttpProxyAgent(proxyAgentConfig);
|
||||
} else if (isUrlHttps(proxyUrl) && !isUrlHttps(serverUrl)) {
|
||||
return new HttpProxyAgent(proxyAgentConfig);
|
||||
} else if (!isUrlHttps(proxyUrl) && isUrlHttps(serverUrl)) {
|
||||
return new HttpsProxyAgent(proxyAgentConfig);
|
||||
} else {
|
||||
return new HttpsProxyAgent(proxyAgentConfig);
|
||||
}
|
||||
};
|
||||
|
||||
shim.openOrCreateFile = (filepath, defaultContents) => {
|
||||
// If the file doesn't exist, create it
|
||||
if (!fs.existsSync(filepath)) {
|
||||
@@ -684,4 +634,4 @@ function shimInit(options = null) {
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { shimInit, setupProxySettings };
|
||||
module.exports = { shimInit };
|
||||
|
||||
@@ -16,7 +16,7 @@ let isTestingEnv_ = false;
|
||||
// (app-desktop, app-mobile, etc.) since we are sure they won't be dependency to
|
||||
// other packages (unlike the lib which can be included anywhere).
|
||||
//
|
||||
// Regarding the type - although we import React, we only use it as a type
|
||||
// Regarding the type - althought we import React, we only use it as a type
|
||||
// using `typeof React`. This is just to get types in hooks.
|
||||
//
|
||||
// https://stackoverflow.com/a/42816077/561309
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
const Entities = require('html-entities').AllHtmlEntities;
|
||||
const htmlentities = new Entities().encode;
|
||||
const stringUtilsCommon = require('./string-utils-common.js');
|
||||
|
||||
const defaultDiacriticsRemovalMap = [
|
||||
@@ -296,25 +294,16 @@ function escapeHtml(s) {
|
||||
// keywords can either be a list of strings, or a list of objects with the format:
|
||||
// { value: 'actualkeyword', type: 'regex/string' }
|
||||
// The function surrounds the keywords wherever they are, even within other words.
|
||||
function surroundKeywords(keywords, text, prefix, suffix, options = null) {
|
||||
options = Object.assign({}, {
|
||||
escapeHtml: false,
|
||||
}, options);
|
||||
|
||||
function surroundKeywords(keywords, text, prefix, suffix) {
|
||||
if (!keywords.length) return text;
|
||||
|
||||
function escapeHtml(s) {
|
||||
if (!options.escapeHtml) return s;
|
||||
return htmlentities(s);
|
||||
}
|
||||
|
||||
let regexString = keywords
|
||||
.map(k => {
|
||||
if (k.type === 'regex') {
|
||||
return escapeHtml(stringUtilsCommon.replaceRegexDiacritics(k.valueRegex));
|
||||
return stringUtilsCommon.replaceRegexDiacritics(k.valueRegex);
|
||||
} else {
|
||||
const value = typeof k === 'string' ? k : k.value;
|
||||
return escapeHtml(stringUtilsCommon.replaceRegexDiacritics(stringUtilsCommon.pregQuote(value)));
|
||||
return stringUtilsCommon.replaceRegexDiacritics(stringUtilsCommon.pregQuote(value));
|
||||
}
|
||||
})
|
||||
.join('|');
|
||||
|
||||
@@ -30,7 +30,7 @@ import MasterKey from '../models/MasterKey';
|
||||
import BaseItem from '../models/BaseItem';
|
||||
import { FileApi } from '../file-api';
|
||||
const FileApiDriverMemory = require('../file-api-driver-memory').default;
|
||||
const { FileApiDriverLocal } = require('../file-api-driver-local');
|
||||
const { FileApiDriverLocal } = require('../file-api-driver-local.js');
|
||||
const { FileApiDriverWebDav } = require('../file-api-driver-webdav.js');
|
||||
const { FileApiDriverDropbox } = require('../file-api-driver-dropbox.js');
|
||||
const { FileApiDriverOneDrive } = require('../file-api-driver-onedrive.js');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@joplin/plugin-repo-cli",
|
||||
"version": "2.9.0",
|
||||
"version": "2.8.1",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"bin": "./dist/index.js",
|
||||
@@ -18,8 +18,8 @@
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@joplin/lib": "~2.9",
|
||||
"@joplin/tools": "~2.9",
|
||||
"@joplin/lib": "^2.8.1",
|
||||
"@joplin/tools": "^2.8.1",
|
||||
"fs-extra": "^9.0.1",
|
||||
"gh-release-assets": "^2.0.0",
|
||||
"node-fetch": "^2.6.1",
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# EditorConfig helps developers define and maintain consistent
|
||||
# coding styles between different editors and IDEs
|
||||
# editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
@@ -1,3 +0,0 @@
|
||||
node_modules/
|
||||
lib/
|
||||
.env
|
||||
3
packages/react-native-saf-x/.gitattributes
vendored
3
packages/react-native-saf-x/.gitattributes
vendored
@@ -1,3 +0,0 @@
|
||||
*.pbxproj -text
|
||||
# specific for windows script files
|
||||
*.bat text eol=crlf
|
||||
66
packages/react-native-saf-x/.gitignore
vendored
66
packages/react-native-saf-x/.gitignore
vendored
@@ -1,66 +0,0 @@
|
||||
# OSX
|
||||
#
|
||||
.DS_Store
|
||||
|
||||
# XDE
|
||||
.expo/
|
||||
|
||||
# VSCode
|
||||
.vscode/
|
||||
jsconfig.json
|
||||
|
||||
# Xcode
|
||||
#
|
||||
build/
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
xcuserdata
|
||||
*.xccheckout
|
||||
*.moved-aside
|
||||
DerivedData
|
||||
*.hmap
|
||||
*.ipa
|
||||
*.xcuserstate
|
||||
project.xcworkspace
|
||||
|
||||
# Android/IJ
|
||||
#
|
||||
.classpath
|
||||
.cxx
|
||||
.gradle
|
||||
.idea
|
||||
.project
|
||||
.settings
|
||||
local.properties
|
||||
android.iml
|
||||
|
||||
# Cocoapods
|
||||
#
|
||||
example/ios/Pods
|
||||
|
||||
# node.js
|
||||
#
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
yarn-debug.log
|
||||
yarn-error.log
|
||||
|
||||
# BUCK
|
||||
buck-out/
|
||||
\.buckd/
|
||||
android/app/libs
|
||||
android/keystores/debug.keystore
|
||||
|
||||
# Expo
|
||||
.expo/*
|
||||
|
||||
# generated by bob
|
||||
lib/
|
||||
.env
|
||||
docs
|
||||
@@ -1,3 +0,0 @@
|
||||
# Override Yarn command so we can automatically setup the repo on running `yarn`
|
||||
|
||||
yarn-path "scripts/bootstrap.js"
|
||||
@@ -1,196 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
|
||||
|
||||
## Development workflow
|
||||
|
||||
To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
|
||||
|
||||
```sh
|
||||
yarn
|
||||
```
|
||||
|
||||
> While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development.
|
||||
|
||||
While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app.
|
||||
|
||||
To start the packager:
|
||||
|
||||
```sh
|
||||
yarn example start
|
||||
```
|
||||
|
||||
To run the example app on Android:
|
||||
|
||||
```sh
|
||||
yarn example android
|
||||
```
|
||||
|
||||
To run the example app on iOS:
|
||||
|
||||
```sh
|
||||
yarn example ios
|
||||
```
|
||||
|
||||
Make sure your code passes TypeScript and ESLint. Run the following to verify:
|
||||
|
||||
```sh
|
||||
yarn typescript
|
||||
yarn lint
|
||||
```
|
||||
|
||||
To fix formatting errors, run the following:
|
||||
|
||||
```sh
|
||||
yarn lint --fix
|
||||
```
|
||||
|
||||
Remember to add tests for your change if possible. Run the unit tests by:
|
||||
|
||||
```sh
|
||||
yarn test
|
||||
```
|
||||
|
||||
To edit the Objective-C files, open `example/ios/SafXExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-saf-x`.
|
||||
|
||||
To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativesafx` under `Android`.
|
||||
|
||||
### Commit message convention
|
||||
|
||||
We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
|
||||
|
||||
- `fix`: bug fixes, e.g. fix crash due to deprecated method.
|
||||
- `feat`: new features, e.g. add new method to the module.
|
||||
- `refactor`: code refactor, e.g. migrate from class components to hooks.
|
||||
- `docs`: changes into documentation, e.g. add usage example for the module..
|
||||
- `test`: adding or updating tests, e.g. add integration tests using detox.
|
||||
- `chore`: tooling changes, e.g. change CI config.
|
||||
|
||||
Our pre-commit hooks verify that your commit message matches this format when committing.
|
||||
|
||||
### Linting and tests
|
||||
|
||||
[ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
|
||||
|
||||
We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
|
||||
|
||||
Our pre-commit hooks verify that the linter and tests pass when committing.
|
||||
|
||||
### Publishing to npm
|
||||
|
||||
We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
|
||||
|
||||
To publish new versions, run the following:
|
||||
|
||||
```sh
|
||||
yarn release
|
||||
```
|
||||
|
||||
### Scripts
|
||||
|
||||
The `package.json` file contains various scripts for common tasks:
|
||||
|
||||
- `yarn bootstrap`: setup project by installing all dependencies and pods.
|
||||
- `yarn typescript`: type-check files with TypeScript.
|
||||
- `yarn lint`: lint files with ESLint.
|
||||
- `yarn test`: run unit tests with Jest.
|
||||
- `yarn example start`: start the Metro server for the example app.
|
||||
- `yarn example android`: run the example app on Android.
|
||||
- `yarn example ios`: run the example app on iOS.
|
||||
|
||||
### Sending a pull request
|
||||
|
||||
> **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
|
||||
|
||||
When you're sending a pull request:
|
||||
|
||||
- Prefer small pull requests focused on one change.
|
||||
- Verify that linters and tests are passing.
|
||||
- Review the documentation to make sure it looks good.
|
||||
- Follow the pull request template when opening a pull request.
|
||||
- For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
### Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
### Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
### Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||
|
||||
### Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||
|
||||
### Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
### Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
#### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
#### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||
|
||||
#### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||
|
||||
#### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||
|
||||
### Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
||||
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Javad Mnjd
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,563 +0,0 @@
|
||||
# react-native-saf-x
|
||||
|
||||
<a href="https://www.npmjs.com/package/react-native-saf-x" target="_blank">
|
||||
<img src="https://img.shields.io/npm/v/react-native-saf-x?color=green"/>
|
||||
</a>
|
||||
|
||||
A module to help simplify usage of scoped storages on android.
|
||||
|
||||
intended to use when targeting Android API level 30+
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install react-native-saf-x
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```sh
|
||||
yarn add react-native-saf-x
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
After receiving a content uri using `openDocumentTree` function,
|
||||
you can use this as if like it's a normal path like we are used to.
|
||||
This is the intended behaviour,
|
||||
if you find any problems or if something does not behave as intended,
|
||||
please create an issue.
|
||||
|
||||
Note that each method can reject when there's an unexpected error or when the permission is revoked.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
import { openDocumentTree, mkdir } from "react-native-saf-x";
|
||||
|
||||
// somewhere in the app .....
|
||||
|
||||
async function testIt() {
|
||||
const doc = await openDocumentTree(true);
|
||||
if (doc && doc.uri) {
|
||||
// user has selected a directory and uri is available
|
||||
// you can save this uri as base directory in your app and reuse it anywhere you want
|
||||
await mkdir(doc.uri + '/foo/bar'); // creates foo/bar folder and subfolder at selected directory
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
For more examples look at example folder in the source.
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Type aliases](#type-aliases)
|
||||
- [Functions](#functions)
|
||||
- [Caveats](#caveats)
|
||||
- [Thanks to](#thanks-to)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
|
||||
### Type aliases
|
||||
|
||||
- [CreateDocumentOptions](#createdocumentoptions)
|
||||
- [DocumentFileDetail](#documentfiledetail)
|
||||
- [Encoding](#encoding)
|
||||
- [FileOperationOptions](#fileoperationoptions)
|
||||
|
||||
### Functions
|
||||
|
||||
- [copyFile](#copyfile)
|
||||
- [createDocument](#createdocument)
|
||||
- [createFile](#createfile)
|
||||
- [exists](#exists)
|
||||
- [getPersistedUriPermissions](#getpersisteduripermissions)
|
||||
- [hasPermission](#haspermission)
|
||||
- [listFiles](#listfiles)
|
||||
- [mkdir](#mkdir)
|
||||
- [moveFile](#movefile)
|
||||
- [openDocument](#opendocument)
|
||||
- [openDocumentTree](#opendocumenttree)
|
||||
- [readFile](#readfile)
|
||||
- [releasePersistableUriPermission](#releasepersistableuripermission)
|
||||
- [rename](#rename)
|
||||
- [stat](#stat)
|
||||
- [unlink](#unlink)
|
||||
- [writeFile](#writefile)
|
||||
|
||||
## Type aliases
|
||||
|
||||
### CreateDocumentOptions
|
||||
|
||||
Ƭ **CreateDocumentOptions**: [`FileOperationOptions`](#fileoperationoptions) & { `initialName?`: `string` }
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:80](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L80)
|
||||
|
||||
___
|
||||
|
||||
### DocumentFileDetail
|
||||
|
||||
Ƭ **DocumentFileDetail**: `Object`
|
||||
|
||||
#### Type declaration
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `lastModified` | `number` |
|
||||
| `mime?` | `string` |
|
||||
| `name` | `string` |
|
||||
| `size?` | `number` |
|
||||
| `type` | ``"directory"`` \| ``"file"`` |
|
||||
| `uri` | `string` |
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:60](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L60)
|
||||
|
||||
___
|
||||
|
||||
### Encoding
|
||||
|
||||
Ƭ **Encoding**: ``"utf8"`` \| ``"base64"`` \| ``"ascii"``
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:22](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L22)
|
||||
|
||||
___
|
||||
|
||||
### FileOperationOptions
|
||||
|
||||
Ƭ **FileOperationOptions**: `Object`
|
||||
|
||||
#### Type declaration
|
||||
|
||||
| Name | Type | Description |
|
||||
| :------ | :------ | :------ |
|
||||
| `append?` | `boolean` | Append data to the file. If not set file content will be overwritten. |
|
||||
| `encoding?` | [`Encoding`](#encoding) | Defaults to `'utf8'` |
|
||||
| `mimeType?` | `string` | mime type of the file being saved. Defaults to '\*\/\*' |
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:69](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L69)
|
||||
|
||||
## Functions
|
||||
|
||||
### copyFile
|
||||
|
||||
▸ **copyFile**(`srcUri`, `destUri`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Copy file from source uri to destination uri.
|
||||
promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
|
||||
Does not support moving directories.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `srcUri` | `string` |
|
||||
| `destUri` | `string` |
|
||||
| `options?` | `FileTransferOptions` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:214](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L214)
|
||||
|
||||
___
|
||||
|
||||
### createDocument
|
||||
|
||||
▸ **createDocument**(`data`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Open the Document Picker to save a file.
|
||||
Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `data` | `string` |
|
||||
| `options?` | [`CreateDocumentOptions`](#createdocumentoptions) |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:105](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L105)
|
||||
|
||||
___
|
||||
|
||||
### createFile
|
||||
|
||||
▸ **createFile**(`uriString`, `options?`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Creates an empty file at given uri.
|
||||
Rejects if a file or directory exist at given uri.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
| `options?` | `Pick`<[`FileOperationOptions`](#fileoperationoptions), ``"mimeType"``\> |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:150](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L150)
|
||||
|
||||
___
|
||||
|
||||
### exists
|
||||
|
||||
▸ **exists**(`uriString`): `Promise`<`boolean`\>
|
||||
|
||||
Check if there's a document located at the given uri.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`boolean`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:117](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L117)
|
||||
|
||||
___
|
||||
|
||||
### getPersistedUriPermissions
|
||||
|
||||
▸ **getPersistedUriPermissions**(): `Promise`<`string`[]\>
|
||||
|
||||
Returns a list of all the persisted uri permissions.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`string`[]\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:186](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L186)
|
||||
|
||||
___
|
||||
|
||||
### hasPermission
|
||||
|
||||
▸ **hasPermission**(`uriString`): `Promise`<`boolean`\>
|
||||
|
||||
Check if you have permission to access the uri.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`boolean`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:112](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L112)
|
||||
|
||||
___
|
||||
|
||||
### listFiles
|
||||
|
||||
▸ **listFiles**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)[]\>
|
||||
|
||||
List all files and folders in a directory uri.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`DocumentFileDetail`](#documentfiledetail)[]\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:196](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L196)
|
||||
|
||||
___
|
||||
|
||||
### mkdir
|
||||
|
||||
▸ **mkdir**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Create a directory at given uri.
|
||||
Automatically creates folders in path if needed.
|
||||
You can use it to create nested directories easily.
|
||||
Rejects if it fails.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:172](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L172)
|
||||
|
||||
___
|
||||
|
||||
### moveFile
|
||||
|
||||
▸ **moveFile**(`srcUri`, `destUri`, `options?`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Move file from source uri to destination uri.
|
||||
promise Rejects if destination already exists and `replaceIfDestinationExists` option is not set to true.
|
||||
Does not support moving directories.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `srcUri` | `string` |
|
||||
| `destUri` | `string` |
|
||||
| `options?` | `FileTransferOptions` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:229](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L229)
|
||||
|
||||
___
|
||||
|
||||
### openDocument
|
||||
|
||||
▸ **openDocument**(`persist`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Open the Document Picker to select a file.
|
||||
Returns an object of type `DocumentFileDetail` or `null` if user did not select a file.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `persist` | `boolean` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:97](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L97)
|
||||
|
||||
___
|
||||
|
||||
### openDocumentTree
|
||||
|
||||
▸ **openDocumentTree**(`persist`): `Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Open the Document Picker to select a folder. Read/Write Permission will be granted to the selected folder.
|
||||
Returns an object of type `DocumentFileDetail` or `null` if user did not select a folder.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `persist` | `boolean` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<``null`` \| [`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:89](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L89)
|
||||
|
||||
___
|
||||
|
||||
### readFile
|
||||
|
||||
▸ **readFile**(`uriString`, `options?`): `Promise`<`string`\>
|
||||
|
||||
Read contents of the given uri. uri must point to a file.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
| `options?` | `Pick`<[`FileOperationOptions`](#fileoperationoptions), ``"encoding"``\> |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`string`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:122](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L122)
|
||||
|
||||
___
|
||||
|
||||
### releasePersistableUriPermission
|
||||
|
||||
▸ **releasePersistableUriPermission**(`uriString`): `Promise`<`void`\>
|
||||
|
||||
Remove a uri from persisted uri permissions list.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`void`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:191](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L191)
|
||||
|
||||
___
|
||||
|
||||
### rename
|
||||
|
||||
▸ **rename**(`uriString`, `newName`): `Promise`<`boolean`\>
|
||||
|
||||
Renames the document at given uri.
|
||||
uri can be file or folder.
|
||||
Resolves with `true` if successful and `false` otherwise.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
| `newName` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`boolean`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:181](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L181)
|
||||
|
||||
___
|
||||
|
||||
### stat
|
||||
|
||||
▸ **stat**(`uriString`): `Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
Get details for a file/directory at given uri.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`DocumentFileDetail`](#documentfiledetail)\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:201](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L201)
|
||||
|
||||
___
|
||||
|
||||
### unlink
|
||||
|
||||
▸ **unlink**(`uriString`): `Promise`<`boolean`\>
|
||||
|
||||
Removes the file or directory at given uri.
|
||||
Resolves with `true` if delete is successful, `false` otherwise.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`boolean`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:162](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L162)
|
||||
|
||||
___
|
||||
|
||||
### writeFile
|
||||
|
||||
▸ **writeFile**(`uriString`, `data`, `options?`): `Promise`<`string`\>
|
||||
|
||||
Writes the given data to the file at given uri.
|
||||
Tries to create the file if does not already exist before writing to it.
|
||||
Resolves with given uriString if successful.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type |
|
||||
| :------ | :------ |
|
||||
| `uriString` | `string` |
|
||||
| `data` | `string` |
|
||||
| `options?` | [`FileOperationOptions`](#fileoperationoptions) |
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`string`\>
|
||||
|
||||
#### Defined in
|
||||
|
||||
[index.tsx:136](https://github.com/jd1378/react-native-saf-x/blob/e0f8106/src/index.tsx#L136)
|
||||
|
||||
## Caveats
|
||||
|
||||
Due to simplyifing the uri structure usage, file and directories should not have the same name at a given uri.
|
||||
doing so can cause unexpected results.
|
||||
for example in a folder named "foo", do not create "bar" file and "bar" directory making the uri being "foo/bar" for both cases.
|
||||
|
||||
___
|
||||
|
||||
## Thanks to
|
||||
|
||||
- [ammarahm-ed](https://github.com/ammarahm-ed) for his work on [react-native-scoped-storage](https://github.com/ammarahm-ed/react-native-scoped-storage)
|
||||
which helped me jump start this module.
|
||||
|
||||
## Contributing
|
||||
|
||||
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,60 +0,0 @@
|
||||
buildscript {
|
||||
if (project == rootProject) {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
jcenter()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:4.2.2'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
def safeExtGet(prop, fallback) {
|
||||
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion safeExtGet('SafX_compileSdkVersion', 30)
|
||||
defaultConfig {
|
||||
minSdkVersion safeExtGet('SafX_minSdkVersion', 21)
|
||||
targetSdkVersion safeExtGet('SafX_targetSdkVersion', 30)
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
}
|
||||
}
|
||||
lintOptions {
|
||||
disable 'GradleCompatible'
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven {
|
||||
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
|
||||
url("$rootDir/../node_modules/react-native/android")
|
||||
}
|
||||
google()
|
||||
mavenCentral()
|
||||
jcenter()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
//noinspection GradleDynamicVersion
|
||||
implementation "com.facebook.react:react-native:+" // From node_modules
|
||||
implementation 'androidx.documentfile:documentfile:1.0.1'
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
android.useAndroidX=true
|
||||
185
packages/react-native-saf-x/android/gradlew
vendored
185
packages/react-native-saf-x/android/gradlew
vendored
@@ -1,185 +0,0 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
89
packages/react-native-saf-x/android/gradlew.bat
vendored
89
packages/react-native-saf-x/android/gradlew.bat
vendored
@@ -1,89 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1,4 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.reactnativesafx">
|
||||
|
||||
</manifest>
|
||||
@@ -1,55 +0,0 @@
|
||||
package androidx.documentfile.provider;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.DocumentsContract;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.reactnativesafx.SafXModule;
|
||||
|
||||
public class DocumentFileHelper {
|
||||
|
||||
// https://www.reddit.com/r/androiddev/comments/orytnx/fixing_treedocumentfilefindfile_lousy_performance/
|
||||
@Nullable
|
||||
public static DocumentFile findFile(
|
||||
Context context, @NonNull DocumentFile documentFile, @NonNull String displayName) {
|
||||
|
||||
if (!(documentFile instanceof TreeDocumentFile)) {
|
||||
return documentFile.findFile(displayName);
|
||||
}
|
||||
|
||||
final ContentResolver resolver = context.getContentResolver();
|
||||
final Uri childrenUri =
|
||||
DocumentsContract.buildChildDocumentsUriUsingTree(
|
||||
documentFile.getUri(), DocumentsContract.getDocumentId(documentFile.getUri()));
|
||||
|
||||
try (Cursor c =
|
||||
resolver.query(
|
||||
childrenUri,
|
||||
new String[] {
|
||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||
},
|
||||
null,
|
||||
null,
|
||||
null)) {
|
||||
if (c != null) {
|
||||
while (c.moveToNext()) {
|
||||
if (displayName.equals(c.getString(1))) {
|
||||
return new TreeDocumentFile(
|
||||
documentFile,
|
||||
context,
|
||||
DocumentsContract.buildDocumentUriUsingTree(documentFile.getUri(), c.getString(0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(SafXModule.NAME, "query failed: " + e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
package com.reactnativesafx;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build.VERSION_CODES;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
import com.facebook.react.bridge.Arguments;
|
||||
import com.facebook.react.bridge.Promise;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
||||
import com.facebook.react.bridge.ReactMethod;
|
||||
import com.facebook.react.bridge.WritableArray;
|
||||
import com.facebook.react.bridge.WritableMap;
|
||||
import com.facebook.react.module.annotations.ReactModule;
|
||||
import com.reactnativesafx.utils.DocumentHelper;
|
||||
import com.reactnativesafx.utils.GeneralHelper;
|
||||
import com.reactnativesafx.utils.UriHelper;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Arrays;
|
||||
|
||||
@RequiresApi(api = VERSION_CODES.Q)
|
||||
@ReactModule(name = SafXModule.NAME)
|
||||
public class SafXModule extends ReactContextBaseJavaModule {
|
||||
public static final String NAME = "SafX";
|
||||
private final DocumentHelper documentHelper;
|
||||
|
||||
public SafXModule(ReactApplicationContext reactContext) {
|
||||
super(reactContext);
|
||||
this.documentHelper = new DocumentHelper(reactContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String getName() {
|
||||
return NAME;
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void openDocumentTree(final boolean persist, final Promise promise) {
|
||||
this.documentHelper.openDocumentTree(persist, promise);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void openDocument(final boolean persist, final Promise promise) {
|
||||
this.documentHelper.openDocument(persist, promise);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void createDocument(
|
||||
final String data,
|
||||
final String encoding,
|
||||
final String initialName,
|
||||
final String mimeType,
|
||||
final Promise promise) {
|
||||
this.documentHelper.createDocument(data, encoding, initialName, mimeType, promise);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void hasPermission(String uriString, final Promise promise) {
|
||||
if (this.documentHelper.hasPermission(uriString)) {
|
||||
promise.resolve(true);
|
||||
} else {
|
||||
promise.resolve(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void exists(String uriString, final Promise promise) {
|
||||
try {
|
||||
promise.resolve(this.documentHelper.exists(uriString));
|
||||
} catch (Exception e) {
|
||||
promise.reject("ERROR", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void readFile(String uriString, String encoding, final Promise promise) {
|
||||
try {
|
||||
DocumentFile file;
|
||||
|
||||
try {
|
||||
file = this.documentHelper.goToDocument(uriString, false, true);
|
||||
} catch (FileNotFoundException e) {
|
||||
promise.reject("ENOENT", "'" + uriString + "' does not exist");
|
||||
return;
|
||||
}
|
||||
if (encoding != null) {
|
||||
if (encoding.equals("ascii")) {
|
||||
WritableArray arr =
|
||||
(WritableArray) this.documentHelper.readFromUri(file.getUri(), encoding);
|
||||
promise.resolve((arr));
|
||||
} else {
|
||||
promise.resolve(this.documentHelper.readFromUri(file.getUri(), encoding));
|
||||
}
|
||||
} else {
|
||||
promise.resolve(this.documentHelper.readFromUri(file.getUri(), "utf8"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void writeFile(
|
||||
String uriString,
|
||||
String data,
|
||||
String encoding,
|
||||
String mimeType,
|
||||
boolean append,
|
||||
final Promise promise) {
|
||||
try {
|
||||
DocumentFile file;
|
||||
|
||||
try {
|
||||
file = this.documentHelper.goToDocument(uriString, false, true);
|
||||
} catch (FileNotFoundException e) {
|
||||
file = this.documentHelper.createFile(uriString, mimeType);
|
||||
}
|
||||
|
||||
byte[] bytes = GeneralHelper.stringToBytes(data, encoding);
|
||||
|
||||
try (OutputStream fout =
|
||||
this.getReactApplicationContext()
|
||||
.getContentResolver()
|
||||
.openOutputStream(file.getUri(), append ? "wa" : "wt")) {
|
||||
fout.write(bytes);
|
||||
}
|
||||
|
||||
promise.resolve(uriString);
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void transferFile(
|
||||
String srcUri, String destUri, boolean replaceIfDestExists, boolean copy, Promise promise) {
|
||||
this.documentHelper.transferFile(srcUri, destUri, replaceIfDestExists, copy, promise);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void rename(String uriString, String newName, final Promise promise) {
|
||||
try {
|
||||
|
||||
DocumentFile doc;
|
||||
try {
|
||||
doc = this.documentHelper.goToDocument(uriString, false, true);
|
||||
} catch (FileNotFoundException e) {
|
||||
promise.reject("ENOENT", "'" + uriString + "' does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
if (doc.renameTo(newName)) {
|
||||
promise.resolve(true);
|
||||
} else {
|
||||
promise.resolve(false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void unlink(String uriString, final Promise promise) {
|
||||
try {
|
||||
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
|
||||
boolean result = doc.delete();
|
||||
promise.resolve(result);
|
||||
} catch (FileNotFoundException e) {
|
||||
promise.reject("ENOENT", e.getLocalizedMessage());
|
||||
} catch (SecurityException e) {
|
||||
promise.reject("EPERM", e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void mkdir(String uriString, final Promise promise) {
|
||||
try {
|
||||
DocumentFile dir = this.documentHelper.mkdir(uriString);
|
||||
DocumentHelper.resolveWithDocument(dir, promise, uriString);
|
||||
} catch (IOException e) {
|
||||
promise.reject("EEXIST", e.getLocalizedMessage());
|
||||
} catch (SecurityException e) {
|
||||
promise.reject("EPERM", e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void createFile(String uriString, String mimeType, final Promise promise) {
|
||||
try {
|
||||
DocumentFile createdFile = this.documentHelper.createFile(uriString, mimeType);
|
||||
DocumentHelper.resolveWithDocument(createdFile, promise, uriString);
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void getPersistedUriPermissions(final Promise promise) {
|
||||
String[] uriList =
|
||||
getReactApplicationContext().getContentResolver().getPersistedUriPermissions().stream()
|
||||
.map(uriPermission -> uriPermission.getUri().toString())
|
||||
.toArray(String[]::new);
|
||||
|
||||
WritableArray wa = Arguments.fromArray(uriList);
|
||||
promise.resolve(wa);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void releasePersistableUriPermission(String uriString, final Promise promise) {
|
||||
Uri uriToRevoke = Uri.parse(UriHelper.normalize(uriString));
|
||||
final int takeFlags =
|
||||
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||
this.getReactApplicationContext()
|
||||
.getContentResolver()
|
||||
.releasePersistableUriPermission(uriToRevoke, takeFlags);
|
||||
promise.resolve(null);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void listFiles(String uriString, final Promise promise) {
|
||||
try {
|
||||
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
|
||||
|
||||
WritableMap[] resolvedDocs =
|
||||
Arrays.stream(doc.listFiles())
|
||||
.map(
|
||||
docEntry ->
|
||||
DocumentHelper.resolveWithDocument(
|
||||
docEntry, null, uriString + "/" + docEntry.getName()))
|
||||
.toArray(WritableMap[]::new);
|
||||
WritableArray resolveData = Arguments.fromJavaArgs(resolvedDocs);
|
||||
promise.resolve(resolveData);
|
||||
} catch (FileNotFoundException e) {
|
||||
promise.reject("ENOENT", e.getLocalizedMessage());
|
||||
} catch (SecurityException e) {
|
||||
promise.reject("EPERM", e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void stat(String uriString, final Promise promise) {
|
||||
try {
|
||||
DocumentFile doc = this.documentHelper.goToDocument(uriString, false, true);
|
||||
|
||||
DocumentHelper.resolveWithDocument(doc, promise, uriString);
|
||||
} catch (FileNotFoundException e) {
|
||||
promise.reject("ENOENT", e.getLocalizedMessage());
|
||||
} catch (SecurityException e) {
|
||||
promise.reject("EPERM", e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.reactnativesafx;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.facebook.react.ReactPackage;
|
||||
import com.facebook.react.bridge.NativeModule;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.uimanager.ViewManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class SafXPackage implements ReactPackage {
|
||||
@NonNull
|
||||
@Override
|
||||
public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
|
||||
List<NativeModule> modules = new ArrayList<>();
|
||||
modules.add(new SafXModule(reactContext));
|
||||
return modules;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
package com.reactnativesafx.utils;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.content.UriPermission;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Build.VERSION_CODES;
|
||||
import android.util.Base64;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
import androidx.documentfile.provider.DocumentFileHelper;
|
||||
import com.facebook.react.bridge.ActivityEventListener;
|
||||
import com.facebook.react.bridge.Arguments;
|
||||
import com.facebook.react.bridge.Promise;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.WritableArray;
|
||||
import com.facebook.react.bridge.WritableMap;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.List;
|
||||
|
||||
@RequiresApi(api = VERSION_CODES.Q)
|
||||
public class DocumentHelper {
|
||||
|
||||
private static final int DOCUMENT_TREE_REQUEST_CODE = 1;
|
||||
private static final int DOCUMENT_REQUEST_CODE = 2;
|
||||
private static final int DOCUMENT_CREATE_CODE = 3;
|
||||
|
||||
private final ReactApplicationContext context;
|
||||
private ActivityEventListener activityEventListener;
|
||||
|
||||
public DocumentHelper(ReactApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public void openDocumentTree(final boolean persist, final Promise promise) {
|
||||
try {
|
||||
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE);
|
||||
|
||||
if (activityEventListener != null) {
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
activityEventListener =
|
||||
new ActivityEventListener() {
|
||||
@SuppressLint("WrongConstant")
|
||||
@Override
|
||||
public void onActivityResult(
|
||||
Activity activity, int requestCode, int resultCode, Intent intent) {
|
||||
if (requestCode == DOCUMENT_TREE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
|
||||
if (intent != null) {
|
||||
Uri uri = intent.getData();
|
||||
if (persist) {
|
||||
final int takeFlags =
|
||||
intent.getFlags()
|
||||
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||
|
||||
context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentFile doc = goToDocument(uri.toString(), false);
|
||||
resolveWithDocument(doc, promise, uri.toString());
|
||||
} catch (Exception e) {
|
||||
promise.resolve(null);
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {}
|
||||
};
|
||||
|
||||
context.addActivityEventListener(activityEventListener);
|
||||
|
||||
Activity activity = context.getCurrentActivity();
|
||||
if (activity != null) {
|
||||
activity.startActivityForResult(intent, DOCUMENT_TREE_REQUEST_CODE);
|
||||
} else {
|
||||
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
promise.reject("ERROR", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void openDocument(final boolean persist, final Promise promise) {
|
||||
try {
|
||||
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("*/*");
|
||||
|
||||
if (activityEventListener != null) {
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
activityEventListener =
|
||||
new ActivityEventListener() {
|
||||
@SuppressLint("WrongConstant")
|
||||
@Override
|
||||
public void onActivityResult(
|
||||
Activity activity, int requestCode, int resultCode, Intent intent) {
|
||||
if (requestCode == DOCUMENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
|
||||
if (intent != null) {
|
||||
Uri uri = intent.getData();
|
||||
if (persist) {
|
||||
final int takeFlags =
|
||||
intent.getFlags()
|
||||
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||
|
||||
context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentFile doc = goToDocument(uri.toString(), false);
|
||||
resolveWithDocument(doc, promise, uri.toString());
|
||||
} catch (Exception e) {
|
||||
promise.resolve(null);
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {}
|
||||
};
|
||||
|
||||
context.addActivityEventListener(activityEventListener);
|
||||
|
||||
Activity activity = context.getCurrentActivity();
|
||||
if (activity != null) {
|
||||
activity.startActivityForResult(intent, DOCUMENT_REQUEST_CODE);
|
||||
} else {
|
||||
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
promise.reject("ERROR", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void createDocument(
|
||||
final String data,
|
||||
final String encoding,
|
||||
final String initialName,
|
||||
final String mimeType,
|
||||
final Promise promise) {
|
||||
try {
|
||||
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(Intent.ACTION_CREATE_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
if (initialName != null) {
|
||||
intent.putExtra(Intent.EXTRA_TITLE, initialName);
|
||||
}
|
||||
if (mimeType != null) {
|
||||
intent.setType(mimeType);
|
||||
} else {
|
||||
intent.setType("*/*");
|
||||
}
|
||||
|
||||
if (activityEventListener != null) {
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
activityEventListener =
|
||||
new ActivityEventListener() {
|
||||
@Override
|
||||
public void onActivityResult(
|
||||
Activity activity, int requestCode, int resultCode, Intent intent) {
|
||||
|
||||
if (requestCode == DOCUMENT_CREATE_CODE && resultCode == Activity.RESULT_OK) {
|
||||
if (intent != null) {
|
||||
Uri uri = intent.getData();
|
||||
|
||||
DocumentFile doc = DocumentFile.fromSingleUri(context, uri);
|
||||
|
||||
try {
|
||||
byte[] bytes = GeneralHelper.stringToBytes(data, encoding);
|
||||
try (OutputStream os = context.getContentResolver().openOutputStream(uri)) {
|
||||
os.write(bytes);
|
||||
}
|
||||
assert doc != null;
|
||||
resolveWithDocument(doc, promise, uri.toString());
|
||||
} catch (Exception e) {
|
||||
promise.reject("ERROR", e.getLocalizedMessage());
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
} else {
|
||||
promise.resolve(null);
|
||||
}
|
||||
|
||||
context.removeActivityEventListener(activityEventListener);
|
||||
activityEventListener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewIntent(Intent intent) {}
|
||||
};
|
||||
|
||||
context.addActivityEventListener(activityEventListener);
|
||||
|
||||
Activity activity = context.getCurrentActivity();
|
||||
if (activity != null) {
|
||||
activity.startActivityForResult(intent, DOCUMENT_CREATE_CODE);
|
||||
} else {
|
||||
promise.reject("ERROR", "Cannot get current activity, so cannot launch document picker");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
promise.reject("ERROR", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.Q)
|
||||
@SuppressWarnings({"UnusedDeclaration", "UnusedAssignment"})
|
||||
public Object readFromUri(Uri uri, String encoding) throws IOException {
|
||||
byte[] bytes;
|
||||
int bytesRead;
|
||||
int length;
|
||||
|
||||
InputStream inputStream = context.getContentResolver().openInputStream(uri);
|
||||
|
||||
length = inputStream.available();
|
||||
bytes = new byte[length];
|
||||
bytesRead = inputStream.read(bytes);
|
||||
inputStream.close();
|
||||
|
||||
switch (encoding.toLowerCase()) {
|
||||
case "base64":
|
||||
return Base64.encodeToString(bytes, Base64.NO_WRAP);
|
||||
case "ascii":
|
||||
WritableArray asciiResult = Arguments.createArray();
|
||||
for (byte b : bytes) {
|
||||
asciiResult.pushInt(b);
|
||||
}
|
||||
return asciiResult;
|
||||
case "utf8":
|
||||
default:
|
||||
return new String(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean exists(final String uriString) {
|
||||
return this.exists(uriString, false);
|
||||
}
|
||||
|
||||
public boolean exists(final String uriString, final boolean shouldBeFile) {
|
||||
try {
|
||||
DocumentFile fileOrFolder = goToDocument(uriString, false);
|
||||
if (shouldBeFile) {
|
||||
return !fileOrFolder.isDirectory();
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasPermission(String uriString) {
|
||||
// list of all persisted permissions for our app
|
||||
List<UriPermission> uriList = context.getContentResolver().getPersistedUriPermissions();
|
||||
for (UriPermission uriPermission : uriList) {
|
||||
if (permissionMatchesAndHasAccess(uriPermission, UriHelper.normalize(uriString))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean permissionMatchesAndHasAccess(
|
||||
UriPermission permission, String normalizedUriString) {
|
||||
String permittedUri = permission.getUri().toString();
|
||||
return (permittedUri.startsWith(normalizedUriString)
|
||||
|| normalizedUriString.startsWith(permittedUri))
|
||||
&& permission.isReadPermission()
|
||||
&& permission.isWritePermission();
|
||||
}
|
||||
|
||||
private String getPermissionErrorMsg(final String uriString) {
|
||||
return "You don't have read/write permission to access uri: " + uriString;
|
||||
}
|
||||
|
||||
public static WritableMap resolveWithDocument(
|
||||
@NonNull DocumentFile file, Promise promise, String SimplifiedUri) {
|
||||
WritableMap fileMap = Arguments.createMap();
|
||||
fileMap.putString("uri", UriHelper.denormalize(SimplifiedUri));
|
||||
fileMap.putString("name", file.getName());
|
||||
fileMap.putString("type", file.isDirectory() ? "directory" : "file");
|
||||
if (file.isFile()) {
|
||||
fileMap.putString("mime", file.getType());
|
||||
fileMap.putDouble("size", file.length());
|
||||
}
|
||||
fileMap.putDouble("lastModified", file.lastModified());
|
||||
|
||||
if (promise != null) {
|
||||
promise.resolve(fileMap);
|
||||
}
|
||||
return fileMap;
|
||||
}
|
||||
|
||||
public DocumentFile mkdir(String uriString)
|
||||
throws IOException, SecurityException, IllegalArgumentException {
|
||||
return this.mkdir(uriString, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a DocumentFile that is created using DocumentFile.fromTreeUri()
|
||||
*/
|
||||
public DocumentFile mkdir(String uriString, boolean includeLastSegment)
|
||||
throws IOException, SecurityException, IllegalArgumentException {
|
||||
DocumentFile dir = goToDocument(uriString, true, includeLastSegment);
|
||||
assert dir != null;
|
||||
return dir;
|
||||
}
|
||||
|
||||
public DocumentFile createFile(String uriString) throws IOException, SecurityException {
|
||||
return createFile(uriString, null);
|
||||
}
|
||||
|
||||
public DocumentFile createFile(String uriString, String mimeType)
|
||||
throws IOException, SecurityException {
|
||||
if (this.exists(uriString)) {
|
||||
throw new IOException("a file or directory already exist at: " + uriString);
|
||||
}
|
||||
DocumentFile parentDirOfFile = this.mkdir(uriString, false);
|
||||
// it should be safe because user cannot select sd root or primary root
|
||||
// and any other path would have at least one '/' to provide a file name in a folder
|
||||
String fileName = UriHelper.getLastSegment(uriString);
|
||||
if (fileName.indexOf(':') != -1) {
|
||||
throw new IOException(
|
||||
"Invalid file name: Could not extract filename from uri string provided");
|
||||
}
|
||||
DocumentFile createdFile =
|
||||
parentDirOfFile.createFile(
|
||||
mimeType != null && !mimeType.equals("") ? mimeType : "*/*", fileName);
|
||||
if (createdFile == null) {
|
||||
throw new IOException(
|
||||
"File creation failed without any specific error for '" + fileName + "'");
|
||||
}
|
||||
return createdFile;
|
||||
}
|
||||
|
||||
public DocumentFile goToDocument(String uriString, boolean createIfDirectoryNotExist)
|
||||
throws SecurityException, IOException {
|
||||
return goToDocument(uriString, createIfDirectoryNotExist, true);
|
||||
}
|
||||
|
||||
public DocumentFile goToDocument(
|
||||
String unknownUriString, boolean createIfDirectoryNotExist, boolean includeLastSegment)
|
||||
throws SecurityException, IOException {
|
||||
String uriString = UriHelper.normalize(unknownUriString);
|
||||
String baseUri = "";
|
||||
String appendUri;
|
||||
String[] strings = new String[0];
|
||||
|
||||
List<UriPermission> uriList = context.getContentResolver().getPersistedUriPermissions();
|
||||
|
||||
for (UriPermission uriPermission : uriList) {
|
||||
String uriPath = uriPermission.getUri().toString();
|
||||
if (this.permissionMatchesAndHasAccess(uriPermission, uriString)) {
|
||||
baseUri = uriPath;
|
||||
appendUri = Uri.decode(uriString.substring(uriPath.length()));
|
||||
strings = appendUri.split("/");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (baseUri.equals("")) {
|
||||
throw new SecurityException(getPermissionErrorMsg(uriString));
|
||||
}
|
||||
|
||||
if (baseUri.matches("^content://[\\w.]+/document/.*")) {
|
||||
// It's a document picked by user
|
||||
DocumentFile doc = DocumentFile.fromSingleUri(context, Uri.parse(uriString));
|
||||
if (doc != null && doc.isFile() && doc.exists()) {
|
||||
return doc;
|
||||
} else {
|
||||
throw new FileNotFoundException(
|
||||
"Cannot find the given document. File does not exist at '" + uriString + "'");
|
||||
}
|
||||
}
|
||||
|
||||
Uri uri = Uri.parse(baseUri);
|
||||
DocumentFile dir = DocumentFile.fromTreeUri(context, uri);
|
||||
|
||||
int pathSegmentsToTraverseLength = includeLastSegment ? strings.length : strings.length - 1;
|
||||
for (int i = 0; i < pathSegmentsToTraverseLength; i++) {
|
||||
if (!strings[i].equals("")) {
|
||||
assert dir != null;
|
||||
DocumentFile childDoc = DocumentFileHelper.findFile(context, dir, strings[i]);
|
||||
if (childDoc != null) {
|
||||
if (childDoc.isDirectory()) {
|
||||
dir = childDoc;
|
||||
} else if (i == pathSegmentsToTraverseLength - 1) {
|
||||
// we are at the last part to traverse, its our destination, doesn't matter if its a
|
||||
// file or directory
|
||||
dir = childDoc;
|
||||
} else {
|
||||
// child doc is a file
|
||||
throw new IOException(
|
||||
"There's a document with the same name as the one we are trying to traverse at: '"
|
||||
+ childDoc.getUri()
|
||||
+ "'");
|
||||
}
|
||||
} else {
|
||||
if (createIfDirectoryNotExist) {
|
||||
dir = dir.createDirectory(strings[i]);
|
||||
} else {
|
||||
throw new FileNotFoundException(
|
||||
"Cannot traverse to the pointed document. Directory '"
|
||||
+ strings[i]
|
||||
+ "'"
|
||||
+ " does not exist in '"
|
||||
+ dir.getUri()
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert dir != null;
|
||||
return dir;
|
||||
}
|
||||
|
||||
public void transferFile(
|
||||
String srcUri, String destUri, boolean replaceIfDestExists, boolean copy, Promise promise) {
|
||||
try {
|
||||
DocumentFile srcDoc = this.goToDocument(srcUri, false, true);
|
||||
|
||||
if (srcDoc.isDirectory()) {
|
||||
throw new IllegalArgumentException("Cannot move directories");
|
||||
}
|
||||
|
||||
DocumentFile destDoc;
|
||||
try {
|
||||
destDoc = this.goToDocument(destUri, false, true);
|
||||
if (!replaceIfDestExists) {
|
||||
throw new IOException("a document with the same name already exists in destination");
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
destDoc = this.createFile(destUri, srcDoc.getType());
|
||||
}
|
||||
|
||||
try (InputStream inStream =
|
||||
this.context.getContentResolver().openInputStream(srcDoc.getUri());
|
||||
OutputStream outStream =
|
||||
this.context.getContentResolver().openOutputStream(destDoc.getUri(), "wt"); ) {
|
||||
byte[] buffer = new byte[1024 * 4];
|
||||
int length;
|
||||
while ((length = inStream.read(buffer)) > 0) {
|
||||
outStream.write(buffer, 0, length);
|
||||
}
|
||||
}
|
||||
|
||||
if (!copy) {
|
||||
srcDoc.delete();
|
||||
}
|
||||
|
||||
promise.resolve(resolveWithDocument(destDoc, promise, destUri));
|
||||
} catch (Exception e) {
|
||||
promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.reactnativesafx.utils;
|
||||
|
||||
import android.util.Base64;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class GeneralHelper {
|
||||
/**
|
||||
* String to byte converter method
|
||||
*
|
||||
* @param data Raw data in string format
|
||||
* @param encoding Decoder name
|
||||
* @return Converted data byte array
|
||||
*/
|
||||
public static byte[] stringToBytes(String data, String encoding) {
|
||||
if (encoding != null) {
|
||||
if (encoding.equalsIgnoreCase("ascii")) {
|
||||
return data.getBytes(StandardCharsets.US_ASCII);
|
||||
} else if (encoding.toLowerCase().contains("base64")) {
|
||||
return Base64.decode(data, Base64.NO_WRAP);
|
||||
} else if (encoding.equalsIgnoreCase("utf8")) {
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.reactnativesafx.utils;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.os.Build.VERSION_CODES;
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
@RequiresApi(api = VERSION_CODES.Q)
|
||||
public class UriHelper {
|
||||
public static final String CONTENT_URI_PREFIX = "content://";
|
||||
|
||||
public static String getLastSegment(String uriString) {
|
||||
|
||||
return Uri.parse(Uri.decode(uriString)).getLastPathSegment();
|
||||
}
|
||||
|
||||
public static String normalize(String uriString) {
|
||||
// an abnormal uri example:
|
||||
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin/locks/2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
|
||||
// normalized:
|
||||
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin%2Flocks%2F2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
|
||||
|
||||
// uri parts:
|
||||
|
||||
String[] parts = Uri.decode(uriString).split(":");
|
||||
return parts[0] + ":" + parts[1] + Uri.encode(":" + parts[2]);
|
||||
}
|
||||
|
||||
public static String denormalize(String uriString) {
|
||||
// an normalized uri example:
|
||||
// content://com.android.externalstorage.documents/tree/1707-3F0B%3Ajoplin%2Flocks%2F2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
|
||||
// denormalized:
|
||||
// content://com.android.externalstorage.documents/tree/1707-3F0B/Ajoplin/locks/2_2_fa4f9801e9a545a58f1a6c5d3a7cfded.json
|
||||
|
||||
return Uri.decode(normalize(uriString));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user