This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
outline/app/components/Editor/changes.js
Tom Moor e64ca3ca43 Cleanup
2017-12-05 22:29:07 -08:00

77 lines
1.9 KiB
JavaScript

// @flow
import { Change } from 'slate';
import uuid from 'uuid';
import EditList from './plugins/EditList';
import uploadFile from 'utils/uploadFile';
const { changes } = EditList;
type Options = {
type: string | Object,
wrapper?: string | Object,
};
export function splitAndInsertBlock(change: Change, options: Options) {
const { type, wrapper } = options;
const parent = change.value.document.getParent(change.value.startBlock.key);
// lists get some special treatment
if (parent && parent.type === 'list-item') {
change
.collapseToStart()
.call(changes.splitListItem)
.collapseToEndOfPreviousBlock()
.call(changes.unwrapList);
}
change.insertBlock(type);
if (wrapper) change.wrapBlock(wrapper);
return change;
}
export async function insertImageFile(
change: Change,
file: window.File,
onImageUploadStart: () => void,
onImageUploadStop: () => void
) {
onImageUploadStart();
try {
// load the file as a data URL
const id = uuid.v4();
const alt = '';
const reader = new FileReader();
reader.addEventListener('load', () => {
const src = reader.result;
// insert into document as uploading placeholder
change.insertBlock({
type: 'image',
isVoid: true,
data: { src, id, alt, loading: true },
});
});
reader.readAsDataURL(file);
// now we have a placeholder, start the upload
const asset = await uploadFile(file);
const src = asset.url;
// we dont use the original change provided to the callback here
// as the state may have changed significantly in the time it took to
// upload the file.
const placeholder = change.value.document.findDescendant(
node => node.data && node.data.get('id') === id
);
return change.setNodeByKey(placeholder.key, {
data: { src, alt, loading: false },
});
} catch (err) {
throw err;
} finally {
onImageUploadStop();
}
}