Java Code Examples for com.google.gwt.dom.client.Document

The following examples show how to use com.google.gwt.dom.client.Document. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: swellrt   Source File: EditorEventHandlerGwtTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the event handler normalises the selection when necessary
 * Note that this is currently just for firefox.
 */
public void testNormalisesSelection() {
  FakeEditorEvent fakeEvent = FakeEditorEvent.create(KeySignalType.INPUT, 'a');
  final Point<ContentNode> caret =
      Point.<ContentNode> end(newParaElement());

  EditorEventsSubHandler subHandler = new FakeEditorEventsSubHandler();
  FakeEditorInteractor interactor = setupFakeEditorInteractor(new FocusedContentRange(caret));
  final Point<ContentNode> newCaret = Point.<ContentNode>inText(
      new ContentTextNode(Document.get().createTextNode("hi"), null), 2);
  interactor.call(FakeEditorInteractor.NORMALIZE_POINT).returns(newCaret);
  interactor.call(FakeEditorInteractor.SET_CARET).nOf(1).withArgs(newCaret);
  interactor.call(FakeEditorInteractor.NOTIFYING_TYPING_EXTRACTOR).nOf(1).withArgs(
      newCaret, false);
  EditorEventHandler handler = createEditorEventHandler(interactor, subHandler);

  handler.handleEvent(fakeEvent);
  interactor.checkExpectations();
}
 
Example 2
private void resetInner() {
	this.anchor.getElement().removeAllChildren();
	if (this.iconType != null) {
		Icon icon = new Icon();
		icon.setType(this.iconType);

		this.anchor.getElement().appendChild(icon.getElement());
	}
	if (this.label != null) {
		Text textElem = Document.get().createTextNode(this.label);
		this.anchor.getElement().appendChild(textElem);
	}
	Text spaceElem = Document.get().createTextNode(" ");
	this.anchor.getElement().appendChild(spaceElem);
	this.anchor.getElement().appendChild(this.caret);
}
 
Example 3
@Override
public void init(String userAccount) {
  Element firstScript = Document.get().getElementsByTagName("script").getItem(0);

  ScriptElement config = Document.get().createScriptElement(
      "var _gaq = _gaq || [];_gaq.push(['_setAccount', '" + userAccount
          + "']);_gaq.push (['_gat._anonymizeIp']);_gaq.push(['_trackPageview']);");

  firstScript.getParentNode().insertBefore(config, firstScript);

  ScriptElement script = Document.get().createScriptElement();

  // Add the google analytics script.
  script.setSrc(("https:".equals(Window.Location.getProtocol())
      ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js");
  script.setType("text/javascript");
  script.setAttribute("async", "true");

  firstScript.getParentNode().insertBefore(script, firstScript);
}
 
Example 4
/**
 * Ensure that new keybindings are used after changing them in the editor.
 */
public void testReregistrationKeyBinding() {
  KeyBindingRegistry bindings = new KeyBindingRegistry();
  callTracker = 0;
  EditorAction testAction = new EditorAction() {
    public void execute(EditorContext context) {
      callTracker++;
    }
  };
  bindings.registerAction(KeyCombo.ORDER_G, testAction);

  EditorImpl editor = createEditor(bindings);
  Event rawEvent = Document.get().createKeyPressEvent(
      true, false, false, false, G_CODE, G_CODE).cast();
  editor.onJavaScriptEvent("keypress", rawEvent);
  // callTracker should be 1 assuming the test above passes

  bindings.removeAction(KeyCombo.ORDER_G);
  initEditor(editor, Editor.ROOT_REGISTRIES, bindings);
  editor.onJavaScriptEvent("keypress", rawEvent);
  assertEquals("Callback action called on deregistered keypress", callTracker, 1);
}
 
Example 5
@Test
@Description("Exception occures when processing serialized data structure for preparing the drop targets to show.")
public void exceptionWhenProcessingDropTargetHintsDataStructure() {
    final ViewComponentClientCriterion cut = new ViewComponentClientCriterion();

    // prepare configuration:
    final Document document = Document.get();
    final UIDL uidl = GWT.create(UIDL.class);
    when(uidl.getIntAttribute("cda")).thenReturn(2);
    when(uidl.getStringAttribute("da0")).thenReturn("no-problem");
    when(uidl.getStringAttribute("da1")).thenReturn("problem-bear");
    doThrow(new RuntimeException()).when(uidl).getStringAttribute("da1");

    // act
    try {
        cut.showDropTargetHints(uidl);
    } catch (final RuntimeException re) {
        fail("Exception is not re-thrown in order to continue with the loop");
    }

    // assure that no-problem was invoked anyway
    verify(document).getElementById("no-problem");

    // cross-check that problem-bear was never invoked
    verify(document, Mockito.times(0)).getElementById("problem-bear");
}
 
Example 6
Source Project: incubator-retired-wave   Source File: DomLogger.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Appends an entry to the log panel.
 * @param formatted
 * @param level
 */
public static void appendEntry(String formatted, Level level) {
  DivElement entry = Document.get().createDivElement();
  entry.setClassName(RESOURCES.css().entry());
  entry.setInnerHTML(formatted);

  // Add the style name associated with the log level.
  switch (level) {
    case ERROR:
      entry.addClassName(RESOURCES.css().error());
      break;
    case FATAL:
      entry.addClassName(RESOURCES.css().fatal());
      break;
    case TRACE:
      entry.addClassName(RESOURCES.css().trace());
      break;
  }

  // Make fatals detectable by WebDriver, so that tests can early out on
  // failure:
  if (level.equals(Level.FATAL)) {
    latestFatalError = formatted;
  }
  writeOrCacheOutput(entry);
}
 
Example 7
Source Project: dashbuilder   Source File: NavRootNodeEditorView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addCommand(String name, Command command) {
    AnchorElement anchor = Document.get().createAnchorElement();
    anchor.setInnerText(name);

    LIElement li = Document.get().createLIElement();
    li.getStyle().setCursor(Style.Cursor.POINTER);
    li.appendChild(anchor);
    commandMenu.appendChild((Node) li);

    Event.sinkEvents(anchor, Event.ONCLICK);
    Event.setEventListener(anchor, event -> {
        if(Event.ONCLICK == event.getTypeInt()) {
            command.execute();
        }
    });
}
 
Example 8
/** Ensure that when other keys are pressed, they are not passed to the action. */
public void testAlternativeKeyPress() {
  KeyBindingRegistry bindings = new KeyBindingRegistry();
  callTracker = 0;
  EditorAction testAction = new EditorAction() {
    public void execute(EditorContext context) {
      callTracker++;
    }
  };
  bindings.registerAction(KeyCombo.ORDER_G, testAction);
  EditorImpl editor = createEditor(bindings);

  // This event is not ORDER_G, it has other accelerators thrown in.
  Event rawEvent = Document.get().createKeyPressEvent(
      true, true, true, false, G_CODE, G_CODE).cast();
  editor.onJavaScriptEvent("keypress", rawEvent);
  assertEquals("Callback action called on unregistered keypress", callTracker, 0);
}
 
Example 9
Source Project: gwt-material-addins   Source File: MaterialWindow.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onLoad() {
    super.onLoad();

    // Add handlers to action buttons
    registerHandler(iconMaximize.addClickHandler(event -> toggleMaximize()));

    registerHandler(toolbar.addDoubleClickHandler(event -> {
        toggleMaximize();
        Document.get().getDocumentElement().getStyle().setCursor(Style.Cursor.DEFAULT);
    }));

    registerHandler(iconClose.addClickHandler(event -> {
        if (!preventClose) {
            if (!isOpen()) {
                open();
            } else {
                close();
            }
        }
    }));

    AddinsDarkThemeReloader.get().reload(MaterialWindowDarkTheme.class);
}
 
Example 10
Source Project: bitcoin-transaction-explorer   Source File: ConfigViewImpl.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void setValue(final AdministratedApplicationConfig value, final boolean fireEvents) {
  for (int i = 0; i < connectorListBox.getItemCount(); i++) {
    if(connectorListBox.getValue(i).equals(value.getBlockchainSource().name())) {
      connectorListBox.setSelectedIndex(i);
      DomEvent.fireNativeEvent(Document.get().createChangeEvent(), connectorListBox);
      break;
    }
  }

  currentEditor.setValue(value);

  applicationTitle.setText(value.getApplicationTitle());
  applicationSubtitle.setText(value.getApplicationSubTitle());
  donationAddress.setText(value.getHostDonationAddress());
}
 
Example 11
Source Project: unitime   Source File: MapWidget.java    License: Apache License 2.0 6 votes vote down vote up
public static void insert(final RootPanel panel) {
	RPC.execute(new MapPropertiesRequest(), new AsyncCallback<MapPropertiesInterface>() {
		@Override
		public void onFailure(Throwable caught) {
		}

		@Override
		public void onSuccess(MapPropertiesInterface result) {
			MapWidget map = MapWidget.createMap(TextBox.wrap(Document.get().getElementById("coordX")), TextBox.wrap(Document.get().getElementById("coordY")), result);
			if (map != null) {
				panel.add(map);
				panel.setVisible(true);
				map.onShow();
			}
		}
	});
}
 
Example 12
Source Project: gwt-material   Source File: MaterialSwitch.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a switch element
 */
public MaterialSwitch() {
    super(Document.get().createDivElement(), CssName.SWITCH);
    span.setStyleName(CssName.LEVER);
    input.setType(InputType.CHECKBOX);
    setAsyncDisplayLoader(new DefaultSwitchLoader(this));
}
 
Example 13
Source Project: swellrt   Source File: ParagraphNiceHtmlRenderer.java    License: Apache License 2.0 5 votes vote down vote up
private ContentNode renderHeadingItem(
    ReadableDocumentView<ContentNode, ContentElement, ContentTextNode> view,
    Element dest, ContentElement src,
    SelectionMatcher selectionMatcher) {
  Element e = Document.get().createHElement(Paragraph.getHeadingSize(src));
  dest.appendChild(e);
  doInnards(view, e, src, selectionMatcher);
  return src;
}
 
Example 14
Source Project: lumongo   Source File: PlaceHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void initGA() {
	Document doc = Document.get();
	ScriptElement script = doc.createScriptElement();
	script.setSrc("https://ssl.google-analytics.com/ga.js");
	script.setType("text/javascript");
	script.setLang("javascript");
	doc.getBody().appendChild(script);
}
 
Example 15
Source Project: consulo   Source File: CellTreeNodeView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update the image based on the current state.
 *
 * @param isLoading true if still loading data
 */
private void updateImage(boolean isLoading) {
  // Early out if this is a root node.
  if (isRootNode()) {
    return;
  }

  // Replace the image element with a new one.
  boolean isTopLevel = parentNode.isRootNode();
  SafeHtml html = tree.getClosedImageHtml(isTopLevel);
  if (open) {
    html = isLoading ? tree.getLoadingImageHtml() : tree.getOpenImageHtml(isTopLevel);
  }
  if (nodeInfoLoaded && nodeInfo == null) {
    html = LEAF_IMAGE;
  }
  Element tmp = Document.get().createDivElement();
  tmp.setInnerSafeHtml(html);
  Element imageElem = tmp.getFirstChildElement();

  Element oldImg = getImageElement();
  oldImg.getParentElement().replaceChild(imageElem, oldImg);

  // Set 'aria-expanded' state
  // don't set aria-expanded on the leaf nodes
  if (isLeaf()) {
    Roles.getTreeitemRole().removeAriaExpandedState(getElement());
  }
  else {
    Roles.getTreeitemRole().setAriaExpandedState(getElement(), ExpandedValue.of(open));
  }
}
 
Example 16
Source Project: cuba   Source File: CubaFileUploadProgressWindow.java    License: Apache License 2.0 5 votes vote down vote up
private void hideModalityCurtain() {
    Document.get().getBody().removeClassName(MODAL_WINDOW_OPEN_CLASSNAME);

    modalityCurtain.removeFromParent();

    if (BrowserInfo.get().isIE()) {
        // IE leaks memory in certain cases unless we release the reference
        // (#9197)
        modalityCurtain = null;
    }
}
 
Example 17
@PresentHandler
void presentAddressBook(AddressBookPlace place) {
	Document.get().setTitle("PWT - Sample - Address book");

	List<Group> groups = ContactService.get().getGroups();
	Collection<String> groupsItems = Lists.newArrayList();
	for (int i = 1; i < groups.size(); i++) {
		groupsItems.add(groups.get(i).getName());
	}
	this.groupSelect.setItems(groupsItems);
	this.groupsList.edit(groups);
	this.displayGroup(groups.get(0));
}
 
Example 18
Source Project: swellrt   Source File: IeNodeletHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Some IE element classes require their html nodelets be attached to
 * somewhere under the body of html document in order for implementation to
 * work. See, e.g., {@link ParagraphHelperIE#onEmpty(Element)}
 */
public static Point<Node> beforeImplementation(Element nodelet) {
  // Get point after nodelet
  Point<Node> point = nodelet.getParentNode() != null ?
      Point.inElement(nodelet.getParentNode(), nodelet.getNextSibling()) : null;
  // Attach nodelet to document body
  Document.get().getBody().appendChild(nodelet);
  return point;
}
 
Example 19
Source Project: incubator-retired-wave   Source File: StageOne.java    License: Apache License 2.0 5 votes vote down vote up
/** @return the container of the wave panel. Subclasses may override. */
protected Element createWaveHolder() {
  Element panel = Document.get().getElementById("initialHtml");
  if (panel == null) {
    throw new RuntimeException("Page is malformed: no wave frame.");
  }
  return panel;
}
 
Example 20
/**
 * Creates an xml block structure from a model, and injects it into the page.
 */
private XmlStructure createXml(ConversationView model) {
  String xml =
      XmlRenderer.render(new ViewIdMapper(ModelIdMapperImpl.create(model, "empty")), model);
  Element dom = Document.get().createElement("xml");
  dom.setInnerHTML(xml);
  Document.get().getBody().appendChild(dom);
  return XmlStructure.create(XmlRenderer.ROOT_ID);
}
 
Example 21
@Override
public void prepareForPaste() {
  element.setInnerHTML("");
  element.appendChild(Document.get().createTextNode(MARKER_NODE_STRING));
  NativeSelectionUtil.setCaret(Point.inText(element.getFirstChild(), 1));
  markersStripped = false;
}
 
Example 22
Source Project: gwt-material-addins   Source File: MaterialCutOut.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the computed background color, based on the backgroundColor CSS
 * class.
 */
protected void setupComputedBackgroundColor() {
    // temp is just a widget created to evaluate the computed background
    // color
    MaterialWidget temp = new MaterialWidget(Document.get().createDivElement());
    temp.setBackgroundColor(backgroundColor);

    // setting a style to make it invisible for the user
    Style style = temp.getElement().getStyle();
    style.setPosition(Position.FIXED);
    style.setWidth(1, Unit.PX);
    style.setHeight(1, Unit.PX);
    style.setLeft(-10, Unit.PX);
    style.setTop(-10, Unit.PX);
    style.setZIndex(-10000);

    // adding it to the body (on Chrome the component must be added to the
    // DOM before getting computed values).
    String computed = ColorHelper.setupComputedBackgroundColor(backgroundColor);

    // convert rgb to rgba, considering the opacity field
    if (opacity < 1 && computed.startsWith("rgb(")) {
        computed = computed.replace("rgb(", "rgba(").replace(")", ", " + opacity + ")");
    }

    computedBackgroundColor = computed;
}
 
Example 23
Source Project: swellrt   Source File: WebClient.java    License: Apache License 2.0 5 votes vote down vote up
private void setupWavePanel() {
  // Hide the frame until waves start getting opened.
  UIObject.setVisible(waveFrame.getElement(), false);

  Document.get().getElementById("signout").setInnerText(messages.signout());

  // Handles opening waves.
  ClientEvents.get().addWaveSelectionEventHandler(new WaveSelectionEventHandler() {
    @Override
    public void onSelection(WaveRef waveRef) {
      openWave(waveRef, false, null);
    }
  });
}
 
Example 24
Source Project: hawkbit   Source File: ViewClientCriterionTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Process serialized config for hiding the drop hints.")
public void processSerializedDropTargetHintsConfig() {
    final ViewClientCriterion cut = new ViewClientCriterion();

    // prepare configuration:
    final Document document = Document.get();
    final UIDL uidl = GWT.create(UIDL.class);
    when(uidl.getIntAttribute("cdac")).thenReturn(3);
    final Element[] elements = new Element[3];
    for (int i = 0; i < 3; i++) {
        when(uidl.getStringAttribute("dac" + String.valueOf(i))).thenReturn("itemId" + String.valueOf(i));
        elements[i] = Mockito.mock(Element.class);
        when(document.getElementById("itemId" + String.valueOf(i))).thenReturn(elements[i]);
    }

    // act
    try {
        cut.hideDropTargetHints(uidl);

        // assure invocation
        for (int i = 0; i < 3; i++) {
            verify(document).getElementById("itemId" + String.valueOf(i));
            verify(elements[i]).removeClassName(ViewComponentClientCriterion.HINT_AREA_STYLE);
        }

        // cross-check
        verify(document, Mockito.never()).getElementById("itemId3");

    } finally {
        reset(Document.get());
    }
}
 
Example 25
Source Project: swellrt   Source File: ContentTextNodeGwtTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testContentDataInitialisedFromNodelet() {
  ContentDocument dom = TestEditors.createTestDocument();

  ContentTextNode txt = new ContentTextNode(
      Document.get().createTextNode("abc"),
      dom.debugGetContext());
  assertEquals("abc", txt.getData());
}
 
Example 26
Source Project: gwt-material-addins   Source File: MaterialMasonry.java    License: Apache License 2.0 5 votes vote down vote up
public MaterialMasonry() {
    super(Document.get().createDivElement(), AddinsCssName.MASONRY, CssName.ROW);

    sizerDiv.setWidth("8.3333%");
    sizerDiv.setStyleName(AddinsCssName.COL_SIZER);
    add(sizerDiv);
}
 
Example 27
Source Project: hawkbit   Source File: ViewClientCriterionTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Check multi row drag decoration with a single item dragged while a multi selection is active in table")
public void processMultiRowDragDecorationMultiSelectionNotDragged() {
    final ViewClientCriterion cut = new ViewClientCriterion();

    // prepare table
    final VScrollTable table = Mockito.spy(new VScrollTable());
    table.selectedRowKeys.add("one");
    table.selectedRowKeys.add("two");
    table.focusedRow = Mockito.mock(VScrollTable.VScrollTableBody.VScrollTableRow.class);
    when(table.focusedRow.getKey()).thenReturn("another");

    // prepare drag-event with table widget:
    final VDragEvent dragEvent = CriterionTestHelper.createMockedVDragEvent("thisId", table);

    // prepare document
    final Document document = Document.get();
    final Element ele = Mockito.mock(Element.class);
    when(document.getElementById(ViewClientCriterion.SP_DRAG_COUNT)).thenReturn(ele);

    try {
        // act
        cut.setMultiRowDragDecoration(dragEvent);

        // assure that multi-row decoration for the table was processed
        verify(document).getElementById(ViewClientCriterion.SP_DRAG_COUNT);

        // assure that no multi selection was detected
        verify(ele).removeFromParent();
    } finally {
        reset(Document.get());
    }
}
 
Example 28
Source Project: swellrt   Source File: ImeExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public static void register(ElementHandlerRegistry registry) {
  registry.registerRenderer(WRAPPER_TAGNAME, new Renderer() {
    @Override
    public Element createDomImpl(Renderable element) {
      return element.setAutoAppendContainer(Document.get().createSpanElement());
    }
  });
}
 
Example 29
Source Project: gwt-material   Source File: MaterialRangeTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testChangeHandler() {
    MaterialRange range = getWidget();

    final boolean[] firedEvent = {false};
    range.addChangeHandler(changeEvent -> firedEvent[0] = true);
    ChangeEvent.fireNativeEvent(Document.get().createChangeEvent(), range.getRangeInputElement());
    assertTrue(firedEvent[0]);
}
 
Example 30
Source Project: requestor   Source File: Page.java    License: Apache License 2.0 5 votes vote down vote up
private static void setPageElementText(String id, String title, boolean alignCenter) {
    final Element e = Document.get().getElementById(id);
    e.setInnerText(title);
    if (alignCenter) {
        e.addClassName("text-center");
    } else {
        e.removeClassName("text-center");
    }
}