1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2025-04-06 18:56:56 +00:00

chore: add dependencies

This commit is contained in:
linonetwo 2025-03-23 21:54:57 +08:00
parent cec30f9ed2
commit 685520aa88
14 changed files with 5031 additions and 15 deletions

View File

@ -0,0 +1,31 @@
'use strict';
function crelt() {
var elt = arguments[0];
if (typeof elt == "string") elt = document.createElement(elt);
var i = 1, next = arguments[1];
if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
var value = next[name];
if (typeof value == "string") elt.setAttribute(name, value);
else if (value != null) elt[name] = value;
}
i++;
}
for (; i < arguments.length; i++) add(elt, arguments[i]);
return elt
}
function add(elt, child) {
if (typeof child == "string") {
elt.appendChild(document.createTextNode(child));
} else if (child == null) ; else if (child.nodeType != null) {
elt.appendChild(child);
} else if (Array.isArray(child)) {
for (var i = 0; i < child.length; i++) add(elt, child[i]);
} else {
throw new RangeError("Unsupported child node: " + child)
}
}
module.exports = crelt;

View File

@ -0,0 +1,139 @@
'use strict';
// ::- Persistent data structure representing an ordered mapping from
// strings to values, with some convenient update methods.
function OrderedMap(content) {
this.content = content;
}
OrderedMap.prototype = {
constructor: OrderedMap,
find: function(key) {
for (var i = 0; i < this.content.length; i += 2)
if (this.content[i] === key) return i
return -1
},
// :: (string) → ?any
// Retrieve the value stored under `key`, or return undefined when
// no such key exists.
get: function(key) {
var found = this.find(key);
return found == -1 ? undefined : this.content[found + 1]
},
// :: (string, any, ?string) → OrderedMap
// Create a new map by replacing the value of `key` with a new
// value, or adding a binding to the end of the map. If `newKey` is
// given, the key of the binding will be replaced with that key.
update: function(key, value, newKey) {
var self = newKey && newKey != key ? this.remove(newKey) : this;
var found = self.find(key), content = self.content.slice();
if (found == -1) {
content.push(newKey || key, value);
} else {
content[found + 1] = value;
if (newKey) content[found] = newKey;
}
return new OrderedMap(content)
},
// :: (string) → OrderedMap
// Return a map with the given key removed, if it existed.
remove: function(key) {
var found = this.find(key);
if (found == -1) return this
var content = this.content.slice();
content.splice(found, 2);
return new OrderedMap(content)
},
// :: (string, any) → OrderedMap
// Add a new key to the start of the map.
addToStart: function(key, value) {
return new OrderedMap([key, value].concat(this.remove(key).content))
},
// :: (string, any) → OrderedMap
// Add a new key to the end of the map.
addToEnd: function(key, value) {
var content = this.remove(key).content.slice();
content.push(key, value);
return new OrderedMap(content)
},
// :: (string, string, any) → OrderedMap
// Add a key after the given key. If `place` is not found, the new
// key is added to the end.
addBefore: function(place, key, value) {
var without = this.remove(key), content = without.content.slice();
var found = without.find(place);
content.splice(found == -1 ? content.length : found, 0, key, value);
return new OrderedMap(content)
},
// :: ((key: string, value: any))
// Call the given function for each key/value pair in the map, in
// order.
forEach: function(f) {
for (var i = 0; i < this.content.length; i += 2)
f(this.content[i], this.content[i + 1]);
},
// :: (union<Object, OrderedMap>) → OrderedMap
// Create a new map by prepending the keys in this map that don't
// appear in `map` before the keys in `map`.
prepend: function(map) {
map = OrderedMap.from(map);
if (!map.size) return this
return new OrderedMap(map.content.concat(this.subtract(map).content))
},
// :: (union<Object, OrderedMap>) → OrderedMap
// Create a new map by appending the keys in this map that don't
// appear in `map` after the keys in `map`.
append: function(map) {
map = OrderedMap.from(map);
if (!map.size) return this
return new OrderedMap(this.subtract(map).content.concat(map.content))
},
// :: (union<Object, OrderedMap>) → OrderedMap
// Create a map containing all the keys in this map that don't
// appear in `map`.
subtract: function(map) {
var result = this;
map = OrderedMap.from(map);
for (var i = 0; i < map.content.length; i += 2)
result = result.remove(map.content[i]);
return result
},
// :: () → Object
// Turn ordered map into a plain object.
toObject: function() {
var result = {};
this.forEach(function(key, value) { result[key] = value; });
return result
},
// :: number
// The amount of keys in this map.
get size() {
return this.content.length >> 1
}
};
// :: (?union<Object, OrderedMap>) → OrderedMap
// Return a map with the given content. If null, create an empty
// map. If given an ordered map, return that map itself. If given an
// object, create a map from the object's properties.
OrderedMap.from = function(value) {
if (value instanceof OrderedMap) return value
var content = [];
if (value) for (var prop in value) content.push(prop, value[prop]);
return new OrderedMap(content)
};
module.exports = OrderedMap;

View File

@ -0,0 +1,686 @@
'use strict';
var prosemirrorTransform = require('prosemirror-transform');
var prosemirrorModel = require('prosemirror-model');
var prosemirrorState = require('prosemirror-state');
var deleteSelection = function deleteSelection(state, dispatch) {
if (state.selection.empty) return false;
if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView());
return true;
};
function atBlockStart(state, view) {
var $cursor = state.selection.$cursor;
if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) return null;
return $cursor;
}
var joinBackward = function joinBackward(state, dispatch, view) {
var $cursor = atBlockStart(state, view);
if (!$cursor) return false;
var $cut = findCutBefore($cursor);
if (!$cut) {
var range = $cursor.blockRange(),
target = range && prosemirrorTransform.liftTarget(range);
if (target == null) return false;
if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
return true;
}
var before = $cut.nodeBefore;
if (deleteBarrier(state, $cut, dispatch, -1)) return true;
if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || prosemirrorState.NodeSelection.isSelectable(before))) {
for (var depth = $cursor.depth;; depth--) {
var delStep = prosemirrorTransform.replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), prosemirrorModel.Slice.empty);
if (delStep && delStep.slice.size < delStep.to - delStep.from) {
if (dispatch) {
var tr = state.tr.step(delStep);
tr.setSelection(textblockAt(before, "end") ? prosemirrorState.Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : prosemirrorState.NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));
dispatch(tr.scrollIntoView());
}
return true;
}
if (depth == 1 || $cursor.node(depth - 1).childCount > 1) break;
}
}
if (before.isAtom && $cut.depth == $cursor.depth - 1) {
if (dispatch) dispatch(state.tr["delete"]($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
return true;
}
return false;
};
var joinTextblockBackward = function joinTextblockBackward(state, dispatch, view) {
var $cursor = atBlockStart(state, view);
if (!$cursor) return false;
var $cut = findCutBefore($cursor);
return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
var joinTextblockForward = function joinTextblockForward(state, dispatch, view) {
var $cursor = atBlockEnd(state, view);
if (!$cursor) return false;
var $cut = findCutAfter($cursor);
return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
function joinTextblocksAround(state, $cut, dispatch) {
var before = $cut.nodeBefore,
beforeText = before,
beforePos = $cut.pos - 1;
for (; !beforeText.isTextblock; beforePos--) {
if (beforeText.type.spec.isolating) return false;
var child = beforeText.lastChild;
if (!child) return false;
beforeText = child;
}
var after = $cut.nodeAfter,
afterText = after,
afterPos = $cut.pos + 1;
for (; !afterText.isTextblock; afterPos++) {
if (afterText.type.spec.isolating) return false;
var _child = afterText.firstChild;
if (!_child) return false;
afterText = _child;
}
var step = prosemirrorTransform.replaceStep(state.doc, beforePos, afterPos, prosemirrorModel.Slice.empty);
if (!step || step.from != beforePos || step instanceof prosemirrorTransform.ReplaceStep && step.slice.size >= afterPos - beforePos) return false;
if (dispatch) {
var tr = state.tr.step(step);
tr.setSelection(prosemirrorState.TextSelection.create(tr.doc, beforePos));
dispatch(tr.scrollIntoView());
}
return true;
}
function textblockAt(node, side) {
var only = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
for (var scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
if (scan.isTextblock) return true;
if (only && scan.childCount != 1) return false;
}
return false;
}
var selectNodeBackward = function selectNodeBackward(state, dispatch, view) {
var _state$selection = state.selection,
$head = _state$selection.$head,
empty = _state$selection.empty,
$cut = $head;
if (!empty) return false;
if ($head.parent.isTextblock) {
if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) return false;
$cut = findCutBefore($head);
}
var node = $cut && $cut.nodeBefore;
if (!node || !prosemirrorState.NodeSelection.isSelectable(node)) return false;
if (dispatch) dispatch(state.tr.setSelection(prosemirrorState.NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
return true;
};
function findCutBefore($pos) {
if (!$pos.parent.type.spec.isolating) for (var i = $pos.depth - 1; i >= 0; i--) {
if ($pos.index(i) > 0) return $pos.doc.resolve($pos.before(i + 1));
if ($pos.node(i).type.spec.isolating) break;
}
return null;
}
function atBlockEnd(state, view) {
var $cursor = state.selection.$cursor;
if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) return null;
return $cursor;
}
var joinForward = function joinForward(state, dispatch, view) {
var $cursor = atBlockEnd(state, view);
if (!$cursor) return false;
var $cut = findCutAfter($cursor);
if (!$cut) return false;
var after = $cut.nodeAfter;
if (deleteBarrier(state, $cut, dispatch, 1)) return true;
if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || prosemirrorState.NodeSelection.isSelectable(after))) {
var delStep = prosemirrorTransform.replaceStep(state.doc, $cursor.before(), $cursor.after(), prosemirrorModel.Slice.empty);
if (delStep && delStep.slice.size < delStep.to - delStep.from) {
if (dispatch) {
var tr = state.tr.step(delStep);
tr.setSelection(textblockAt(after, "start") ? prosemirrorState.Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : prosemirrorState.NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));
dispatch(tr.scrollIntoView());
}
return true;
}
}
if (after.isAtom && $cut.depth == $cursor.depth - 1) {
if (dispatch) dispatch(state.tr["delete"]($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
return true;
}
return false;
};
var selectNodeForward = function selectNodeForward(state, dispatch, view) {
var _state$selection2 = state.selection,
$head = _state$selection2.$head,
empty = _state$selection2.empty,
$cut = $head;
if (!empty) return false;
if ($head.parent.isTextblock) {
if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) return false;
$cut = findCutAfter($head);
}
var node = $cut && $cut.nodeAfter;
if (!node || !prosemirrorState.NodeSelection.isSelectable(node)) return false;
if (dispatch) dispatch(state.tr.setSelection(prosemirrorState.NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
return true;
};
function findCutAfter($pos) {
if (!$pos.parent.type.spec.isolating) for (var i = $pos.depth - 1; i >= 0; i--) {
var parent = $pos.node(i);
if ($pos.index(i) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i + 1));
if (parent.type.spec.isolating) break;
}
return null;
}
var joinUp = function joinUp(state, dispatch) {
var sel = state.selection,
nodeSel = sel instanceof prosemirrorState.NodeSelection,
point;
if (nodeSel) {
if (sel.node.isTextblock || !prosemirrorTransform.canJoin(state.doc, sel.from)) return false;
point = sel.from;
} else {
point = prosemirrorTransform.joinPoint(state.doc, sel.from, -1);
if (point == null) return false;
}
if (dispatch) {
var tr = state.tr.join(point);
if (nodeSel) tr.setSelection(prosemirrorState.NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
dispatch(tr.scrollIntoView());
}
return true;
};
var joinDown = function joinDown(state, dispatch) {
var sel = state.selection,
point;
if (sel instanceof prosemirrorState.NodeSelection) {
if (sel.node.isTextblock || !prosemirrorTransform.canJoin(state.doc, sel.to)) return false;
point = sel.to;
} else {
point = prosemirrorTransform.joinPoint(state.doc, sel.to, 1);
if (point == null) return false;
}
if (dispatch) dispatch(state.tr.join(point).scrollIntoView());
return true;
};
var lift = function lift(state, dispatch) {
var _state$selection3 = state.selection,
$from = _state$selection3.$from,
$to = _state$selection3.$to;
var range = $from.blockRange($to),
target = range && prosemirrorTransform.liftTarget(range);
if (target == null) return false;
if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
return true;
};
var newlineInCode = function newlineInCode(state, dispatch) {
var _state$selection4 = state.selection,
$head = _state$selection4.$head,
$anchor = _state$selection4.$anchor;
if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;
if (dispatch) dispatch(state.tr.insertText("\n").scrollIntoView());
return true;
};
function defaultBlockAt(match) {
for (var i = 0; i < match.edgeCount; i++) {
var _match$edge = match.edge(i),
type = _match$edge.type;
if (type.isTextblock && !type.hasRequiredAttrs()) return type;
}
return null;
}
var exitCode = function exitCode(state, dispatch) {
var _state$selection5 = state.selection,
$head = _state$selection5.$head,
$anchor = _state$selection5.$anchor;
if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;
var above = $head.node(-1),
after = $head.indexAfter(-1),
type = defaultBlockAt(above.contentMatchAt(after));
if (!type || !above.canReplaceWith(after, after, type)) return false;
if (dispatch) {
var pos = $head.after(),
tr = state.tr.replaceWith(pos, pos, type.createAndFill());
tr.setSelection(prosemirrorState.Selection.near(tr.doc.resolve(pos), 1));
dispatch(tr.scrollIntoView());
}
return true;
};
var createParagraphNear = function createParagraphNear(state, dispatch) {
var sel = state.selection,
$from = sel.$from,
$to = sel.$to;
if (sel instanceof prosemirrorState.AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) return false;
var type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
if (!type || !type.isTextblock) return false;
if (dispatch) {
var side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
var tr = state.tr.insert(side, type.createAndFill());
tr.setSelection(prosemirrorState.TextSelection.create(tr.doc, side + 1));
dispatch(tr.scrollIntoView());
}
return true;
};
var liftEmptyBlock = function liftEmptyBlock(state, dispatch) {
var $cursor = state.selection.$cursor;
if (!$cursor || $cursor.parent.content.size) return false;
if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
var before = $cursor.before();
if (prosemirrorTransform.canSplit(state.doc, before)) {
if (dispatch) dispatch(state.tr.split(before).scrollIntoView());
return true;
}
}
var range = $cursor.blockRange(),
target = range && prosemirrorTransform.liftTarget(range);
if (target == null) return false;
if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
return true;
};
function splitBlockAs(splitNode) {
return function (state, dispatch) {
var _state$selection6 = state.selection,
$from = _state$selection6.$from,
$to = _state$selection6.$to;
if (state.selection instanceof prosemirrorState.NodeSelection && state.selection.node.isBlock) {
if (!$from.parentOffset || !prosemirrorTransform.canSplit(state.doc, $from.pos)) return false;
if (dispatch) dispatch(state.tr.split($from.pos).scrollIntoView());
return true;
}
if (!$from.depth) return false;
var types = [];
var splitDepth,
deflt,
atEnd = false,
atStart = false;
for (var d = $from.depth;; d--) {
var node = $from.node(d);
if (node.isBlock) {
atEnd = $from.end(d) == $from.pos + ($from.depth - d);
atStart = $from.start(d) == $from.pos - ($from.depth - d);
deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));
var splitType = splitNode && splitNode($to.parent, atEnd, $from);
types.unshift(splitType || (atEnd && deflt ? {
type: deflt
} : null));
splitDepth = d;
break;
} else {
if (d == 1) return false;
types.unshift(null);
}
}
var tr = state.tr;
if (state.selection instanceof prosemirrorState.TextSelection || state.selection instanceof prosemirrorState.AllSelection) tr.deleteSelection();
var splitPos = tr.mapping.map($from.pos);
var can = prosemirrorTransform.canSplit(tr.doc, splitPos, types.length, types);
if (!can) {
types[0] = deflt ? {
type: deflt
} : null;
can = prosemirrorTransform.canSplit(tr.doc, splitPos, types.length, types);
}
tr.split(splitPos, types.length, types);
if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
var first = tr.mapping.map($from.before(splitDepth)),
$first = tr.doc.resolve(first);
if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);
}
if (dispatch) dispatch(tr.scrollIntoView());
return true;
};
}
var splitBlock = splitBlockAs();
var splitBlockKeepMarks = function splitBlockKeepMarks(state, dispatch) {
return splitBlock(state, dispatch && function (tr) {
var marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
if (marks) tr.ensureMarks(marks);
dispatch(tr);
});
};
var selectParentNode = function selectParentNode(state, dispatch) {
var _state$selection7 = state.selection,
$from = _state$selection7.$from,
to = _state$selection7.to,
pos;
var same = $from.sharedDepth(to);
if (same == 0) return false;
pos = $from.before(same);
if (dispatch) dispatch(state.tr.setSelection(prosemirrorState.NodeSelection.create(state.doc, pos)));
return true;
};
var selectAll = function selectAll(state, dispatch) {
if (dispatch) dispatch(state.tr.setSelection(new prosemirrorState.AllSelection(state.doc)));
return true;
};
function joinMaybeClear(state, $pos, dispatch) {
var before = $pos.nodeBefore,
after = $pos.nodeAfter,
index = $pos.index();
if (!before || !after || !before.type.compatibleContent(after.type)) return false;
if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {
if (dispatch) dispatch(state.tr["delete"]($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
return true;
}
if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || prosemirrorTransform.canJoin(state.doc, $pos.pos))) return false;
if (dispatch) dispatch(state.tr.join($pos.pos).scrollIntoView());
return true;
}
function deleteBarrier(state, $cut, dispatch, dir) {
var before = $cut.nodeBefore,
after = $cut.nodeAfter,
conn,
match;
var isolated = before.type.spec.isolating || after.type.spec.isolating;
if (!isolated && joinMaybeClear(state, $cut, dispatch)) return true;
var canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) {
if (dispatch) {
var end = $cut.pos + after.nodeSize,
wrap = prosemirrorModel.Fragment.empty;
for (var i = conn.length - 1; i >= 0; i--) wrap = prosemirrorModel.Fragment.from(conn[i].create(null, wrap));
wrap = prosemirrorModel.Fragment.from(before.copy(wrap));
var tr = state.tr.step(new prosemirrorTransform.ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new prosemirrorModel.Slice(wrap, 1, 0), conn.length, true));
var $joinAt = tr.doc.resolve(end + 2 * conn.length);
if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && prosemirrorTransform.canJoin(tr.doc, $joinAt.pos)) tr.join($joinAt.pos);
dispatch(tr.scrollIntoView());
}
return true;
}
var selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : prosemirrorState.Selection.findFrom($cut, 1);
var range = selAfter && selAfter.$from.blockRange(selAfter.$to),
target = range && prosemirrorTransform.liftTarget(range);
if (target != null && target >= $cut.depth) {
if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());
return true;
}
if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
var at = before,
_wrap = [];
for (;;) {
_wrap.push(at);
if (at.isTextblock) break;
at = at.lastChild;
}
var afterText = after,
afterDepth = 1;
for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++;
if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
if (dispatch) {
var _end = prosemirrorModel.Fragment.empty;
for (var _i = _wrap.length - 1; _i >= 0; _i--) _end = prosemirrorModel.Fragment.from(_wrap[_i].copy(_end));
var _tr = state.tr.step(new prosemirrorTransform.ReplaceAroundStep($cut.pos - _wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new prosemirrorModel.Slice(_end, _wrap.length, 0), 0, true));
dispatch(_tr.scrollIntoView());
}
return true;
}
}
return false;
}
function selectTextblockSide(side) {
return function (state, dispatch) {
var sel = state.selection,
$pos = side < 0 ? sel.$from : sel.$to;
var depth = $pos.depth;
while ($pos.node(depth).isInline) {
if (!depth) return false;
depth--;
}
if (!$pos.node(depth).isTextblock) return false;
if (dispatch) dispatch(state.tr.setSelection(prosemirrorState.TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
return true;
};
}
var selectTextblockStart = selectTextblockSide(-1);
var selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType) {
var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return function (state, dispatch) {
var _state$selection8 = state.selection,
$from = _state$selection8.$from,
$to = _state$selection8.$to;
var range = $from.blockRange($to),
wrapping = range && prosemirrorTransform.findWrapping(range, nodeType, attrs);
if (!wrapping) return false;
if (dispatch) dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
return true;
};
}
function setBlockType(nodeType) {
var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return function (state, dispatch) {
var applicable = false;
for (var i = 0; i < state.selection.ranges.length && !applicable; i++) {
var _state$selection$rang = state.selection.ranges[i],
from = _state$selection$rang.$from.pos,
to = _state$selection$rang.$to.pos;
state.doc.nodesBetween(from, to, function (node, pos) {
if (applicable) return false;
if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) return;
if (node.type == nodeType) {
applicable = true;
} else {
var $pos = state.doc.resolve(pos),
index = $pos.index();
applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
}
});
}
if (!applicable) return false;
if (dispatch) {
var tr = state.tr;
for (var _i2 = 0; _i2 < state.selection.ranges.length; _i2++) {
var _state$selection$rang2 = state.selection.ranges[_i2],
_from = _state$selection$rang2.$from.pos,
_to = _state$selection$rang2.$to.pos;
tr.setBlockType(_from, _to, nodeType, attrs);
}
dispatch(tr.scrollIntoView());
}
return true;
};
}
function markApplies(doc, ranges, type, enterAtoms) {
var _loop = function _loop() {
var _ranges$i = ranges[i],
$from = _ranges$i.$from,
$to = _ranges$i.$to;
var can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;
doc.nodesBetween($from.pos, $to.pos, function (node, pos) {
if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) return false;
can = node.inlineContent && node.type.allowsMarkType(type);
});
if (can) return {
v: true
};
},
_ret;
for (var i = 0; i < ranges.length; i++) {
_ret = _loop();
if (_ret) return _ret.v;
}
return false;
}
function removeInlineAtoms(ranges) {
var result = [];
var _loop2 = function _loop2() {
var _ranges$i2 = ranges[i],
$from = _ranges$i2.$from,
$to = _ranges$i2.$to;
$from.doc.nodesBetween($from.pos, $to.pos, function (node, pos) {
if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {
if (pos + 1 > $from.pos) result.push(new prosemirrorState.SelectionRange($from, $from.doc.resolve(pos + 1)));
$from = $from.doc.resolve(pos + 1 + node.content.size);
return false;
}
});
if ($from.pos < $to.pos) result.push(new prosemirrorState.SelectionRange($from, $to));
};
for (var i = 0; i < ranges.length; i++) {
_loop2();
}
return result;
}
function toggleMark(markType) {
var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var options = arguments.length > 2 ? arguments[2] : undefined;
var removeWhenPresent = (options && options.removeWhenPresent) !== false;
var enterAtoms = (options && options.enterInlineAtoms) !== false;
var dropSpace = !(options && options.includeWhitespace);
return function (state, dispatch) {
var _state$selection9 = state.selection,
empty = _state$selection9.empty,
$cursor = _state$selection9.$cursor,
ranges = _state$selection9.ranges;
if (empty && !$cursor || !markApplies(state.doc, ranges, markType, enterAtoms)) return false;
if (dispatch) {
if ($cursor) {
if (markType.isInSet(state.storedMarks || $cursor.marks())) dispatch(state.tr.removeStoredMark(markType));else dispatch(state.tr.addStoredMark(markType.create(attrs)));
} else {
var add,
tr = state.tr;
if (!enterAtoms) ranges = removeInlineAtoms(ranges);
if (removeWhenPresent) {
add = !ranges.some(function (r) {
return state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType);
});
} else {
add = !ranges.every(function (r) {
var missing = false;
tr.doc.nodesBetween(r.$from.pos, r.$to.pos, function (node, pos, parent) {
if (missing) return false;
missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) && !(node.isText && /^\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));
});
return !missing;
});
}
for (var i = 0; i < ranges.length; i++) {
var _ranges$i3 = ranges[i],
$from = _ranges$i3.$from,
$to = _ranges$i3.$to;
if (!add) {
tr.removeMark($from.pos, $to.pos, markType);
} else {
var from = $from.pos,
to = $to.pos,
start = $from.nodeAfter,
end = $to.nodeBefore;
var spaceStart = dropSpace && start && start.isText ? /^\s*/.exec(start.text)[0].length : 0;
var spaceEnd = dropSpace && end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
if (from + spaceStart < to) {
from += spaceStart;
to -= spaceEnd;
}
tr.addMark(from, to, markType.create(attrs));
}
}
dispatch(tr.scrollIntoView());
}
}
return true;
};
}
function wrapDispatchForJoin(dispatch, isJoinable) {
return function (tr) {
if (!tr.isGeneric) return dispatch(tr);
var ranges = [];
for (var i = 0; i < tr.mapping.maps.length; i++) {
var map = tr.mapping.maps[i];
for (var j = 0; j < ranges.length; j++) ranges[j] = map.map(ranges[j]);
map.forEach(function (_s, _e, from, to) {
return ranges.push(from, to);
});
}
var joinable = [];
for (var _i3 = 0; _i3 < ranges.length; _i3 += 2) {
var from = ranges[_i3],
to = ranges[_i3 + 1];
var $from = tr.doc.resolve(from),
depth = $from.sharedDepth(to),
parent = $from.node(depth);
for (var index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {
var after = parent.maybeChild(index);
if (!after) break;
if (index && joinable.indexOf(pos) == -1) {
var before = parent.child(index - 1);
if (before.type == after.type && isJoinable(before, after)) joinable.push(pos);
}
pos += after.nodeSize;
}
}
joinable.sort(function (a, b) {
return a - b;
});
for (var _i4 = joinable.length - 1; _i4 >= 0; _i4--) {
if (prosemirrorTransform.canJoin(tr.doc, joinable[_i4])) tr.join(joinable[_i4]);
}
dispatch(tr);
};
}
function autoJoin(command, isJoinable) {
var canJoin = Array.isArray(isJoinable) ? function (node) {
return isJoinable.indexOf(node.type.name) > -1;
} : isJoinable;
return function (state, dispatch, view) {
return command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);
};
}
function chainCommands() {
for (var _len = arguments.length, commands = new Array(_len), _key = 0; _key < _len; _key++) {
commands[_key] = arguments[_key];
}
return function (state, dispatch, view) {
for (var i = 0; i < commands.length; i++) if (commands[i](state, dispatch, view)) return true;
return false;
};
}
var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
var pcBaseKeymap = {
"Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
"Mod-Enter": exitCode,
"Backspace": backspace,
"Mod-Backspace": backspace,
"Shift-Backspace": backspace,
"Delete": del,
"Mod-Delete": del,
"Mod-a": selectAll
};
var macBaseKeymap = {
"Ctrl-h": pcBaseKeymap["Backspace"],
"Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
"Ctrl-d": pcBaseKeymap["Delete"],
"Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
"Alt-Delete": pcBaseKeymap["Mod-Delete"],
"Alt-d": pcBaseKeymap["Mod-Delete"],
"Ctrl-a": selectTextblockStart,
"Ctrl-e": selectTextblockEnd
};
for (var key in pcBaseKeymap) macBaseKeymap[key] = pcBaseKeymap[key];
var mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
var baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;
exports.autoJoin = autoJoin;
exports.baseKeymap = baseKeymap;
exports.chainCommands = chainCommands;
exports.createParagraphNear = createParagraphNear;
exports.deleteSelection = deleteSelection;
exports.exitCode = exitCode;
exports.joinBackward = joinBackward;
exports.joinDown = joinDown;
exports.joinForward = joinForward;
exports.joinTextblockBackward = joinTextblockBackward;
exports.joinTextblockForward = joinTextblockForward;
exports.joinUp = joinUp;
exports.lift = lift;
exports.liftEmptyBlock = liftEmptyBlock;
exports.macBaseKeymap = macBaseKeymap;
exports.newlineInCode = newlineInCode;
exports.pcBaseKeymap = pcBaseKeymap;
exports.selectAll = selectAll;
exports.selectNodeBackward = selectNodeBackward;
exports.selectNodeForward = selectNodeForward;
exports.selectParentNode = selectParentNode;
exports.selectTextblockEnd = selectTextblockEnd;
exports.selectTextblockStart = selectTextblockStart;
exports.setBlockType = setBlockType;
exports.splitBlock = splitBlock;
exports.splitBlockAs = splitBlockAs;
exports.splitBlockKeepMarks = splitBlockKeepMarks;
exports.toggleMark = toggleMark;
exports.wrapIn = wrapIn;

View File

@ -0,0 +1,208 @@
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
Object.defineProperty(exports, '__esModule', {
value: true
});
var prosemirrorState = require('prosemirror-state');
var prosemirrorTransform = require('prosemirror-transform');
function dropCursor() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return new prosemirrorState.Plugin({
view: function view(editorView) {
return new DropCursorView(editorView, options);
}
});
}
var DropCursorView = function () {
function DropCursorView(editorView, options) {
var _this = this;
_classCallCheck(this, DropCursorView);
var _a;
this.editorView = editorView;
this.cursorPos = null;
this.element = null;
this.timeout = -1;
this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;
this.color = options.color === false ? undefined : options.color || "black";
this["class"] = options["class"];
this.handlers = ["dragover", "dragend", "drop", "dragleave"].map(function (name) {
var handler = function handler(e) {
_this[name](e);
};
editorView.dom.addEventListener(name, handler);
return {
name: name,
handler: handler
};
});
}
_createClass(DropCursorView, [{
key: "destroy",
value: function destroy() {
var _this2 = this;
this.handlers.forEach(function (_ref) {
var name = _ref.name,
handler = _ref.handler;
return _this2.editorView.dom.removeEventListener(name, handler);
});
}
}, {
key: "update",
value: function update(editorView, prevState) {
if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
if (this.cursorPos > editorView.state.doc.content.size) this.setCursor(null);else this.updateOverlay();
}
}
}, {
key: "setCursor",
value: function setCursor(pos) {
if (pos == this.cursorPos) return;
this.cursorPos = pos;
if (pos == null) {
this.element.parentNode.removeChild(this.element);
this.element = null;
} else {
this.updateOverlay();
}
}
}, {
key: "updateOverlay",
value: function updateOverlay() {
var $pos = this.editorView.state.doc.resolve(this.cursorPos);
var isBlock = !$pos.parent.inlineContent,
rect;
if (isBlock) {
var before = $pos.nodeBefore,
after = $pos.nodeAfter;
if (before || after) {
var node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
if (node) {
var nodeRect = node.getBoundingClientRect();
var top = before ? nodeRect.bottom : nodeRect.top;
if (before && after) top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
rect = {
left: nodeRect.left,
right: nodeRect.right,
top: top - this.width / 2,
bottom: top + this.width / 2
};
}
}
}
if (!rect) {
var coords = this.editorView.coordsAtPos(this.cursorPos);
rect = {
left: coords.left - this.width / 2,
right: coords.left + this.width / 2,
top: coords.top,
bottom: coords.bottom
};
}
var parent = this.editorView.dom.offsetParent;
if (!this.element) {
this.element = parent.appendChild(document.createElement("div"));
if (this["class"]) this.element.className = this["class"];
this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;";
if (this.color) {
this.element.style.backgroundColor = this.color;
}
}
this.element.classList.toggle("prosemirror-dropcursor-block", isBlock);
this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock);
var parentLeft, parentTop;
if (!parent || parent == document.body && getComputedStyle(parent).position == "static") {
parentLeft = -pageXOffset;
parentTop = -pageYOffset;
} else {
var _rect = parent.getBoundingClientRect();
parentLeft = _rect.left - parent.scrollLeft;
parentTop = _rect.top - parent.scrollTop;
}
this.element.style.left = rect.left - parentLeft + "px";
this.element.style.top = rect.top - parentTop + "px";
this.element.style.width = rect.right - rect.left + "px";
this.element.style.height = rect.bottom - rect.top + "px";
}
}, {
key: "scheduleRemoval",
value: function scheduleRemoval(timeout) {
var _this3 = this;
clearTimeout(this.timeout);
this.timeout = setTimeout(function () {
return _this3.setCursor(null);
}, timeout);
}
}, {
key: "dragover",
value: function dragover(event) {
if (!this.editorView.editable) return;
var pos = this.editorView.posAtCoords({
left: event.clientX,
top: event.clientY
});
var node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
var disableDropCursor = node && node.type.spec.disableDropCursor;
var disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;
if (pos && !disabled) {
var target = pos.pos;
if (this.editorView.dragging && this.editorView.dragging.slice) {
var point = prosemirrorTransform.dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);
if (point != null) target = point;
}
this.setCursor(target);
this.scheduleRemoval(5000);
}
}
}, {
key: "dragend",
value: function dragend() {
this.scheduleRemoval(20);
}
}, {
key: "drop",
value: function drop() {
this.scheduleRemoval(20);
}
}, {
key: "dragleave",
value: function dragleave(event) {
if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget)) this.setCursor(null);
}
}]);
return DropCursorView;
}();
exports.dropCursor = dropCursor;

View File

@ -0,0 +1,295 @@
'use strict';
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
Object.defineProperty(exports, '__esModule', {
value: true
});
var prosemirrorKeymap = require('prosemirror-keymap');
var prosemirrorState = require('prosemirror-state');
var prosemirrorModel = require('prosemirror-model');
var prosemirrorView = require('prosemirror-view');
var GapCursor = function (_prosemirrorState$Sel) {
_inherits(GapCursor, _prosemirrorState$Sel);
var _super = _createSuper(GapCursor);
function GapCursor($pos) {
_classCallCheck(this, GapCursor);
return _super.call(this, $pos, $pos);
}
_createClass(GapCursor, [{
key: "map",
value: function map(doc, mapping) {
var $pos = doc.resolve(mapping.map(this.head));
return GapCursor.valid($pos) ? new GapCursor($pos) : prosemirrorState.Selection.near($pos);
}
}, {
key: "content",
value: function content() {
return prosemirrorModel.Slice.empty;
}
}, {
key: "eq",
value: function eq(other) {
return other instanceof GapCursor && other.head == this.head;
}
}, {
key: "toJSON",
value: function toJSON() {
return {
type: "gapcursor",
pos: this.head
};
}
}, {
key: "getBookmark",
value: function getBookmark() {
return new GapBookmark(this.anchor);
}
}], [{
key: "fromJSON",
value: function fromJSON(doc, json) {
if (typeof json.pos != "number") throw new RangeError("Invalid input for GapCursor.fromJSON");
return new GapCursor(doc.resolve(json.pos));
}
}, {
key: "valid",
value: function valid($pos) {
var parent = $pos.parent;
if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos)) return false;
var override = parent.type.spec.allowGapCursor;
if (override != null) return override;
var deflt = parent.contentMatchAt($pos.index()).defaultType;
return deflt && deflt.isTextblock;
}
}, {
key: "findGapCursorFrom",
value: function findGapCursorFrom($pos, dir) {
var mustMove = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
search: for (;;) {
if (!mustMove && GapCursor.valid($pos)) return $pos;
var pos = $pos.pos,
next = null;
for (var d = $pos.depth;; d--) {
var parent = $pos.node(d);
if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {
next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);
break;
} else if (d == 0) {
return null;
}
pos += dir;
var $cur = $pos.doc.resolve(pos);
if (GapCursor.valid($cur)) return $cur;
}
for (;;) {
var inside = dir > 0 ? next.firstChild : next.lastChild;
if (!inside) {
if (next.isAtom && !next.isText && !prosemirrorState.NodeSelection.isSelectable(next)) {
$pos = $pos.doc.resolve(pos + next.nodeSize * dir);
mustMove = false;
continue search;
}
break;
}
next = inside;
pos += dir;
var _$cur = $pos.doc.resolve(pos);
if (GapCursor.valid(_$cur)) return _$cur;
}
return null;
}
}
}]);
return GapCursor;
}(prosemirrorState.Selection);
GapCursor.prototype.visible = false;
GapCursor.findFrom = GapCursor.findGapCursorFrom;
prosemirrorState.Selection.jsonID("gapcursor", GapCursor);
var GapBookmark = function () {
function GapBookmark(pos) {
_classCallCheck(this, GapBookmark);
this.pos = pos;
}
_createClass(GapBookmark, [{
key: "map",
value: function map(mapping) {
return new GapBookmark(mapping.map(this.pos));
}
}, {
key: "resolve",
value: function resolve(doc) {
var $pos = doc.resolve(this.pos);
return GapCursor.valid($pos) ? new GapCursor($pos) : prosemirrorState.Selection.near($pos);
}
}]);
return GapBookmark;
}();
function closedBefore($pos) {
for (var d = $pos.depth; d >= 0; d--) {
var index = $pos.index(d),
parent = $pos.node(d);
if (index == 0) {
if (parent.type.spec.isolating) return true;
continue;
}
for (var before = parent.child(index - 1);; before = before.lastChild) {
if (before.childCount == 0 && !before.inlineContent || before.isAtom || before.type.spec.isolating) return true;
if (before.inlineContent) return false;
}
}
return true;
}
function closedAfter($pos) {
for (var d = $pos.depth; d >= 0; d--) {
var index = $pos.indexAfter(d),
parent = $pos.node(d);
if (index == parent.childCount) {
if (parent.type.spec.isolating) return true;
continue;
}
for (var after = parent.child(index);; after = after.firstChild) {
if (after.childCount == 0 && !after.inlineContent || after.isAtom || after.type.spec.isolating) return true;
if (after.inlineContent) return false;
}
}
return true;
}
function gapCursor() {
return new prosemirrorState.Plugin({
props: {
decorations: drawGapCursor,
createSelectionBetween: function createSelectionBetween(_view, $anchor, $head) {
return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;
},
handleClick: handleClick,
handleKeyDown: handleKeyDown,
handleDOMEvents: {
beforeinput: beforeinput
}
}
});
}
var handleKeyDown = prosemirrorKeymap.keydownHandler({
"ArrowLeft": arrow("horiz", -1),
"ArrowRight": arrow("horiz", 1),
"ArrowUp": arrow("vert", -1),
"ArrowDown": arrow("vert", 1)
});
function arrow(axis, dir) {
var dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
return function (state, dispatch, view) {
var sel = state.selection;
var $start = dir > 0 ? sel.$to : sel.$from,
mustMove = sel.empty;
if (sel instanceof prosemirrorState.TextSelection) {
if (!view.endOfTextblock(dirStr) || $start.depth == 0) return false;
mustMove = false;
$start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
}
var $found = GapCursor.findGapCursorFrom($start, dir, mustMove);
if (!$found) return false;
if (dispatch) dispatch(state.tr.setSelection(new GapCursor($found)));
return true;
};
}
function handleClick(view, pos, event) {
if (!view || !view.editable) return false;
var $pos = view.state.doc.resolve(pos);
if (!GapCursor.valid($pos)) return false;
var clickPos = view.posAtCoords({
left: event.clientX,
top: event.clientY
});
if (clickPos && clickPos.inside > -1 && prosemirrorState.NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside))) return false;
view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
return true;
}
function beforeinput(view, event) {
if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor)) return false;
var $from = view.state.selection.$from;
var insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);
if (!insert) return false;
var frag = prosemirrorModel.Fragment.empty;
for (var i = insert.length - 1; i >= 0; i--) {
frag = prosemirrorModel.Fragment.from(insert[i].createAndFill(null, frag));
}
var tr = view.state.tr.replace($from.pos, $from.pos, new prosemirrorModel.Slice(frag, 0, 0));
tr.setSelection(prosemirrorState.TextSelection.near(tr.doc.resolve($from.pos + 1)));
view.dispatch(tr);
return false;
}
function drawGapCursor(state) {
if (!(state.selection instanceof GapCursor)) return null;
var node = document.createElement("div");
node.className = "ProseMirror-gapcursor";
return prosemirrorView.DecorationSet.create(state.doc, [prosemirrorView.Decoration.widget(state.selection.head, node, {
key: "gapcursor"
})]);
}
exports.GapCursor = GapCursor;
exports.gapCursor = gapCursor;

View File

@ -0,0 +1,378 @@
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var RopeSequence = require('rope-sequence');
var prosemirrorTransform = require('prosemirror-transform');
var prosemirrorState = require('prosemirror-state');
var max_empty_items = 500;
var Branch = function () {
function Branch(items, eventCount) {
_classCallCheck(this, Branch);
this.items = items;
this.eventCount = eventCount;
}
_createClass(Branch, [{
key: "popEvent",
value: function popEvent(state, preserveItems) {
var _this = this;
if (this.eventCount == 0) return null;
var end = this.items.length;
for (;; end--) {
var next = this.items.get(end - 1);
if (next.selection) {
--end;
break;
}
}
var remap, mapFrom;
if (preserveItems) {
remap = this.remapping(end, this.items.length);
mapFrom = remap.maps.length;
}
var transform = state.tr;
var selection, remaining;
var addAfter = [],
addBefore = [];
this.items.forEach(function (item, i) {
if (!item.step) {
if (!remap) {
remap = _this.remapping(end, i + 1);
mapFrom = remap.maps.length;
}
mapFrom--;
addBefore.push(item);
return;
}
if (remap) {
addBefore.push(new Item(item.map));
var step = item.step.map(remap.slice(mapFrom)),
map;
if (step && transform.maybeStep(step).doc) {
map = transform.mapping.maps[transform.mapping.maps.length - 1];
addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));
}
mapFrom--;
if (map) remap.appendMap(map, mapFrom);
} else {
transform.maybeStep(item.step);
}
if (item.selection) {
selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
remaining = new Branch(_this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), _this.eventCount - 1);
return false;
}
}, this.items.length, 0);
return {
remaining: remaining,
transform: transform,
selection: selection
};
}
}, {
key: "addTransform",
value: function addTransform(transform, selection, histOptions, preserveItems) {
var newItems = [],
eventCount = this.eventCount;
var oldItems = this.items,
lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
for (var i = 0; i < transform.steps.length; i++) {
var step = transform.steps[i].invert(transform.docs[i]);
var item = new Item(transform.mapping.maps[i], step, selection),
merged = void 0;
if (merged = lastItem && lastItem.merge(item)) {
item = merged;
if (i) newItems.pop();else oldItems = oldItems.slice(0, oldItems.length - 1);
}
newItems.push(item);
if (selection) {
eventCount++;
selection = undefined;
}
if (!preserveItems) lastItem = item;
}
var overflow = eventCount - histOptions.depth;
if (overflow > DEPTH_OVERFLOW) {
oldItems = cutOffEvents(oldItems, overflow);
eventCount -= overflow;
}
return new Branch(oldItems.append(newItems), eventCount);
}
}, {
key: "remapping",
value: function remapping(from, to) {
var maps = new prosemirrorTransform.Mapping();
this.items.forEach(function (item, i) {
var mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : undefined;
maps.appendMap(item.map, mirrorPos);
}, from, to);
return maps;
}
}, {
key: "addMaps",
value: function addMaps(array) {
if (this.eventCount == 0) return this;
return new Branch(this.items.append(array.map(function (map) {
return new Item(map);
})), this.eventCount);
}
}, {
key: "rebased",
value: function rebased(rebasedTransform, rebasedCount) {
if (!this.eventCount) return this;
var rebasedItems = [],
start = Math.max(0, this.items.length - rebasedCount);
var mapping = rebasedTransform.mapping;
var newUntil = rebasedTransform.steps.length;
var eventCount = this.eventCount;
this.items.forEach(function (item) {
if (item.selection) eventCount--;
}, start);
var iRebased = rebasedCount;
this.items.forEach(function (item) {
var pos = mapping.getMirror(--iRebased);
if (pos == null) return;
newUntil = Math.min(newUntil, pos);
var map = mapping.maps[pos];
if (item.step) {
var step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
var selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
if (selection) eventCount++;
rebasedItems.push(new Item(map, step, selection));
} else {
rebasedItems.push(new Item(map));
}
}, start);
var newMaps = [];
for (var i = rebasedCount; i < newUntil; i++) newMaps.push(new Item(mapping.maps[i]));
var items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
var branch = new Branch(items, eventCount);
if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length);
return branch;
}
}, {
key: "emptyItemCount",
value: function emptyItemCount() {
var count = 0;
this.items.forEach(function (item) {
if (!item.step) count++;
});
return count;
}
}, {
key: "compress",
value: function compress() {
var upto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.items.length;
var remap = this.remapping(0, upto),
mapFrom = remap.maps.length;
var items = [],
events = 0;
this.items.forEach(function (item, i) {
if (i >= upto) {
items.push(item);
if (item.selection) events++;
} else if (item.step) {
var step = item.step.map(remap.slice(mapFrom)),
map = step && step.getMap();
mapFrom--;
if (map) remap.appendMap(map, mapFrom);
if (step) {
var selection = item.selection && item.selection.map(remap.slice(mapFrom));
if (selection) events++;
var newItem = new Item(map.invert(), step, selection),
merged,
last = items.length - 1;
if (merged = items.length && items[last].merge(newItem)) items[last] = merged;else items.push(newItem);
}
} else if (item.map) {
mapFrom--;
}
}, this.items.length, 0);
return new Branch(RopeSequence.from(items.reverse()), events);
}
}]);
return Branch;
}();
Branch.empty = new Branch(RopeSequence.empty, 0);
function cutOffEvents(items, n) {
var cutPoint;
items.forEach(function (item, i) {
if (item.selection && n-- == 0) {
cutPoint = i;
return false;
}
});
return items.slice(cutPoint);
}
var Item = function () {
function Item(map, step, selection, mirrorOffset) {
_classCallCheck(this, Item);
this.map = map;
this.step = step;
this.selection = selection;
this.mirrorOffset = mirrorOffset;
}
_createClass(Item, [{
key: "merge",
value: function merge(other) {
if (this.step && other.step && !other.selection) {
var step = other.step.merge(this.step);
if (step) return new Item(step.getMap().invert(), step, this.selection);
}
}
}]);
return Item;
}();
var HistoryState = _createClass(function HistoryState(done, undone, prevRanges, prevTime, prevComposition) {
_classCallCheck(this, HistoryState);
this.done = done;
this.undone = undone;
this.prevRanges = prevRanges;
this.prevTime = prevTime;
this.prevComposition = prevComposition;
});
var DEPTH_OVERFLOW = 20;
function applyTransaction(history, state, tr, options) {
var historyTr = tr.getMeta(historyKey),
rebased;
if (historyTr) return historyTr.historyState;
if (tr.getMeta(closeHistoryKey)) history = new HistoryState(history.done, history.undone, null, 0, -1);
var appended = tr.getMeta("appendedTransaction");
if (tr.steps.length == 0) {
return history;
} else if (appended && appended.getMeta(historyKey)) {
if (appended.getMeta(historyKey).redo) return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);else return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);
} else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
var composition = tr.getMeta("composition");
var newGroup = history.prevTime == 0 || !appended && history.prevComposition != composition && (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges));
var prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);
return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);
} else if (rebased = tr.getMeta("rebased")) {
return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);
} else {
return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);
}
}
function isAdjacentTo(transform, prevRanges) {
if (!prevRanges) return false;
if (!transform.docChanged) return true;
var adjacent = false;
transform.mapping.maps[0].forEach(function (start, end) {
for (var i = 0; i < prevRanges.length; i += 2) if (start <= prevRanges[i + 1] && end >= prevRanges[i]) adjacent = true;
});
return adjacent;
}
function rangesFor(maps) {
var result = [];
for (var i = maps.length - 1; i >= 0 && result.length == 0; i--) maps[i].forEach(function (_from, _to, from, to) {
return result.push(from, to);
});
return result;
}
function mapRanges(ranges, mapping) {
if (!ranges) return null;
var result = [];
for (var i = 0; i < ranges.length; i += 2) {
var from = mapping.map(ranges[i], 1),
to = mapping.map(ranges[i + 1], -1);
if (from <= to) result.push(from, to);
}
return result;
}
function histTransaction(history, state, redo) {
var preserveItems = mustPreserveItems(state);
var histOptions = historyKey.get(state).spec.config;
var pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);
if (!pop) return null;
var selection = pop.selection.resolve(pop.transform.doc);
var added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
var newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);
return pop.transform.setSelection(selection).setMeta(historyKey, {
redo: redo,
historyState: newHist
});
}
var cachedPreserveItems = false,
cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
var plugins = state.plugins;
if (cachedPreserveItemsPlugins != plugins) {
cachedPreserveItems = false;
cachedPreserveItemsPlugins = plugins;
for (var i = 0; i < plugins.length; i++) if (plugins[i].spec.historyPreserveItems) {
cachedPreserveItems = true;
break;
}
}
return cachedPreserveItems;
}
function closeHistory(tr) {
return tr.setMeta(closeHistoryKey, true);
}
var historyKey = new prosemirrorState.PluginKey("history");
var closeHistoryKey = new prosemirrorState.PluginKey("closeHistory");
function history() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
config = {
depth: config.depth || 100,
newGroupDelay: config.newGroupDelay || 500
};
return new prosemirrorState.Plugin({
key: historyKey,
state: {
init: function init() {
return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
},
apply: function apply(tr, hist, state) {
return applyTransaction(hist, state, tr, config);
}
},
config: config,
props: {
handleDOMEvents: {
beforeinput: function beforeinput(view, e) {
var inputType = e.inputType;
var command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
if (!command) return false;
e.preventDefault();
return command(view.state, view.dispatch);
}
}
}
});
}
function buildCommand(redo, scroll) {
return function (state, dispatch) {
var hist = historyKey.getState(state);
if (!hist || (redo ? hist.undone : hist.done).eventCount == 0) return false;
if (dispatch) {
var tr = histTransaction(hist, state, redo);
if (tr) dispatch(scroll ? tr.scrollIntoView() : tr);
}
return true;
};
}
var undo = buildCommand(false, true);
var redo = buildCommand(true, true);
var undoNoScroll = buildCommand(false, false);
var redoNoScroll = buildCommand(true, false);
function undoDepth(state) {
var hist = historyKey.getState(state);
return hist ? hist.done.eventCount : 0;
}
function redoDepth(state) {
var hist = historyKey.getState(state);
return hist ? hist.undone.eventCount : 0;
}
exports.closeHistory = closeHistory;
exports.history = history;
exports.redo = redo;
exports.redoDepth = redoDepth;
exports.redoNoScroll = redoNoScroll;
exports.undo = undo;
exports.undoDepth = undoDepth;
exports.undoNoScroll = undoNoScroll;

View File

@ -0,0 +1,175 @@
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var prosemirrorState = require('prosemirror-state');
var prosemirrorTransform = require('prosemirror-transform');
var InputRule = _createClass(function InputRule(match, handler) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, InputRule);
this.match = match;
this.match = match;
this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
this.undoable = options.undoable !== false;
this.inCode = options.inCode || false;
this.inCodeMark = options.inCodeMark !== false;
});
function stringHandler(string) {
return function (state, match, start, end) {
var insert = string;
if (match[1]) {
var offset = match[0].lastIndexOf(match[1]);
insert += match[0].slice(offset + match[1].length);
start += offset;
var cutOff = start - end;
if (cutOff > 0) {
insert = match[0].slice(offset - cutOff, offset) + insert;
start = end;
}
}
return state.tr.insertText(insert, start, end);
};
}
var MAX_MATCH = 500;
function inputRules(_ref) {
var rules = _ref.rules;
var plugin = new prosemirrorState.Plugin({
state: {
init: function init() {
return null;
},
apply: function apply(tr, prev) {
var stored = tr.getMeta(this);
if (stored) return stored;
return tr.selectionSet || tr.docChanged ? null : prev;
}
},
props: {
handleTextInput: function handleTextInput(view, from, to, text) {
return run(view, from, to, text, rules, plugin);
},
handleDOMEvents: {
compositionend: function compositionend(view) {
setTimeout(function () {
var $cursor = view.state.selection.$cursor;
if ($cursor) run(view, $cursor.pos, $cursor.pos, "", rules, plugin);
});
}
}
},
isInputRules: true
});
return plugin;
}
function run(view, from, to, text, rules, plugin) {
if (view.composing) return false;
var state = view.state,
$from = state.doc.resolve(from);
var textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, "\uFFFC") + text;
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (!rule.inCodeMark && $from.marks().some(function (m) {
return m.type.spec.code;
})) continue;
if ($from.parent.type.spec.code) {
if (!rule.inCode) continue;
} else if (rule.inCode === "only") {
continue;
}
var match = rule.match.exec(textBefore);
var tr = match && match[0].length >= text.length && rule.handler(state, match, from - (match[0].length - text.length), to);
if (!tr) continue;
if (rule.undoable) tr.setMeta(plugin, {
transform: tr,
from: from,
to: to,
text: text
});
view.dispatch(tr);
return true;
}
return false;
}
var undoInputRule = function undoInputRule(state, dispatch) {
var plugins = state.plugins;
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i],
undoable = void 0;
if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
if (dispatch) {
var tr = state.tr,
toUndo = undoable.transform;
for (var j = toUndo.steps.length - 1; j >= 0; j--) tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
if (undoable.text) {
var marks = tr.doc.resolve(undoable.from).marks();
tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
} else {
tr["delete"](undoable.from, undoable.to);
}
dispatch(tr);
}
return true;
}
}
return false;
};
var emDash = new InputRule(/--$/, "—", {
inCodeMark: false
});
var ellipsis = new InputRule(/\.\.\.$/, "…", {
inCodeMark: false
});
var openDoubleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "“", {
inCodeMark: false
});
var closeDoubleQuote = new InputRule(/"$/, "”", {
inCodeMark: false
});
var openSingleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "", {
inCodeMark: false
});
var closeSingleQuote = new InputRule(/'$/, "", {
inCodeMark: false
});
var smartQuotes = [openDoubleQuote, closeDoubleQuote, openSingleQuote, closeSingleQuote];
function wrappingInputRule(regexp, nodeType) {
var getAttrs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var joinPredicate = arguments.length > 3 ? arguments[3] : undefined;
return new InputRule(regexp, function (state, match, start, end) {
var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;
var tr = state.tr["delete"](start, end);
var $start = tr.doc.resolve(start),
range = $start.blockRange(),
wrapping = range && prosemirrorTransform.findWrapping(range, nodeType, attrs);
if (!wrapping) return null;
tr.wrap(range, wrapping);
var before = tr.doc.resolve(start - 1).nodeBefore;
if (before && before.type == nodeType && prosemirrorTransform.canJoin(tr.doc, start - 1) && (!joinPredicate || joinPredicate(match, before))) tr.join(start - 1);
return tr;
});
}
function textblockTypeInputRule(regexp, nodeType) {
var getAttrs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return new InputRule(regexp, function (state, match, start, end) {
var $start = state.doc.resolve(start);
var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;
if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType)) return null;
return state.tr["delete"](start, end).setBlockType(start, start, nodeType, attrs);
});
}
exports.InputRule = InputRule;
exports.closeDoubleQuote = closeDoubleQuote;
exports.closeSingleQuote = closeSingleQuote;
exports.ellipsis = ellipsis;
exports.emDash = emDash;
exports.inputRules = inputRules;
exports.openDoubleQuote = openDoubleQuote;
exports.openSingleQuote = openSingleQuote;
exports.smartQuotes = smartQuotes;
exports.textblockTypeInputRule = textblockTypeInputRule;
exports.undoInputRule = undoInputRule;
exports.wrappingInputRule = wrappingInputRule;

View File

@ -0,0 +1,85 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var w3cKeyname = require('w3c-keyname');
var prosemirrorState = require('prosemirror-state');
var mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;
function normalizeKeyName(name) {
var parts = name.split(/-(?!$)/),
result = parts[parts.length - 1];
if (result == "Space") result = " ";
var alt, ctrl, shift, meta;
for (var i = 0; i < parts.length - 1; i++) {
var mod = parts[i];
if (/^(cmd|meta|m)$/i.test(mod)) meta = true;else if (/^a(lt)?$/i.test(mod)) alt = true;else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;else if (/^s(hift)?$/i.test(mod)) shift = true;else if (/^mod$/i.test(mod)) {
if (mac) meta = true;else ctrl = true;
} else throw new Error("Unrecognized modifier name: " + mod);
}
if (alt) result = "Alt-" + result;
if (ctrl) result = "Ctrl-" + result;
if (meta) result = "Meta-" + result;
if (shift) result = "Shift-" + result;
return result;
}
function normalize(map) {
var copy = Object.create(null);
for (var prop in map) {
copy[normalizeKeyName(prop)] = map[prop];
}
return copy;
}
function modifiers(name, event) {
var shift = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (event.altKey) name = "Alt-" + name;
if (event.ctrlKey) name = "Ctrl-" + name;
if (event.metaKey) name = "Meta-" + name;
if (shift && event.shiftKey) name = "Shift-" + name;
return name;
}
function keymap(bindings) {
return new prosemirrorState.Plugin({
props: {
handleKeyDown: keydownHandler(bindings)
}
});
}
function keydownHandler(bindings) {
var map = normalize(bindings);
return function (view, event) {
var name = w3cKeyname.keyName(event),
baseName,
direct = map[modifiers(name, event)];
if (direct && direct(view.state, view.dispatch, view)) return true;
if (name.length == 1 && name != " ") {
if (event.shiftKey) {
var noShift = map[modifiers(name, event, false)];
if (noShift && noShift(view.state, view.dispatch, view)) return true;
}
if ((event.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) && (baseName = w3cKeyname.base[event.keyCode]) && baseName != name) {
var fromCode = map[modifiers(baseName, event)];
if (fromCode && fromCode(view.state, view.dispatch, view)) return true;
}
}
return false;
};
}
exports.keydownHandler = keydownHandler;
exports.keymap = keymap;

View File

@ -0,0 +1,726 @@
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var crel = require('crelt');
var prosemirrorCommands = require('prosemirror-commands');
var prosemirrorHistory = require('prosemirror-history');
var prosemirrorState = require('prosemirror-state');
var SVG = "http://www.w3.org/2000/svg";
var XLINK = "http://www.w3.org/1999/xlink";
var prefix$2 = "ProseMirror-icon";
function hashPath(path) {
var hash = 0;
for (var i = 0; i < path.length; i++) {
hash = (hash << 5) - hash + path.charCodeAt(i) | 0;
}
return hash;
}
function getIcon(root, icon) {
var doc = (root.nodeType == 9 ? root : root.ownerDocument) || document;
var node = doc.createElement("div");
node.className = prefix$2;
if (icon.path) {
var path = icon.path,
width = icon.width,
height = icon.height;
var name = "pm-icon-" + hashPath(path).toString(16);
if (!doc.getElementById(name)) buildSVG(root, name, icon);
var svg = node.appendChild(doc.createElementNS(SVG, "svg"));
svg.style.width = width / height + "em";
var use = svg.appendChild(doc.createElementNS(SVG, "use"));
use.setAttributeNS(XLINK, "href", /([^#]*)/.exec(doc.location.toString())[1] + "#" + name);
} else if (icon.dom) {
node.appendChild(icon.dom.cloneNode(true));
} else {
var text = icon.text,
css = icon.css;
node.appendChild(doc.createElement("span")).textContent = text || '';
if (css) node.firstChild.style.cssText = css;
}
return node;
}
function buildSVG(root, name, data) {
var _ref = root.nodeType == 9 ? [root, root.body] : [root.ownerDocument || document, root],
_ref2 = _slicedToArray(_ref, 2),
doc = _ref2[0],
top = _ref2[1];
var collection = doc.getElementById(prefix$2 + "-collection");
if (!collection) {
collection = doc.createElementNS(SVG, "svg");
collection.id = prefix$2 + "-collection";
collection.style.display = "none";
top.insertBefore(collection, top.firstChild);
}
var sym = doc.createElementNS(SVG, "symbol");
sym.id = name;
sym.setAttribute("viewBox", "0 0 " + data.width + " " + data.height);
var path = sym.appendChild(doc.createElementNS(SVG, "path"));
path.setAttribute("d", data.path);
collection.appendChild(sym);
}
var prefix$1 = "ProseMirror-menu";
var MenuItem = function () {
function MenuItem(spec) {
_classCallCheck(this, MenuItem);
this.spec = spec;
}
_createClass(MenuItem, [{
key: "render",
value: function render(view) {
var spec = this.spec;
var dom = spec.render ? spec.render(view) : spec.icon ? getIcon(view.root, spec.icon) : spec.label ? crel("div", null, translate(view, spec.label)) : null;
if (!dom) throw new RangeError("MenuItem without icon or label property");
if (spec.title) {
var title = typeof spec.title === "function" ? spec.title(view.state) : spec.title;
dom.setAttribute("title", translate(view, title));
}
if (spec["class"]) dom.classList.add(spec["class"]);
if (spec.css) dom.style.cssText += spec.css;
dom.addEventListener("mousedown", function (e) {
e.preventDefault();
if (!dom.classList.contains(prefix$1 + "-disabled")) spec.run(view.state, view.dispatch, view, e);
});
function update(state) {
if (spec.select) {
var selected = spec.select(state);
dom.style.display = selected ? "" : "none";
if (!selected) return false;
}
var enabled = true;
if (spec.enable) {
enabled = spec.enable(state) || false;
setClass(dom, prefix$1 + "-disabled", !enabled);
}
if (spec.active) {
var active = enabled && spec.active(state) || false;
setClass(dom, prefix$1 + "-active", active);
}
return true;
}
return {
dom: dom,
update: update
};
}
}]);
return MenuItem;
}();
function translate(view, text) {
return view._props.translate ? view._props.translate(text) : text;
}
var lastMenuEvent = {
time: 0,
node: null
};
function markMenuEvent(e) {
lastMenuEvent.time = Date.now();
lastMenuEvent.node = e.target;
}
function isMenuEvent(wrapper) {
return Date.now() - 100 < lastMenuEvent.time && lastMenuEvent.node && wrapper.contains(lastMenuEvent.node);
}
var Dropdown = function () {
function Dropdown(content) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Dropdown);
this.options = options;
this.options = options || {};
this.content = Array.isArray(content) ? content : [content];
}
_createClass(Dropdown, [{
key: "render",
value: function render(view) {
var _this = this;
var content = renderDropdownItems(this.content, view);
var win = view.dom.ownerDocument.defaultView || window;
var label = crel("div", {
"class": prefix$1 + "-dropdown " + (this.options["class"] || ""),
style: this.options.css
}, translate(view, this.options.label || ""));
if (this.options.title) label.setAttribute("title", translate(view, this.options.title));
var wrap = crel("div", {
"class": prefix$1 + "-dropdown-wrap"
}, label);
var open = null;
var listeningOnClose = null;
var close = function close() {
if (open && open.close()) {
open = null;
win.removeEventListener("mousedown", listeningOnClose);
}
};
label.addEventListener("mousedown", function (e) {
e.preventDefault();
markMenuEvent(e);
if (open) {
close();
} else {
open = _this.expand(wrap, content.dom);
win.addEventListener("mousedown", listeningOnClose = function listeningOnClose() {
if (!isMenuEvent(wrap)) close();
});
}
});
function update(state) {
var inner = content.update(state);
wrap.style.display = inner ? "" : "none";
return inner;
}
return {
dom: wrap,
update: update
};
}
}, {
key: "expand",
value: function expand(dom, items) {
var menuDOM = crel("div", {
"class": prefix$1 + "-dropdown-menu " + (this.options["class"] || "")
}, items);
var done = false;
function close() {
if (done) return false;
done = true;
dom.removeChild(menuDOM);
return true;
}
dom.appendChild(menuDOM);
return {
close: close,
node: menuDOM
};
}
}]);
return Dropdown;
}();
function renderDropdownItems(items, view) {
var rendered = [],
updates = [];
for (var i = 0; i < items.length; i++) {
var _items$i$render = items[i].render(view),
dom = _items$i$render.dom,
update = _items$i$render.update;
rendered.push(crel("div", {
"class": prefix$1 + "-dropdown-item"
}, dom));
updates.push(update);
}
return {
dom: rendered,
update: combineUpdates(updates, rendered)
};
}
function combineUpdates(updates, nodes) {
return function (state) {
var something = false;
for (var i = 0; i < updates.length; i++) {
var up = updates[i](state);
nodes[i].style.display = up ? "" : "none";
if (up) something = true;
}
return something;
};
}
var DropdownSubmenu = function () {
function DropdownSubmenu(content) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, DropdownSubmenu);
this.options = options;
this.content = Array.isArray(content) ? content : [content];
}
_createClass(DropdownSubmenu, [{
key: "render",
value: function render(view) {
var items = renderDropdownItems(this.content, view);
var win = view.dom.ownerDocument.defaultView || window;
var label = crel("div", {
"class": prefix$1 + "-submenu-label"
}, translate(view, this.options.label || ""));
var wrap = crel("div", {
"class": prefix$1 + "-submenu-wrap"
}, label, crel("div", {
"class": prefix$1 + "-submenu"
}, items.dom));
var _listeningOnClose = null;
label.addEventListener("mousedown", function (e) {
e.preventDefault();
markMenuEvent(e);
setClass(wrap, prefix$1 + "-submenu-wrap-active", false);
if (!_listeningOnClose) win.addEventListener("mousedown", _listeningOnClose = function listeningOnClose() {
if (!isMenuEvent(wrap)) {
wrap.classList.remove(prefix$1 + "-submenu-wrap-active");
win.removeEventListener("mousedown", _listeningOnClose);
_listeningOnClose = null;
}
});
});
function update(state) {
var inner = items.update(state);
wrap.style.display = inner ? "" : "none";
return inner;
}
return {
dom: wrap,
update: update
};
}
}]);
return DropdownSubmenu;
}();
function renderGrouped(view, content) {
var result = document.createDocumentFragment();
var updates = [],
separators = [];
for (var i = 0; i < content.length; i++) {
var items = content[i],
localUpdates = [],
localNodes = [];
for (var j = 0; j < items.length; j++) {
var _items$j$render = items[j].render(view),
dom = _items$j$render.dom,
_update = _items$j$render.update;
var span = crel("span", {
"class": prefix$1 + "item"
}, dom);
result.appendChild(span);
localNodes.push(span);
localUpdates.push(_update);
}
if (localUpdates.length) {
updates.push(combineUpdates(localUpdates, localNodes));
if (i < content.length - 1) separators.push(result.appendChild(separator()));
}
}
function update(state) {
var something = false,
needSep = false;
for (var _i2 = 0; _i2 < updates.length; _i2++) {
var hasContent = updates[_i2](state);
if (_i2) separators[_i2 - 1].style.display = needSep && hasContent ? "" : "none";
needSep = hasContent;
if (hasContent) something = true;
}
return something;
}
return {
dom: result,
update: update
};
}
function separator() {
return crel("span", {
"class": prefix$1 + "separator"
});
}
var icons = {
join: {
width: 800,
height: 900,
path: "M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z"
},
lift: {
width: 1024,
height: 1024,
path: "M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z"
},
selectParentNode: {
text: "\u2B1A",
css: "font-weight: bold"
},
undo: {
width: 1024,
height: 1024,
path: "M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z"
},
redo: {
width: 1024,
height: 1024,
path: "M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z"
},
strong: {
width: 805,
height: 1024,
path: "M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z"
},
em: {
width: 585,
height: 1024,
path: "M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z"
},
code: {
width: 896,
height: 1024,
path: "M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z"
},
link: {
width: 951,
height: 1024,
path: "M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z"
},
bulletList: {
width: 768,
height: 896,
path: "M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z"
},
orderedList: {
width: 768,
height: 896,
path: "M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z"
},
blockquote: {
width: 640,
height: 896,
path: "M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z"
}
};
var joinUpItem = new MenuItem({
title: "Join with above block",
run: prosemirrorCommands.joinUp,
select: function select(state) {
return prosemirrorCommands.joinUp(state);
},
icon: icons.join
});
var liftItem = new MenuItem({
title: "Lift out of enclosing block",
run: prosemirrorCommands.lift,
select: function select(state) {
return prosemirrorCommands.lift(state);
},
icon: icons.lift
});
var selectParentNodeItem = new MenuItem({
title: "Select parent node",
run: prosemirrorCommands.selectParentNode,
select: function select(state) {
return prosemirrorCommands.selectParentNode(state);
},
icon: icons.selectParentNode
});
var undoItem = new MenuItem({
title: "Undo last change",
run: prosemirrorHistory.undo,
enable: function enable(state) {
return prosemirrorHistory.undo(state);
},
icon: icons.undo
});
var redoItem = new MenuItem({
title: "Redo last undone change",
run: prosemirrorHistory.redo,
enable: function enable(state) {
return prosemirrorHistory.redo(state);
},
icon: icons.redo
});
function wrapItem(nodeType, options) {
var passedOptions = {
run: function run(state, dispatch) {
return prosemirrorCommands.wrapIn(nodeType, options.attrs)(state, dispatch);
},
select: function select(state) {
return prosemirrorCommands.wrapIn(nodeType, options.attrs)(state);
}
};
for (var prop in options) {
passedOptions[prop] = options[prop];
}
return new MenuItem(passedOptions);
}
function blockTypeItem(nodeType, options) {
var command = prosemirrorCommands.setBlockType(nodeType, options.attrs);
var passedOptions = {
run: command,
enable: function enable(state) {
return command(state);
},
active: function active(state) {
var _state$selection = state.selection,
$from = _state$selection.$from,
to = _state$selection.to,
node = _state$selection.node;
if (node) return node.hasMarkup(nodeType, options.attrs);
return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs);
}
};
for (var prop in options) {
passedOptions[prop] = options[prop];
}
return new MenuItem(passedOptions);
}
function setClass(dom, cls, on) {
if (on) dom.classList.add(cls);else dom.classList.remove(cls);
}
var prefix = "ProseMirror-menubar";
function isIOS() {
if (typeof navigator == "undefined") return false;
var agent = navigator.userAgent;
return !/Edge\/\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\/\w+/.test(agent);
}
function menuBar(options) {
return new prosemirrorState.Plugin({
view: function view(editorView) {
return new MenuBarView(editorView, options);
}
});
}
var MenuBarView = function () {
function MenuBarView(editorView, options) {
var _this2 = this;
_classCallCheck(this, MenuBarView);
this.editorView = editorView;
this.options = options;
this.spacer = null;
this.maxHeight = 0;
this.widthForMaxHeight = 0;
this.floating = false;
this.scrollHandler = null;
this.wrapper = crel("div", {
"class": prefix + "-wrapper"
});
this.menu = this.wrapper.appendChild(crel("div", {
"class": prefix
}));
this.menu.className = prefix;
if (editorView.dom.parentNode) editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);
this.wrapper.appendChild(editorView.dom);
var _renderGrouped = renderGrouped(this.editorView, this.options.content),
dom = _renderGrouped.dom,
update = _renderGrouped.update;
this.contentUpdate = update;
this.menu.appendChild(dom);
this.update();
if (options.floating && !isIOS()) {
this.updateFloat();
var potentialScrollers = getAllWrapping(this.wrapper);
this.scrollHandler = function (e) {
var root = _this2.editorView.root;
if (!(root.body || root).contains(_this2.wrapper)) potentialScrollers.forEach(function (el) {
return el.removeEventListener("scroll", _this2.scrollHandler);
});else _this2.updateFloat(e.target.getBoundingClientRect ? e.target : undefined);
};
potentialScrollers.forEach(function (el) {
return el.addEventListener('scroll', _this2.scrollHandler);
});
}
}
_createClass(MenuBarView, [{
key: "update",
value: function update() {
this.contentUpdate(this.editorView.state);
if (this.floating) {
this.updateScrollCursor();
} else {
if (this.menu.offsetWidth != this.widthForMaxHeight) {
this.widthForMaxHeight = this.menu.offsetWidth;
this.maxHeight = 0;
}
if (this.menu.offsetHeight > this.maxHeight) {
this.maxHeight = this.menu.offsetHeight;
this.menu.style.minHeight = this.maxHeight + "px";
}
}
}
}, {
key: "updateScrollCursor",
value: function updateScrollCursor() {
var selection = this.editorView.root.getSelection();
if (!selection.focusNode) return;
var rects = selection.getRangeAt(0).getClientRects();
var selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];
if (!selRect) return;
var menuRect = this.menu.getBoundingClientRect();
if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {
var scrollable = findWrappingScrollable(this.wrapper);
if (scrollable) scrollable.scrollTop -= menuRect.bottom - selRect.top;
}
}
}, {
key: "updateFloat",
value: function updateFloat(scrollAncestor) {
var parent = this.wrapper,
editorRect = parent.getBoundingClientRect(),
top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;
if (this.floating) {
if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) {
this.floating = false;
this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = "";
this.menu.style.display = "";
this.spacer.parentNode.removeChild(this.spacer);
this.spacer = null;
} else {
var border = (parent.offsetWidth - parent.clientWidth) / 2;
this.menu.style.left = editorRect.left + border + "px";
this.menu.style.display = editorRect.top > (this.editorView.dom.ownerDocument.defaultView || window).innerHeight ? "none" : "";
if (scrollAncestor) this.menu.style.top = top + "px";
}
} else {
if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) {
this.floating = true;
var menuRect = this.menu.getBoundingClientRect();
this.menu.style.left = menuRect.left + "px";
this.menu.style.width = menuRect.width + "px";
if (scrollAncestor) this.menu.style.top = top + "px";
this.menu.style.position = "fixed";
this.spacer = crel("div", {
"class": prefix + "-spacer",
style: "height: ".concat(menuRect.height, "px")
});
parent.insertBefore(this.spacer, this.menu);
}
}
}
}, {
key: "destroy",
value: function destroy() {
if (this.wrapper.parentNode) this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper);
}
}]);
return MenuBarView;
}();
function selectionIsInverted(selection) {
if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset;
return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING;
}
function findWrappingScrollable(node) {
for (var cur = node.parentNode; cur; cur = cur.parentNode) {
if (cur.scrollHeight > cur.clientHeight) return cur;
}
}
function getAllWrapping(node) {
var res = [node.ownerDocument.defaultView || window];
for (var cur = node.parentNode; cur; cur = cur.parentNode) {
res.push(cur);
}
return res;
}
exports.Dropdown = Dropdown;
exports.DropdownSubmenu = DropdownSubmenu;
exports.MenuItem = MenuItem;
exports.blockTypeItem = blockTypeItem;
exports.icons = icons;
exports.joinUpItem = joinUpItem;
exports.liftItem = liftItem;
exports.menuBar = menuBar;
exports.redoItem = redoItem;
exports.renderGrouped = renderGrouped;
exports.selectParentNodeItem = selectParentNodeItem;
exports.undoItem = undoItem;
exports.wrapItem = wrapItem;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,209 @@
'use strict';
var GOOD_LEAF_SIZE = 200;
// :: class<T> A rope sequence is a persistent sequence data structure
// that supports appending, prepending, and slicing without doing a
// full copy. It is represented as a mostly-balanced tree.
var RopeSequence = function RopeSequence () {};
RopeSequence.prototype.append = function append (other) {
if (!other.length) { return this }
other = RopeSequence.from(other);
return (!this.length && other) ||
(other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||
(this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||
this.appendInner(other)
};
// :: (union<[T], RopeSequence<T>>) → RopeSequence<T>
// Prepend an array or other rope to this one, returning a new rope.
RopeSequence.prototype.prepend = function prepend (other) {
if (!other.length) { return this }
return RopeSequence.from(other).append(this)
};
RopeSequence.prototype.appendInner = function appendInner (other) {
return new Append(this, other)
};
// :: (?number, ?number) → RopeSequence<T>
// Create a rope repesenting a sub-sequence of this rope.
RopeSequence.prototype.slice = function slice (from, to) {
if ( from === void 0 ) from = 0;
if ( to === void 0 ) to = this.length;
if (from >= to) { return RopeSequence.empty }
return this.sliceInner(Math.max(0, from), Math.min(this.length, to))
};
// :: (number) → T
// Retrieve the element at the given position from this rope.
RopeSequence.prototype.get = function get (i) {
if (i < 0 || i >= this.length) { return undefined }
return this.getInner(i)
};
// :: ((element: T, index: number) → ?bool, ?number, ?number)
// Call the given function for each element between the given
// indices. This tends to be more efficient than looping over the
// indices and calling `get`, because it doesn't have to descend the
// tree for every element.
RopeSequence.prototype.forEach = function forEach (f, from, to) {
if ( from === void 0 ) from = 0;
if ( to === void 0 ) to = this.length;
if (from <= to)
{ this.forEachInner(f, from, to, 0); }
else
{ this.forEachInvertedInner(f, from, to, 0); }
};
// :: ((element: T, index: number) → U, ?number, ?number) → [U]
// Map the given functions over the elements of the rope, producing
// a flat array.
RopeSequence.prototype.map = function map (f, from, to) {
if ( from === void 0 ) from = 0;
if ( to === void 0 ) to = this.length;
var result = [];
this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);
return result
};
// :: (?union<[T], RopeSequence<T>>) → RopeSequence<T>
// Create a rope representing the given array, or return the rope
// itself if a rope was given.
RopeSequence.from = function from (values) {
if (values instanceof RopeSequence) { return values }
return values && values.length ? new Leaf(values) : RopeSequence.empty
};
var Leaf = /*@__PURE__*/(function (RopeSequence) {
function Leaf(values) {
RopeSequence.call(this);
this.values = values;
}
if ( RopeSequence ) Leaf.__proto__ = RopeSequence;
Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );
Leaf.prototype.constructor = Leaf;
var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };
Leaf.prototype.flatten = function flatten () {
return this.values
};
Leaf.prototype.sliceInner = function sliceInner (from, to) {
if (from == 0 && to == this.length) { return this }
return new Leaf(this.values.slice(from, to))
};
Leaf.prototype.getInner = function getInner (i) {
return this.values[i]
};
Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {
for (var i = from; i < to; i++)
{ if (f(this.values[i], start + i) === false) { return false } }
};
Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {
for (var i = from - 1; i >= to; i--)
{ if (f(this.values[i], start + i) === false) { return false } }
};
Leaf.prototype.leafAppend = function leafAppend (other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
{ return new Leaf(this.values.concat(other.flatten())) }
};
Leaf.prototype.leafPrepend = function leafPrepend (other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
{ return new Leaf(other.flatten().concat(this.values)) }
};
prototypeAccessors.length.get = function () { return this.values.length };
prototypeAccessors.depth.get = function () { return 0 };
Object.defineProperties( Leaf.prototype, prototypeAccessors );
return Leaf;
}(RopeSequence));
// :: RopeSequence
// The empty rope sequence.
RopeSequence.empty = new Leaf([]);
var Append = /*@__PURE__*/(function (RopeSequence) {
function Append(left, right) {
RopeSequence.call(this);
this.left = left;
this.right = right;
this.length = left.length + right.length;
this.depth = Math.max(left.depth, right.depth) + 1;
}
if ( RopeSequence ) Append.__proto__ = RopeSequence;
Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );
Append.prototype.constructor = Append;
Append.prototype.flatten = function flatten () {
return this.left.flatten().concat(this.right.flatten())
};
Append.prototype.getInner = function getInner (i) {
return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)
};
Append.prototype.forEachInner = function forEachInner (f, from, to, start) {
var leftLen = this.left.length;
if (from < leftLen &&
this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)
{ return false }
if (to > leftLen &&
this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)
{ return false }
};
Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {
var leftLen = this.left.length;
if (from > leftLen &&
this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)
{ return false }
if (to < leftLen &&
this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)
{ return false }
};
Append.prototype.sliceInner = function sliceInner (from, to) {
if (from == 0 && to == this.length) { return this }
var leftLen = this.left.length;
if (to <= leftLen) { return this.left.slice(from, to) }
if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }
return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))
};
Append.prototype.leafAppend = function leafAppend (other) {
var inner = this.right.leafAppend(other);
if (inner) { return new Append(this.left, inner) }
};
Append.prototype.leafPrepend = function leafPrepend (other) {
var inner = this.left.leafPrepend(other);
if (inner) { return new Append(inner, this.right) }
};
Append.prototype.appendInner = function appendInner (other) {
if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)
{ return new Append(this.left, new Append(this.right, other)) }
return new Append(this, other)
};
return Append;
}(RopeSequence));
module.exports = RopeSequence;

View File

@ -42,6 +42,102 @@
"title": "prosemirror-schema-basic",
"module-type": "library"
}
},
{
"file": "orderedmap.cjs",
"fields": {
"type": "application/javascript",
"title": "orderedmap",
"module-type": "library"
}
},
{
"file": "prosemirror-transform.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-transform",
"module-type": "library"
}
},
{
"file": "prosemirror-keymap.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-keymap",
"module-type": "library"
}
},
{
"file": "prosemirror-history.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-history",
"module-type": "library"
}
},
{
"file": "prosemirror-commands.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-commands",
"module-type": "library"
}
},
{
"file": "prosemirror-dropcursor.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-dropcursor",
"module-type": "library"
}
},
{
"file": "prosemirror-gapcursor.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-gapcursor",
"module-type": "library"
}
},
{
"file": "prosemirror-menu.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-menu",
"module-type": "library"
}
},
{
"file": "prosemirror-inputrules.cjs",
"fields": {
"type": "application/javascript",
"title": "prosemirror-inputrules",
"module-type": "library"
}
},
{
"file": "w3c-keyname.cjs",
"fields": {
"type": "application/javascript",
"title": "w3c-keyname",
"module-type": "library"
}
},
{
"file": "crelt.cjs",
"fields": {
"type": "application/javascript",
"title": "crelt",
"module-type": "library"
}
},
{
"file": "rope-sequence.cjs",
"fields": {
"type": "application/javascript",
"title": "rope-sequence",
"module-type": "library"
}
}
]
}

View File

@ -0,0 +1,127 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var base = {
8: "Backspace",
9: "Tab",
10: "Enter",
12: "NumLock",
13: "Enter",
16: "Shift",
17: "Control",
18: "Alt",
20: "CapsLock",
27: "Escape",
32: " ",
33: "PageUp",
34: "PageDown",
35: "End",
36: "Home",
37: "ArrowLeft",
38: "ArrowUp",
39: "ArrowRight",
40: "ArrowDown",
44: "PrintScreen",
45: "Insert",
46: "Delete",
59: ";",
61: "=",
91: "Meta",
92: "Meta",
106: "*",
107: "+",
108: ",",
109: "-",
110: ".",
111: "/",
144: "NumLock",
145: "ScrollLock",
160: "Shift",
161: "Shift",
162: "Control",
163: "Control",
164: "Alt",
165: "Alt",
173: "-",
186: ";",
187: "=",
188: ",",
189: "-",
190: ".",
191: "/",
192: "`",
219: "[",
220: "\\",
221: "]",
222: "'"
};
var shift = {
48: ")",
49: "!",
50: "@",
51: "#",
52: "$",
53: "%",
54: "^",
55: "&",
56: "*",
57: "(",
59: ":",
61: "+",
173: "_",
186: ":",
187: "+",
188: "<",
189: "_",
190: ">",
191: "?",
192: "~",
219: "{",
220: "|",
221: "}",
222: "\""
};
var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
// Fill in the digit keys
for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
// The function keys
for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
// And the alphabetic keys
for (var i = 65; i <= 90; i++) {
base[i] = String.fromCharCode(i + 32);
shift[i] = String.fromCharCode(i);
}
// For each code that doesn't have a shift-equivalent, copy the base name
for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
function keyName(event) {
// On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.
// On IE, shift effect is never included in `.key`.
var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||
ie && event.shiftKey && event.key && event.key.length == 1 ||
event.key == "Unidentified";
var name = (!ignoreKey && event.key) ||
(event.shiftKey ? shift : base)[event.keyCode] ||
event.key || "Unidentified";
// Edge sometimes produces wrong names (Issue #3)
if (name == "Esc") name = "Escape";
if (name == "Del") name = "Delete";
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
if (name == "Left") name = "ArrowLeft";
if (name == "Up") name = "ArrowUp";
if (name == "Right") name = "ArrowRight";
if (name == "Down") name = "ArrowDown";
return name
}
exports.base = base;
exports.keyName = keyName;
exports.shift = shift;

View File

@ -6,18 +6,21 @@ Test Test
Downloaded from JsDelivr CDN (like `https://cdn.jsdelivr.net/npm/prosemirror-state@latest/dist/index.cjs` and store as `prosemirror-state.js`):
* [ext[prosemirror-state|https://cdn.jsdelivr.net/npm/prosemirror-state@latest/dist/index.cjs]]: 1.4.3
* [ext[prosemirror-view|https://cdn.jsdelivr.net/npm/prosemirror-view@latest/dist/index.cjs]]: 1.38.1
* [ext[prosemirror-model|https://cdn.jsdelivr.net/npm/prosemirror-model@latest/dist/index.cjs]]: 1.25.0
* [ext[prosemirror-schema-basic|https://cdn.jsdelivr.net/npm/prosemirror-schema-basic@latest/dist/index.cjs]]: 1.2.4
* [ext[prosemirror-schema-list|https://cdn.jsdelivr.net/npm/prosemirror-schema-list@latest/dist/index.cjs]]: 1.5.1
* [ext[prosemirror-example-setup|https://cdn.jsdelivr.net/npm/prosemirror-example-setup@latest/dist/index.cjs]]: 1.2.3
* [ext[orderedmap|https://cdn.jsdelivr.net/npm/orderedmap@latest/dist/index.cjs]]: latest
* [ext[prosemirror-transform|https://cdn.jsdelivr.net/npm/prosemirror-transform@latest/dist/index.cjs]]: latest
* [ext[prosemirror-keymap|https://cdn.jsdelivr.net/npm/prosemirror-keymap@latest/dist/index.cjs]]: latest
* [ext[prosemirror-history|https://cdn.jsdelivr.net/npm/prosemirror-history@latest/dist/index.cjs]]: latest
* [ext[prosemirror-commands|https://cdn.jsdelivr.net/npm/prosemirror-commands@latest/dist/index.cjs]]: latest
* [ext[prosemirror-dropcursor|https://cdn.jsdelivr.net/npm/prosemirror-dropcursor@latest/dist/index.cjs]]: latest
* [ext[prosemirror-gapcursor|https://cdn.jsdelivr.net/npm/prosemirror-gapcursor@latest/dist/index.cjs]]: latest
* [ext[prosemirror-menu|https://cdn.jsdelivr.net/npm/prosemirror-menu@latest/dist/index.cjs]]: latest
* [ext[prosemirror-inputrules|https://cdn.jsdelivr.net/npm/prosemirror-inputrules@latest/dist/index.cjs]]: latest
* [ext[prosemirror-state|https://cdn.jsdelivr.net/npm/prosemirror-state@latest/dist/index.cjs]]: v1.4.3
* [ext[prosemirror-view|https://cdn.jsdelivr.net/npm/prosemirror-view@latest/dist/index.cjs]]: v1.38.1
* [ext[prosemirror-model|https://cdn.jsdelivr.net/npm/prosemirror-model@latest/dist/index.cjs]]: v1.25.0
* [ext[prosemirror-schema-basic|https://cdn.jsdelivr.net/npm/prosemirror-schema-basic@latest/dist/index.cjs]]: v1.2.4
* [ext[prosemirror-schema-list|https://cdn.jsdelivr.net/npm/prosemirror-schema-list@latest/dist/index.cjs]]: v1.5.1
* [ext[prosemirror-example-setup|https://cdn.jsdelivr.net/npm/prosemirror-example-setup@latest/dist/index.cjs]]: v1.2.3
* [ext[orderedmap|https://cdn.jsdelivr.net/npm/orderedmap@latest/dist/index.cjs]]: v2.1.1
* [ext[prosemirror-transform|https://cdn.jsdelivr.net/npm/prosemirror-transform@latest/dist/index.cjs]]: v1.10.3
* [ext[prosemirror-keymap|https://cdn.jsdelivr.net/npm/prosemirror-keymap@latest/dist/index.cjs]]: v1.2.2
* [ext[prosemirror-history|https://cdn.jsdelivr.net/npm/prosemirror-history@latest/dist/index.cjs]]: v1.4.1
* [ext[prosemirror-commands|https://cdn.jsdelivr.net/npm/prosemirror-commands@latest/dist/index.cjs]]: v1.7.0
* [ext[prosemirror-dropcursor|https://cdn.jsdelivr.net/npm/prosemirror-dropcursor@latest/dist/index.cjs]]: v1.8.1
* [ext[prosemirror-gapcursor|https://cdn.jsdelivr.net/npm/prosemirror-gapcursor@latest/dist/index.cjs]]: v1.3.2
* [ext[prosemirror-menu|https://cdn.jsdelivr.net/npm/prosemirror-menu@latest/dist/index.cjs]]: v1.2.4
* [ext[prosemirror-inputrules|https://cdn.jsdelivr.net/npm/prosemirror-inputrules@latest/dist/index.cjs]]: v1.5.0
* [ext[w3c-keyname|https://cdn.jsdelivr.net/npm/w3c-keyname@latest/dist/index.cjs]]: v2.2.8
* [ext[crelt|https://cdn.jsdelivr.net/npm/crelt@latest/dist/index.cjs]]: v1.0.6
* [ext[rope-sequence|https://cdn.jsdelivr.net/npm/rope-sequence@latest/dist/index.cjs]]: v1.3.4