Files
svgedit/editor/layer.js
Brett Zamir a3f0b8e501 - Security fix: 'extPath', 'imgPath', 'extIconsPath', 'canvgPath', 'langPath', 'jGraduatePath', and 'jspdfPath' were not being prevented
- Breaking change: Rename "svgutils.js" to "utilities.js" (make in conformity with JSDoc module naming convention)
- Breaking change: Rename "svgedit.js" to "namespaces.js" (to make clear purpose and avoid confusing with editor)
- Breaking change: Rename "jquery-svg.js" to "jQuery.attr.js"
- Breaking change: Rename "jquery.contextMenu.js" to "jQuery.contextMenu.js"
- Breaking change: Rename "jquery.jpicker.js" to "jQuery.jPicker.js"
- Breaking change: Rename "JQuerySpinBtn.css" to "jQuery.SpinButton.css"
- Breaking change: Rename "JQuerySpinBtn.js" to "jQuery.SpinButton.js" (to have file name more closely reflect name)
- Breaking change: Rename "jquery.svgicons.js" to "jQuery.svgIcons.js"
- Breaking change: Rename "jquery.jgraduate.js" to "jQuery.jGraduate.js"
- Breaking change: Rename "pathseg.js" to "svgpathseg.js" (as it is a poyfill of SVGPathSeg)
- Breaking change: Rename `addSvgElementFromJson()` to `addSVGElementFromJson` for consistency
- Breaking change: Rename `changeSvgContent()` to `changeSVGContent()` for consistency
- Breaking change: Have `exportPDF` resolve with `output` and `outputType` rather than `dataurlstring` (as type may vary)
- Breaking change: Rename `extensions/mathjax/MathJax.js` to `extensions/mathjax/MathJax.min.js`
- Breaking change: Avoid recent change to have editor ready callbacks return Promises (we're not using and advantageous to keep sequential)
- Breaking change: Avoid recent addition of locale-side function in ext-imagelib for l10n
- Breaking change: Change name of ext-arrows.js from `Arrows` to `arrows` for sake of file path (not localized anyways).
- Breaking change: Change `addlangData` extension event to `addLangData` for consistency with method name
- Breaking change: Have `readLang`  return lang and data but do not call `setLang`
- Fix: Have general locales load first so extensions may use
- Fix: Provide `importLocale` to extensions `init` so it may delay adding of the extension until locale data loaded
- Fix: Ensure call to `rasterExport` without `imgType` properly sets MIME type to PNG
- Fix: Wrong name for moinsave
- Update: Update WebAppFind per new API changes
- Enhancement: Make `setStrings` public on editor for late setting (used
  by `ext-shapes.js`)
- Enhancement: Add `extensions_added` event
- Enhancement: Add `message` event (Relay messages including those which
  have been been received prior to extension load)
- Enhancement: Allow SVGEdit to work out of the box--avoid need for copying sample config file. Should also help with Github-based file servers
- Enhancement: Allow avoiding "name" in extension export (just extract out of file name)
- Enhancement: Add stack blur to canvg by default (and refactoring it)
- Enhancement: Return `Promise` for `embedImage` (as with some other loading methods)
- Enhancement: Supply `importLocale` to `langReady` to facilitate extension locale loading
- Enhancement: Recover if an extension fails to load (just log and otherwise ignore)
- Enhancement: More i18n of extensions (also fixed issue with some console warnings about missing locale strings); i18nize Hello World too
- Enhancement: Allowing importing of locales within `addLangData`
- npm: Update devDeps
- Docs: Migrate copies of all old wiki pages to docs/from-old-wiki folder; intended for a possible move to Markdown, so raw HTML (with formatting) was not preserved, though named links had their absolute URL links preserved
- Docs: Begin deleting `SvgCanvas.md` as ensuring jsdoc has replacements
- Docs: Add Edtior doc file for help to general users
- Docs: Clarify/simplify install instructions
- npm/Docs (JSDoc): Add script to check for overly generic types
- Docs (JSDoc): For config/prefs and extension creating, link to tutorials (moved tutorials to own directory to avoid recursion problems by jsdoc)
- Docs (JSDoc): Add modules (upper case for usual main entrance files or regular names)
- Docs (JSDoc): Fill out missing areas; indicate return of `undefined`; consistency with `@returns`
- Docs (JSDoc): Add our own layout template to support overflow
- Docs (JSDoc): Use cleverLinks and disallow unknown tags
- Docs (JSDoc): Insist on "pedantic" flag; put output directory in config
- Docs (JSDoc): Use more precise Integer/Float over number, the specific type of array/function/object
- Docs (JSDoc): Use `@throws`, `@enum`, `@event`/`@fires`/`@listens`
- Docs: Generally update/improve docs (fixes #92)
- Docs: Update links to `latest` path (Avoid needing to update such references upon each release)
- Docs: 80 chars max
- Refactoring: Drop code for extension as function (already requiring export to be an object)
- Refactoring: Object destructuring, `Object.entries`, Object shorthand, array extras, more camelCase variable names
- Refactoring: Add a `Command` base class
- Refactoring: Simplify svgicons `callback` ready detection
- Refactoring: Put `let` or `const` closer to scope
- Refactoring: Remove unneeded `delimiter` from regex escaping utility
- Refactoring: Clearer variable names
- Refactoring: Use (non-deprecated) Event constructors
- Testing: Use new Sinon
2018-07-08 22:39:46 -07:00

224 lines
6.3 KiB
JavaScript

/* globals jQuery */
/**
* Provides tools for the layer concept
* @module layer
* @license MIT
*
* @copyright 2011 Jeff Schiller, 2016 Flint O'Brien
*/
import {NS} from './namespaces.js';
import {toXml, walkTree} from './utilities.js';
const $ = jQuery;
/**
* This class encapsulates the concept of a layer in the drawing. It can be constructed with
* an existing group element or, with three parameters, will create a new layer group element.
*
* @example
* new Layer('name', group); // Use the existing group for this layer.
* new Layer('name', group, svgElem); // Create a new group and add it to the DOM after group.
* new Layer('name', null, svgElem); // Create a new group and add it to the DOM as the last layer.
* @memberof module:layer
*/
class Layer {
/**
* @param {string} name - Layer name
* @param {SVGGElement|null} group - An existing SVG group element or null.
* If group and no svgElem, use group for this layer.
* If group and svgElem, create a new group element and insert it in the DOM after group.
* If no group and svgElem, create a new group element and insert it in the DOM as the last layer.
* @param {SVGGElement=} svgElem - The SVG DOM element. If defined, use this to add
* a new layer to the document.
*/
constructor (name, group, svgElem) {
this.name_ = name;
this.group_ = svgElem ? null : group;
if (svgElem) {
// Create a group element with title and add it to the DOM.
const svgdoc = svgElem.ownerDocument;
this.group_ = svgdoc.createElementNS(NS.SVG, 'g');
const layerTitle = svgdoc.createElementNS(NS.SVG, 'title');
layerTitle.textContent = name;
this.group_.append(layerTitle);
if (group) {
$(group).after(this.group_);
} else {
svgElem.append(this.group_);
}
}
addLayerClass(this.group_);
walkTree(this.group_, function (e) {
e.setAttribute('style', 'pointer-events:inherit');
});
this.group_.setAttribute('style', svgElem ? 'pointer-events:all' : 'pointer-events:none');
}
/**
* Get the layer's name.
* @returns {string} The layer name
*/
getName () {
return this.name_;
}
/**
* Get the group element for this layer.
* @returns {SVGGElement} The layer SVG group
*/
getGroup () {
return this.group_;
}
/**
* Active this layer so it takes pointer events.
* @returns {undefined}
*/
activate () {
this.group_.setAttribute('style', 'pointer-events:all');
}
/**
* Deactive this layer so it does NOT take pointer events.
* @returns {undefined}
*/
deactivate () {
this.group_.setAttribute('style', 'pointer-events:none');
}
/**
* Set this layer visible or hidden based on 'visible' parameter.
* @param {boolean} visible - If true, make visible; otherwise, hide it.
* @returns {undefined}
*/
setVisible (visible) {
const expected = visible === undefined || visible ? 'inline' : 'none';
const oldDisplay = this.group_.getAttribute('display');
if (oldDisplay !== expected) {
this.group_.setAttribute('display', expected);
}
}
/**
* Is this layer visible?
* @returns {boolean} True if visible.
*/
isVisible () {
return this.group_.getAttribute('display') !== 'none';
}
/**
* Get layer opacity.
* @returns {Float} Opacity value.
*/
getOpacity () {
const opacity = this.group_.getAttribute('opacity');
if (opacity === null || opacity === undefined) {
return 1;
}
return parseFloat(opacity);
}
/**
* Sets the opacity of this layer. If opacity is not a value between 0.0 and 1.0,
* nothing happens.
* @param {Float} opacity - A float value in the range 0.0-1.0
* @returns {undefined}
*/
setOpacity (opacity) {
if (typeof opacity === 'number' && opacity >= 0.0 && opacity <= 1.0) {
this.group_.setAttribute('opacity', opacity);
}
}
/**
* Append children to this layer.
* @param {SVGGElement} children - The children to append to this layer.
* @returns {undefined}
*/
appendChildren (children) {
for (let i = 0; i < children.length; ++i) {
this.group_.append(children[i]);
}
}
/**
* @returns {SVGTitleElement|null}
*/
getTitleElement () {
const len = this.group_.childNodes.length;
for (let i = 0; i < len; ++i) {
const child = this.group_.childNodes.item(i);
if (child && child.tagName === 'title') {
return child;
}
}
return null;
}
/**
* Set the name of this layer.
* @param {string} name - The new name.
* @param {module:history.HistoryRecordingService} hrService - History recording service
* @returns {string|null} The new name if changed; otherwise, null.
*/
setName (name, hrService) {
const previousName = this.name_;
name = toXml(name);
// now change the underlying title element contents
const title = this.getTitleElement();
if (title) {
$(title).empty();
title.textContent = name;
this.name_ = name;
if (hrService) {
hrService.changeElement(title, {'#text': previousName});
}
return this.name_;
}
return null;
}
/**
* Remove this layer's group from the DOM. No more functions on group can be called after this.
* @param {SVGGElement} children - The children to append to this layer.
* @returns {SVGGElement} The layer SVG group that was just removed.
*/
removeGroup () {
const parent = this.group_.parentNode;
const group = parent.removeChild(this.group_);
this.group_ = undefined;
return group;
}
}
/**
* @property {string} CLASS_NAME - class attribute assigned to all layer groups.
*/
Layer.CLASS_NAME = 'layer';
/**
* @property {RegExp} CLASS_REGEX - Used to test presence of class Layer.CLASS_NAME
*/
Layer.CLASS_REGEX = new RegExp('(\\s|^)' + Layer.CLASS_NAME + '(\\s|$)');
/**
* Add class `Layer.CLASS_NAME` to the element (usually `class='layer'`).
*
* @param {SVGGElement} elem - The SVG element to update
* @returns {undefined}
*/
function addLayerClass (elem) {
const classes = elem.getAttribute('class');
if (classes === null || classes === undefined || !classes.length) {
elem.setAttribute('class', Layer.CLASS_NAME);
} else if (!Layer.CLASS_REGEX.test(classes)) {
elem.setAttribute('class', classes + ' ' + Layer.CLASS_NAME);
}
}
export default Layer;