Example #1
0
const createMenu = function (editorMenuItems, menus, removedMenuItems, context) {
  let menuButton, menu, namedMenuItems, isUserDefined;

  // User defined menu
  if (menus) {
    menu = menus[context];
    isUserDefined = true;
  } else {
    menu = defaultMenus[context];
  }

  if (menu) {
    menuButton = { text: menu.title };
    namedMenuItems = [];

    // Default/user defined items
    Tools.each((menu.items || '').split(/[ ,]/), function (name) {
      const namedMenuItem = createMenuNameItemPair(name, editorMenuItems[name]);

      if (namedMenuItem) {
        namedMenuItems.push(namedMenuItem);
      }
    });

    // Added though context
    if (!isUserDefined) {
      Tools.each(editorMenuItems, function (item, name) {
        if (item.context === context && !hasItemName(namedMenuItems, name)) {
          if (item.separator === 'before') {
            namedMenuItems.push(delimiterMenuNamePair());
          }

          if (item.prependToContext) {
            namedMenuItems.unshift(createMenuNameItemPair(name, item));
          } else {
            namedMenuItems.push(createMenuNameItemPair(name, item));
          }

          if (item.separator === 'after') {
            namedMenuItems.push(delimiterMenuNamePair());
          }
        }
      });
    }

    menuButton.menu = Arr.map(cleanupMenu(namedMenuItems, removedMenuItems), function (menuItem) {
      return menuItem.item;
    });

    if (!menuButton.menu.length) {
      return null;
    }
  }

  return menuButton;
};
    return Chain.mapper(function (viewBlock: any) {
      const ranges = Arr.map(paths, function (path) {
        const container = Hierarchy.follow(Element.fromDom(viewBlock.get()), path).getOrDie();
        const rng = document.createRange();
        rng.selectNode(container.dom());
        return rng;
      });

      return TableCellSelection.getCellsFromRanges(ranges);
    });
Example #3
0
 getItems: (value) => {
   return Arr.map([
     {
       text: 'Cat'
     },
     {
       text: 'Dog'
     }
   ], (d) => makeItem(d.text));
 }
Example #4
0
const getWrapElements = function (rootNode, rng) {
  const commonAnchorContainer = Element.fromDom(rng.commonAncestorContainer);
  const parents = Parents.parentsAndSelf(commonAnchorContainer, rootNode);
  const wrapElements = Arr.filter(parents, function (elm) {
    return ElementType.isInline(elm) || ElementType.isHeading(elm);
  });
  const listWrappers = getFullySelectedListWrappers(parents, rng);
  const allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  return Arr.map(allWrappers, Replication.shallow);
};
Example #5
0
 return new Promise((resolve) => {
   const filteredItems = Arr.filter([ 'two', 'three' ], (number) => number.indexOf(pattern) !== -1);
   resolve(
     Arr.map(filteredItems, (number) => ({
       value: `${number}`,
       text: `${number}`,
       icon: '='
     }))
   );
 });
Example #6
0
    return Chain.mapper(function (viewBlock) {
      const ranges = Arr.map(paths, function (path) {
        const container = Hierarchy.follow(Element.fromDom(viewBlock.get()), path).getOrDie();
        const rng = document.createRange();
        rng.selectNode(container.dom());
        return rng;
      });

      return FragmentReader.read(Element.fromDom(viewBlock.get()), ranges);
    });
Example #7
0
const selectionIndentation = (editor: Editor, indentation: Indentation): boolean => {
  const lists = Arr.map(Selection.getSelectedListRoots(editor), Element.fromDom);
  const dlItems = Arr.map(Selection.getSelectedDlItems(editor), Element.fromDom);
  let isHandled = false;

  if (lists.length || dlItems.length) {
    const bookmark = editor.selection.getBookmark();

    listsIndentation(editor, lists, indentation);
    dlIndentation(editor, indentation, dlItems);

    editor.selection.moveToBookmark(bookmark);
    editor.selection.setRng(Range.normalizeRange(editor.selection.getRng()));
    editor.nodeChanged();
    isHandled = true;
  }

  return isHandled;
};
 ApproxStructure.build((s, str, arr) => {
   return s.element('div', {
     classes: [ arr.has('tox-collection'), arr.has('tox-collection--grid'), arr.not('tox-menu') ],
     children: [
       s.element('div', {
         classes: [ arr.has('tox-collection__group') ],
         children: Arr.map([ 'G', 'H' ], (letter) =>
           structureItem(Option.none(), Option.some('icon-' + letter))(s, str, arr)
         )
       }),
       s.element('div', {
         classes: [ arr.has('tox-collection__group') ],
         children: Arr.map([ 'I' ], (letter) =>
           structureItem(Option.none(), Option.some('icon-' + letter))(s, str, arr)
         )
       })
     ]
   });
 })
Example #9
0
const pluginLister = function (editor) {
  const pluginKeys = getPluginKeys(editor);
  const pluginLis = Arr.map(pluginKeys, function (key) {
    return '<li>' + maybeUrlize(editor, key) + '</li>';
  });
  const count = pluginLis.length;
  const pluginsString = pluginLis.join('');

  return '<p><b>' + I18n.translate(['Plugins installed ({0}):', count ]) + '</b></p>' +
          '<ul>' + pluginsString + '</ul>';
};
Example #10
0
const sSetValueAndTrigger = (selector, value, events: string[]) => (ui) => {
  return Logger.t(`Set ${value} and trigger ${events.join(',')}`, Chain.asStep({}, [
    Chain.fromChains([
      cFindInDialog(selector)(ui),      // get the element
      Chain.op(Focus.focus),            // fire focusin, required by sizeinput to recalc ratios
      cSetValueOn(selector, value)(ui), // change the value
      ...Arr.map(events, (event) => cFakeEvent(event)),                 // fire [change, input etc],
      Chain.wait(0) // Wait needed as paste event is triggered async
    ])
  ]));
};
Example #11
0
export const renderSelectBox = (spec: Types.SelectBox.SelectBox, providersBackstage: UiFactoryBackstageProviders): SketchSpec => {
  const translatedOptions = Arr.map(spec.items, (item) => {
    return {
      text: providersBackstage.translate(item.text),
      value: item.value
    };
  });

  // DUPE with TextField.
  const pLabel = spec.label.map((label) => renderLabel(label, providersBackstage));

  const pField = AlloyFormField.parts().field({
    // TODO: Alloy should not allow dom changing of an HTML select!
    dom: {  },
    selectAttributes: {
      size: spec.size
    },
    options: translatedOptions,
    factory: AlloyHtmlSelect,
    selectBehaviours: Behaviour.derive([
      Tabstopping.config({ }),
      AddEventsBehaviour.config('selectbox-change', [
        AlloyEvents.run(NativeEvents.change(), (component, _) => {
          AlloyTriggers.emitWith(component, formChangeEvent, { name: spec.name } );
        })
      ])
    ])
  });

  const chevron = spec.size > 1 ? Option.none() :
    Option.some({
        dom: {
          tag: 'div',
          classes: ['tox-selectfield__icon-js'],
          innerHtml: Icons.get('chevron-down', providersBackstage.icons)
        }
      });

  const selectWrap: SimpleSpec = {
    dom: {
      tag: 'div',
      classes: ['tox-selectfield']
    },
    components: Arr.flatten([[pField], chevron.toArray()])
  };

  return AlloyFormField.sketch({
    dom: {
      tag: 'div',
      classes: ['tox-form__group']
    },
    components: Arr.flatten<AlloySpec>([pLabel.toArray(), [selectWrap]])
  });
};
Example #12
0
const selectionIndentation = (editor: Editor, indentation: IndentValue) => {
  const dlItems = Arr.map(Selection.getSelectedDlItems(editor), Element.fromDom);
  const lists = Arr.map(Selection.getSelectedListRoots(editor), Element.fromDom);

  if (dlItems.length || lists.length) {
    const bookmark = editor.selection.getBookmark();

    dlIndentation(editor, indentation, dlItems);

    listsIndentation(
      editor,
      lists,
      indentation
    );

    editor.selection.moveToBookmark(bookmark);
    editor.selection.setRng(Range.normalizeRange(editor.selection.getRng()));
    editor.nodeChanged();
  }
};
 fetch: (callback) => {
   callback(
     Arr.map([ '1', '2', '3', '4', '5', '6', '7', '8' ], (num) => {
       return {
         type: 'choiceitem',
         value: num,
         text: num,
         icon: 'fake-icon-name'
       } as Menu.ChoiceMenuItemApi;
     })
   );
 },
Example #14
0
 getItems: (value) => {
   return Arr.map([
     {
       value: 'https://www.tinymce.com',
       text: 'My page 1'
     },
     {
       value: 'https://www.ephox.com',
       text: 'My page 2'
     }
   ], (d) => makeItem(d.text));
 }
Example #15
0
const defaultPatterns = (patterns: KeyPattern[]): KeyPattern[] => {
  return Arr.map(patterns, (pattern) => {
    return Merger.merge({
      shiftKey: false,
      altKey: false,
      ctrlKey: false,
      metaKey: false,
      keyCode: 0,
      action: Fun.noop
    }, pattern);
  });
};
Example #16
0
  return Arr.map(table.rows(), function (row) {
    const cells = Arr.map(row.cells(), function (cell) {
      const td = Replication.deep(cell);
      Attr.remove(td, 'colspan');
      Attr.remove(td, 'rowspan');
      return td;
    });

    const tr = Replication.shallow(row.element());
    InsertAll.append(tr, cells);
    return tr;
  });
Example #17
0
const getRectsFromRange = function (range) {
  if (! range.collapsed) {
    return Arr.map(range.getClientRects(), toRect);
  } else {
    const start = Element.fromDom(range.startContainer);
    return Traverse.parent(start).bind(function (parent) {
      const selection = Selection.exact(start, range.startOffset, parent, Awareness.getEnd(parent));
      const optRect = WindowSelection.getFirstRect(range.startContainer.ownerDocument.defaultView, selection);
      return optRect.map(collapsedRect).map(Arr.pure);
    }).getOr([ ]);
  }
};
const defaultPatterns = function (patterns) {
  return Arr.map(patterns, function (pattern) {
    return Merger.merge({
      shiftKey: false,
      altKey: false,
      ctrlKey: false,
      metaKey: false,
      keyCode: 0,
      action: Fun.noop
    }, pattern);
  });
};
Example #19
0
 const sCheckSections = (sections: TestSection[]) => {
   return Log.stepsAsStep('TBA', 'Link: Settings: ' + getStr(sections), [
     GeneralSteps.sequence(
       Arr.map(sections, ({ setting }) => setting.value.map((v) => tinyApis.sSetSetting(setting.key, v)).getOrThunk(() => {
         return tinyApis.sDeleteSetting(setting.key);
       }))
     ),
     TestLinkUi.sOpenLinkDialog,
     GeneralSteps.sequence(
       Arr.map(
         sections,
         ({ selector, exists }) => {
           console.log('selector', selector, 'exists', exists);
           const sExistence = exists ? UiFinder.sExists : UiFinder.sNotExists;
           return sExistence(TinyDom.fromDom(document.body), selector);
         }
       )
     ),
     TestLinkUi.sClickOnDialog('click on cancel', 'button:contains("Cancel")')
   ]);
 };
Example #20
0
 const submenus = Obj.map(formats.menus, function (menuItems, menuName) {
   const items = Arr.map(menuItems, function (item) {
     return makeItem(
       getValue(item),
       item.title,
       item.isSelected !== undefined ? item.isSelected() : false,
       item.getPreview !== undefined ? item.getPreview() : '',
       Objects.hasKey(formats.expansions, getValue(item))
     );
   });
   return makeMenu(menuName, items, memMenuThunk, true);
 });
Example #21
0
const removeUnusedDefaults = (buttons) => {
  const filteredItemGroups = Arr.map(defaultToolbar, (group) => {
    const items = Arr.filter(group.items, (subItem) => {
      return Obj.has(buttons, subItem) || Obj.has(bespokeButtons as any, subItem);
    });
    return {
      name: group.name,
      items
    };
  });
  return Arr.filter(filteredItemGroups, (group) => group.items.length > 0);
};
Example #22
0
  const equalTargets = function (actualTargets, expectedTargets, message) {
    const nonAttachedTargets = Arr.map(actualTargets, function (target) {
      return {
        level: target.level,
        title: target.title,
        type: target.type,
        url: target.url
      };
    });

    LegacyUnit.deepEqual(nonAttachedTargets, expectedTargets, message);
  };
 Assertions.cAssertStructure('Checking structure', ApproxStructure.build((s, str, arr) => {
   return s.element('div', {
     classes: [ arr.has('tox-collection__group') ],
     children: Arr.map(expectedTicks, (expected) => {
       return s.element('div', {
         attrs: {
           'role': str.is('menuitemcheckbox'),
           'aria-checked': str.is(expected ? 'true' : 'false')
         }
       });
     })
   });
 }))
Example #24
0
const deleteLastPosition = function (forward, editor, target, parentInlines) {
  const isFormatElement = Fun.curry(CaretFormat.isFormatElement, editor);
  const formatNodes = Arr.map(Arr.filter(parentInlines, isFormatElement), function (elm) {
    return elm.dom();
  });

  if (formatNodes.length === 0) {
    DeleteElement.deleteElement(editor, forward, target);
  } else {
    const pos = CaretFormat.replaceWithCaretFormat(target.dom(), formatNodes);
    editor.selection.setRng(pos.toRange());
  }
};
Example #25
0
const filterDescendants = function (scope, predicate) {
  let result = [];
  const dom = scope.dom();
  const children = Arr.map(dom.childNodes, Element.fromDom);

  Arr.each(children, function (x) {
    if (predicate(x)) {
      result = result.concat([ x ]);
    }
    result = result.concat(filterDescendants(x, predicate));
  });
  return result;
};
Example #26
0
 AlloyForm.sketch((parts) => {
   return {
     dom: {
       tag: 'div',
       classes: [ 'tox-form' ]
     },
     // All of the items passed through the form need to be put through the interpreter
     // with their form part preserved.
     components: Arr.map(spec.items, (item) => {
       return interpretInForm(parts, item, backstage);
     })
   };
 })
Example #27
0
const getPatternSet = (editorSettings): PatternSet => {
  const patterns = Obj.get(editorSettings, 'textpattern_patterns').getOr(defaultPatterns);
  if (!Type.isArray(patterns)) {
    error('The setting textpattern_patterns should be an array');
    return {
      inlinePatterns: [],
      blockPatterns: [],
    };
  }
  const normalized = Results.partition(Arr.map(patterns, normalizePattern));
  Arr.each(normalized.errors, (err) => error(err.message, err.pattern));
  return createPatternSet(normalized.values);
};
Example #28
0
const getContentCss = (editor: Editor): string[] => {
  const contentCss = editor.settings.content_css;

  if (Type.isString(contentCss)) {
    return Arr.map(contentCss.split(','), Strings.trim);
  } else if (Type.isArray(contentCss)) {
    return contentCss;
  } else if (contentCss === false || editor.inline) {
    return [];
  } else {
    return ['default'];
  }
};
Example #29
0
  const loadAll = function (urls: string[], success: Function, failure: Function) {
    Futures.par(Arr.map(urls, loadF)).get(function (result) {
      const parts = Arr.partition(result, function (r) {
        return r.isValue();
      });

      if (parts.fail.length > 0) {
        failure(parts.fail.map(unbox));
      } else {
        success(parts.pass.map(unbox));
      }
    });
  };
Example #30
0
 const renderHeader = (header: string[]) => ({
   dom: {
     tag: 'thead'
   },
   components: [
     {
       dom: {
         tag: 'tr'
       },
       components: Arr.map(header, renderTh)
     }
   ]
 });