From 6bf0a5cb5034a7e684dcc3500e841785237ce2dd Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 19:32:43 +0200 Subject: Adding upstream version 1:115.7.0. Signed-off-by: Daniel Baumann --- devtools/client/styleeditor/StyleEditorUI.sys.mjs | 1761 ++++++++ .../client/styleeditor/StyleEditorUtil.sys.mjs | 213 + .../client/styleeditor/StyleSheetEditor.sys.mjs | 1040 +++++ devtools/client/styleeditor/index.xhtml | 238 ++ devtools/client/styleeditor/moz.build | 18 + devtools/client/styleeditor/original-source.js | 103 + devtools/client/styleeditor/panel.js | 171 + devtools/client/styleeditor/test/autocomplete.html | 23 + devtools/client/styleeditor/test/browser.ini | 141 + .../test/browser_styleeditor_add_stylesheet.js | 36 + .../test/browser_styleeditor_at_rules_sidebar.js | 312 ++ .../browser_styleeditor_autocomplete-disabled.js | 42 + .../test/browser_styleeditor_autocomplete.js | 284 ++ .../styleeditor/test/browser_styleeditor_bom.js | 37 + ...itor_bug_1247083_inline_stylesheet_numbering.js | 104 + ...tyleeditor_bug_1405342_serviceworker_iframes.js | 27 + .../test/browser_styleeditor_bug_740541_iframes.js | 107 + .../browser_styleeditor_bug_851132_middle_click.js | 63 + .../test/browser_styleeditor_bug_870339.js | 49 + .../test/browser_styleeditor_copyurl.js | 43 + .../test/browser_styleeditor_enabled.js | 129 + .../browser_styleeditor_fetch-from-netmonitor.js | 80 + .../test/browser_styleeditor_filesave.js | 91 + .../styleeditor/test/browser_styleeditor_filter.js | 343 ++ .../browser_styleeditor_fission_switch_target.js | 33 + .../test/browser_styleeditor_highlight-selector.js | 199 + .../styleeditor/test/browser_styleeditor_import.js | 54 + .../test/browser_styleeditor_import_rule.js | 32 + .../styleeditor/test/browser_styleeditor_init.js | 52 + .../browser_styleeditor_inline_friendly_names.js | 101 + .../test/browser_styleeditor_loading.js | 36 + .../browser_styleeditor_loading_with_containers.js | 70 + .../browser_styleeditor_media_sidebar_links.js | 158 + ...browser_styleeditor_media_sidebar_sourcemaps.js | 62 + .../test/browser_styleeditor_missing_stylesheet.js | 37 + .../test/browser_styleeditor_navigate.js | 31 + .../styleeditor/test/browser_styleeditor_new.js | 97 + .../test/browser_styleeditor_nostyle.js | 56 + .../test/browser_styleeditor_opentab.js | 133 + .../styleeditor/test/browser_styleeditor_pretty.js | 82 + .../browser_styleeditor_private_perwindowpb.js | 76 + .../styleeditor/test/browser_styleeditor_reload.js | 42 + .../test/browser_styleeditor_resize_performance.js | 62 + .../styleeditor/test/browser_styleeditor_scroll.js | 96 + .../test/browser_styleeditor_selectstylesheet.js | 25 + .../test/browser_styleeditor_sidebars.js | 67 + .../test/browser_styleeditor_sourcemap_chrome.js | 47 + .../test/browser_styleeditor_sourcemap_large.js | 34 + .../test/browser_styleeditor_sourcemap_watching.js | 155 + .../test/browser_styleeditor_sourcemaps.js | 152 + .../test/browser_styleeditor_sourcemaps_inline.js | 89 + .../test/browser_styleeditor_sv_keynav.js | 85 + .../test/browser_styleeditor_sv_resize.js | 53 + .../styleeditor/test/browser_styleeditor_sync.js | 73 + .../test/browser_styleeditor_syncAddProperty.js | 52 + .../test/browser_styleeditor_syncAddRule.js | 30 + .../test/browser_styleeditor_syncAlreadyOpen.js | 50 + .../test/browser_styleeditor_syncEditSelector.js | 38 + .../test/browser_styleeditor_syncIntoRuleView.js | 41 + .../test/browser_styleeditor_transition_rule.js | 51 + .../styleeditor/test/browser_styleeditor_xul.js | 23 + .../test/browser_toolbox_styleeditor.js | 100 + .../test/bug_1405342_serviceworker_iframes.html | 10 + devtools/client/styleeditor/test/doc_empty.html | 3 + .../test/doc_fetch_from_netmonitor.html | 13 + devtools/client/styleeditor/test/doc_long.css | 402 ++ .../client/styleeditor/test/doc_long_string.css | 43 + .../client/styleeditor/test/doc_short_string.css | 15 + .../styleeditor/test/doc_sourcemap_chrome.html | 11 + devtools/client/styleeditor/test/doc_xulpage.xhtml | 7 + devtools/client/styleeditor/test/four.html | 25 + devtools/client/styleeditor/test/head.js | 201 + .../styleeditor/test/iframe_service_worker.js | 12 + .../test/iframe_with_service_worker.html | 33 + devtools/client/styleeditor/test/import.css | 8 + devtools/client/styleeditor/test/import.html | 11 + devtools/client/styleeditor/test/import2.css | 8 + devtools/client/styleeditor/test/inline-1.html | 19 + devtools/client/styleeditor/test/inline-2.html | 19 + devtools/client/styleeditor/test/longload.html | 29 + devtools/client/styleeditor/test/longname.html | 12 + .../test/many-media-rules-sourcemaps/index.html | 11 + .../sourcemap/sourcemap-css/sourcemaps.css | 201 + .../sourcemap/sourcemap-css/sourcemaps.css.map | 10 + .../sourcemap/sourcemap-sass/_partial.scss | 25 + .../sourcemap/sourcemap-sass/sourcemaps.scss | 27 + .../styleeditor/test/media-rules-sourcemaps.html | 12 + devtools/client/styleeditor/test/media-rules.css | 29 + devtools/client/styleeditor/test/media-rules.html | 37 + devtools/client/styleeditor/test/media-small.css | 4 + devtools/client/styleeditor/test/media.html | 10 + devtools/client/styleeditor/test/minified.html | 15 + devtools/client/styleeditor/test/missing.html | 11 + devtools/client/styleeditor/test/nostyle.html | 5 + devtools/client/styleeditor/test/pretty.css | 2 + .../client/styleeditor/test/resources_inpage.jsi | 12 + .../client/styleeditor/test/resources_inpage1.css | 11 + .../client/styleeditor/test/resources_inpage2.css | 11 + .../styleeditor/test/selector-highlighter.html | 1 + devtools/client/styleeditor/test/simple.css | 7 + devtools/client/styleeditor/test/simple.css.gz | Bin 0 -> 166 bytes .../client/styleeditor/test/simple.css.gz^headers^ | 4 + devtools/client/styleeditor/test/simple.gz.html | 23 + devtools/client/styleeditor/test/simple.html | 24 + .../styleeditor/test/sjs_huge-css-server.sjs | 19 + .../styleeditor/test/sourcemap-css/contained.css | 4 + .../styleeditor/test/sourcemap-css/media-rules.css | 8 + .../test/sourcemap-css/media-rules.css.map | 6 + .../styleeditor/test/sourcemap-css/sourcemaps.css | 7 + .../test/sourcemap-css/sourcemaps.css.map | 6 + .../test/sourcemap-css/sourcemaps.css.map^headers^ | 2 + .../test/sourcemap-css/sourcemaps_chrome.css | 7 + .../test/sourcemap-css/test-bootstrap-scss.css | 4513 ++++++++++++++++++++ .../styleeditor/test/sourcemap-css/test-stylus.css | 7 + .../test/sourcemap-sass/media-rules.scss | 11 + .../test/sourcemap-sass/sourcemaps.scss | 10 + .../test/sourcemap-sass/sourcemaps.scss^headers^ | 2 + .../test/sourcemap-styl/test-stylus.styl | 7 + .../client/styleeditor/test/sourcemaps-inline.html | 17 + .../client/styleeditor/test/sourcemaps-large.html | 11 + .../styleeditor/test/sourcemaps-watching.html | 11 + devtools/client/styleeditor/test/sourcemaps.html | 13 + devtools/client/styleeditor/test/sync.html | 20 + devtools/client/styleeditor/test/sync_with_csp.css | 10 + .../client/styleeditor/test/sync_with_csp.html | 12 + devtools/client/styleeditor/test/test_private.css | 3 + devtools/client/styleeditor/test/test_private.html | 7 + devtools/client/styleeditor/test/utf-16.css | Bin 0 -> 156 bytes ...yveryverylongnamethatcanbreakthestyleeditor.css | 7 + 129 files changed, 14222 insertions(+) create mode 100644 devtools/client/styleeditor/StyleEditorUI.sys.mjs create mode 100644 devtools/client/styleeditor/StyleEditorUtil.sys.mjs create mode 100644 devtools/client/styleeditor/StyleSheetEditor.sys.mjs create mode 100644 devtools/client/styleeditor/index.xhtml create mode 100644 devtools/client/styleeditor/moz.build create mode 100644 devtools/client/styleeditor/original-source.js create mode 100644 devtools/client/styleeditor/panel.js create mode 100644 devtools/client/styleeditor/test/autocomplete.html create mode 100644 devtools/client/styleeditor/test/browser.ini create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_add_stylesheet.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_at_rules_sidebar.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_autocomplete-disabled.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_autocomplete.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bom.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bug_1247083_inline_stylesheet_numbering.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bug_1405342_serviceworker_iframes.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_bug_870339.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_copyurl.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_enabled.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_fetch-from-netmonitor.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_filesave.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_filter.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_fission_switch_target.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_import.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_import_rule.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_init.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_loading.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_loading_with_containers.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_links.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_sourcemaps.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_missing_stylesheet.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_navigate.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_new.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_nostyle.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_opentab.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_pretty.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_reload.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_resize_performance.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_scroll.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_selectstylesheet.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sidebars.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sourcemap_chrome.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sourcemap_large.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sourcemaps.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sourcemaps_inline.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sv_resize.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_sync.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_syncAddProperty.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_syncAddRule.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_syncAlreadyOpen.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_syncEditSelector.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_transition_rule.js create mode 100644 devtools/client/styleeditor/test/browser_styleeditor_xul.js create mode 100644 devtools/client/styleeditor/test/browser_toolbox_styleeditor.js create mode 100644 devtools/client/styleeditor/test/bug_1405342_serviceworker_iframes.html create mode 100644 devtools/client/styleeditor/test/doc_empty.html create mode 100644 devtools/client/styleeditor/test/doc_fetch_from_netmonitor.html create mode 100644 devtools/client/styleeditor/test/doc_long.css create mode 100644 devtools/client/styleeditor/test/doc_long_string.css create mode 100644 devtools/client/styleeditor/test/doc_short_string.css create mode 100644 devtools/client/styleeditor/test/doc_sourcemap_chrome.html create mode 100644 devtools/client/styleeditor/test/doc_xulpage.xhtml create mode 100644 devtools/client/styleeditor/test/four.html create mode 100644 devtools/client/styleeditor/test/head.js create mode 100644 devtools/client/styleeditor/test/iframe_service_worker.js create mode 100644 devtools/client/styleeditor/test/iframe_with_service_worker.html create mode 100644 devtools/client/styleeditor/test/import.css create mode 100644 devtools/client/styleeditor/test/import.html create mode 100644 devtools/client/styleeditor/test/import2.css create mode 100644 devtools/client/styleeditor/test/inline-1.html create mode 100644 devtools/client/styleeditor/test/inline-2.html create mode 100644 devtools/client/styleeditor/test/longload.html create mode 100644 devtools/client/styleeditor/test/longname.html create mode 100644 devtools/client/styleeditor/test/many-media-rules-sourcemaps/index.html create mode 100644 devtools/client/styleeditor/test/many-media-rules-sourcemaps/sourcemap/sourcemap-css/sourcemaps.css create mode 100644 devtools/client/styleeditor/test/many-media-rules-sourcemaps/sourcemap/sourcemap-css/sourcemaps.css.map create mode 100644 devtools/client/styleeditor/test/many-media-rules-sourcemaps/sourcemap/sourcemap-sass/_partial.scss create mode 100644 devtools/client/styleeditor/test/many-media-rules-sourcemaps/sourcemap/sourcemap-sass/sourcemaps.scss create mode 100644 devtools/client/styleeditor/test/media-rules-sourcemaps.html create mode 100644 devtools/client/styleeditor/test/media-rules.css create mode 100644 devtools/client/styleeditor/test/media-rules.html create mode 100644 devtools/client/styleeditor/test/media-small.css create mode 100644 devtools/client/styleeditor/test/media.html create mode 100644 devtools/client/styleeditor/test/minified.html create mode 100644 devtools/client/styleeditor/test/missing.html create mode 100644 devtools/client/styleeditor/test/nostyle.html create mode 100644 devtools/client/styleeditor/test/pretty.css create mode 100644 devtools/client/styleeditor/test/resources_inpage.jsi create mode 100644 devtools/client/styleeditor/test/resources_inpage1.css create mode 100644 devtools/client/styleeditor/test/resources_inpage2.css create mode 100644 devtools/client/styleeditor/test/selector-highlighter.html create mode 100644 devtools/client/styleeditor/test/simple.css create mode 100644 devtools/client/styleeditor/test/simple.css.gz create mode 100644 devtools/client/styleeditor/test/simple.css.gz^headers^ create mode 100644 devtools/client/styleeditor/test/simple.gz.html create mode 100644 devtools/client/styleeditor/test/simple.html create mode 100644 devtools/client/styleeditor/test/sjs_huge-css-server.sjs create mode 100644 devtools/client/styleeditor/test/sourcemap-css/contained.css create mode 100644 devtools/client/styleeditor/test/sourcemap-css/media-rules.css create mode 100644 devtools/client/styleeditor/test/sourcemap-css/media-rules.css.map create mode 100644 devtools/client/styleeditor/test/sourcemap-css/sourcemaps.css create mode 100644 devtools/client/styleeditor/test/sourcemap-css/sourcemaps.css.map create mode 100644 devtools/client/styleeditor/test/sourcemap-css/sourcemaps.css.map^headers^ create mode 100644 devtools/client/styleeditor/test/sourcemap-css/sourcemaps_chrome.css create mode 100644 devtools/client/styleeditor/test/sourcemap-css/test-bootstrap-scss.css create mode 100644 devtools/client/styleeditor/test/sourcemap-css/test-stylus.css create mode 100644 devtools/client/styleeditor/test/sourcemap-sass/media-rules.scss create mode 100644 devtools/client/styleeditor/test/sourcemap-sass/sourcemaps.scss create mode 100644 devtools/client/styleeditor/test/sourcemap-sass/sourcemaps.scss^headers^ create mode 100644 devtools/client/styleeditor/test/sourcemap-styl/test-stylus.styl create mode 100644 devtools/client/styleeditor/test/sourcemaps-inline.html create mode 100644 devtools/client/styleeditor/test/sourcemaps-large.html create mode 100644 devtools/client/styleeditor/test/sourcemaps-watching.html create mode 100644 devtools/client/styleeditor/test/sourcemaps.html create mode 100644 devtools/client/styleeditor/test/sync.html create mode 100644 devtools/client/styleeditor/test/sync_with_csp.css create mode 100644 devtools/client/styleeditor/test/sync_with_csp.html create mode 100644 devtools/client/styleeditor/test/test_private.css create mode 100644 devtools/client/styleeditor/test/test_private.html create mode 100644 devtools/client/styleeditor/test/utf-16.css create mode 100644 devtools/client/styleeditor/test/veryveryverylongnamethatcanbreakthestyleeditor.css (limited to 'devtools/client/styleeditor') diff --git a/devtools/client/styleeditor/StyleEditorUI.sys.mjs b/devtools/client/styleeditor/StyleEditorUI.sys.mjs new file mode 100644 index 0000000000..dc9b8ab3b5 --- /dev/null +++ b/devtools/client/styleeditor/StyleEditorUI.sys.mjs @@ -0,0 +1,1761 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +import { + loader, + require, +} from "resource://devtools/shared/loader/Loader.sys.mjs"; + +const EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +import { + getString, + text, + showFilePicker, + optionsPopupMenu, +} from "resource://devtools/client/styleeditor/StyleEditorUtil.sys.mjs"; +import { StyleSheetEditor } from "resource://devtools/client/styleeditor/StyleSheetEditor.sys.mjs"; + +const { PluralForm } = require("resource://devtools/shared/plural-form.js"); +const { PrefObserver } = require("resource://devtools/client/shared/prefs.js"); + +const KeyShortcuts = require("resource://devtools/client/shared/key-shortcuts.js"); + +const lazy = {}; + +loader.lazyRequireGetter( + lazy, + "KeyCodes", + "resource://devtools/client/shared/keycodes.js", + true +); + +loader.lazyRequireGetter( + lazy, + "OriginalSource", + "resource://devtools/client/styleeditor/original-source.js", + true +); + +ChromeUtils.defineESModuleGetters(lazy, { + FileUtils: "resource://gre/modules/FileUtils.sys.mjs", +}); +ChromeUtils.defineModuleGetter( + lazy, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); +loader.lazyRequireGetter( + lazy, + "ResponsiveUIManager", + "resource://devtools/client/responsive/manager.js" +); +loader.lazyRequireGetter( + lazy, + "openContentLink", + "resource://devtools/client/shared/link.js", + true +); +loader.lazyRequireGetter( + lazy, + "copyString", + "resource://devtools/shared/platform/clipboard.js", + true +); + +const LOAD_ERROR = "error-load"; +const PREF_AT_RULES_SIDEBAR = "devtools.styleeditor.showAtRulesSidebar"; +const PREF_SIDEBAR_WIDTH = "devtools.styleeditor.atRulesSidebarWidth"; +const PREF_NAV_WIDTH = "devtools.styleeditor.navSidebarWidth"; +const PREF_ORIG_SOURCES = "devtools.source-map.client-service.enabled"; + +const FILTERED_CLASSNAME = "splitview-filtered"; +const ALL_FILTERED_CLASSNAME = "splitview-all-filtered"; + +const HTML_NS = "http://www.w3.org/1999/xhtml"; + +/** + * StyleEditorUI is controls and builds the UI of the Style Editor, including + * maintaining a list of editors for each stylesheet on a debuggee. + * + * Emits events: + * 'editor-added': A new editor was added to the UI + * 'editor-selected': An editor was selected + * 'error': An error occured + * + */ +export class StyleEditorUI extends EventEmitter { + #activeSummary = null; + #commands; + #contextMenu; + #contextMenuStyleSheet; + #copyUrlItem; + #cssProperties; + #filter; + #filterInput; + #filterInputClearButton; + #loadingStyleSheets; + #nav; + #openLinkNewTabItem; + #optionsButton; + #optionsMenu; + #panelDoc; + #prefObserver; + #root; + #seenSheets = new Map(); + #shortcuts; + #side; + #sourceMapPrefObserver; + #styleSheetBoundToSelect; + #styleSheetToSelect; + /** + * Maps keyed by summary element whose value is an object containing: + * - {Element} details: The associated details element (i.e. container for CodeMirror) + * - {StyleSheetEditor} editor: The associated editor, for easy retrieval + */ + #summaryDataMap = new WeakMap(); + #toolbox; + #tplDetails; + #tplSummary; + #uiAbortController = new AbortController(); + #window; + + /** + * @param {Toolbox} toolbox + * @param {Object} commands Object defined from devtools/shared/commands to interact with the devtools backend + * @param {Document} panelDoc + * Document of the toolbox panel to populate UI in. + * @param {CssProperties} A css properties database. + */ + constructor(toolbox, commands, panelDoc, cssProperties) { + super(); + + this.#toolbox = toolbox; + this.#commands = commands; + this.#panelDoc = panelDoc; + this.#cssProperties = cssProperties; + this.#window = this.#panelDoc.defaultView; + this.#root = this.#panelDoc.getElementById("style-editor-chrome"); + + this.editors = []; + this.selectedEditor = null; + this.savedLocations = {}; + + this.#prefObserver = new PrefObserver("devtools.styleeditor."); + this.#prefObserver.on( + PREF_AT_RULES_SIDEBAR, + this.#onAtRulesSidebarPrefChanged + ); + this.#sourceMapPrefObserver = new PrefObserver( + "devtools.source-map.client-service." + ); + this.#sourceMapPrefObserver.on( + PREF_ORIG_SOURCES, + this.#onOrigSourcesPrefChanged + ); + } + + get cssProperties() { + return this.#cssProperties; + } + + get currentTarget() { + return this.#commands.targetCommand.targetFront; + } + + /* + * Index of selected stylesheet in document.styleSheets + */ + get selectedStyleSheetIndex() { + return this.selectedEditor + ? this.selectedEditor.styleSheet.styleSheetIndex + : -1; + } + + /** + * Initiates the style editor ui creation, and start to track TargetCommand updates. + * + * @params {Object} options + * @params {Object} options.stylesheetToSelect + * @params {StyleSheetResource} options.stylesheetToSelect.stylesheet + * @params {Integer} options.stylesheetToSelect.line + * @params {Integer} options.stylesheetToSelect.column + */ + async initialize(options = {}) { + this.createUI(); + + if (options.stylesheetToSelect) { + const { stylesheet, line, column } = options.stylesheetToSelect; + // If a stylesheet resource and its location was passed (e.g. user clicked on a stylesheet + // location in the rule view), we can directly add it to the list and select it + // before watching for resources, for improved performance. + if (stylesheet.resourceId) { + try { + await this.#handleStyleSheetResource(stylesheet); + await this.selectStyleSheet( + stylesheet, + line - 1, + column ? column - 1 : 0 + ); + } catch (e) { + console.error(e); + } + } + } + + await this.#toolbox.resourceCommand.watchResources( + [this.#toolbox.resourceCommand.TYPES.DOCUMENT_EVENT], + { onAvailable: this.#onResourceAvailable } + ); + await this.#commands.targetCommand.watchTargets({ + types: [this.#commands.targetCommand.TYPES.FRAME], + onAvailable: this.#onTargetAvailable, + onDestroyed: this.#onTargetDestroyed, + }); + + this.#startLoadingStyleSheets(); + await this.#toolbox.resourceCommand.watchResources( + [this.#toolbox.resourceCommand.TYPES.STYLESHEET], + { + onAvailable: this.#onResourceAvailable, + onUpdated: this.#onResourceUpdated, + } + ); + await this.#waitForLoadingStyleSheets(); + } + + /** + * Build the initial UI and wire buttons with event handlers. + */ + createUI() { + this.#filterInput = this.#root.querySelector(".devtools-filterinput"); + this.#filterInputClearButton = this.#root.querySelector( + ".devtools-searchinput-clear" + ); + this.#nav = this.#root.querySelector(".splitview-nav"); + this.#side = this.#root.querySelector(".splitview-side-details"); + this.#tplSummary = this.#root.querySelector( + "#splitview-tpl-summary-stylesheet" + ); + this.#tplDetails = this.#root.querySelector( + "#splitview-tpl-details-stylesheet" + ); + + const eventListenersConfig = { signal: this.#uiAbortController.signal }; + + // Add click event on the "new stylesheet" button in the toolbar and on the + // "append a new stylesheet" link (visible when there are no stylesheets). + for (const el of this.#root.querySelectorAll(".style-editor-newButton")) { + el.addEventListener( + "click", + async () => { + const stylesheetsFront = await this.currentTarget.getFront( + "stylesheets" + ); + stylesheetsFront.addStyleSheet(null); + this.#clearFilterInput(); + }, + eventListenersConfig + ); + } + + this.#root.querySelector(".style-editor-importButton").addEventListener( + "click", + () => { + this.#importFromFile(this._mockImportFile || null, this.#window); + this.#clearFilterInput(); + }, + eventListenersConfig + ); + + this.#root + .querySelector("#style-editor-options") + .addEventListener( + "click", + this.#onOptionsButtonClick, + eventListenersConfig + ); + + this.#filterInput.addEventListener( + "input", + this.#onFilterInputChange, + eventListenersConfig + ); + + this.#filterInputClearButton.addEventListener( + "click", + () => this.#clearFilterInput(), + eventListenersConfig + ); + + this.#panelDoc.addEventListener( + "contextmenu", + () => { + this.#contextMenuStyleSheet = null; + }, + { ...eventListenersConfig, capture: true } + ); + + this.#optionsButton = this.#panelDoc.getElementById("style-editor-options"); + + this.#contextMenu = this.#panelDoc.getElementById("sidebar-context"); + this.#contextMenu.addEventListener( + "popupshowing", + this.#updateContextMenuItems, + eventListenersConfig + ); + + this.#openLinkNewTabItem = this.#panelDoc.getElementById( + "context-openlinknewtab" + ); + this.#openLinkNewTabItem.addEventListener( + "command", + this.#openLinkNewTab, + eventListenersConfig + ); + + this.#copyUrlItem = this.#panelDoc.getElementById("context-copyurl"); + this.#copyUrlItem.addEventListener( + "command", + this.#copyUrl, + eventListenersConfig + ); + + // items list focus and search-on-type handling + this.#nav.addEventListener( + "keydown", + this.#onNavKeyDown, + eventListenersConfig + ); + + this.#shortcuts = new KeyShortcuts({ + window: this.#window, + }); + this.#shortcuts.on( + `CmdOrCtrl+${getString("focusFilterInput.commandkey")}`, + this.#onFocusFilterInputKeyboardShortcut + ); + + const nav = this.#panelDoc.querySelector(".splitview-controller"); + nav.style.width = Services.prefs.getIntPref(PREF_NAV_WIDTH) + "px"; + } + + #clearFilterInput() { + this.#filterInput.value = ""; + this.#onFilterInputChange(); + } + + #onFilterInputChange = () => { + this.#filter = this.#filterInput.value; + this.#filterInputClearButton.toggleAttribute("hidden", !this.#filter); + + for (const summary of this.#nav.childNodes) { + // Don't update nav class for every element, we do it after the loop. + this.handleSummaryVisibility(summary, { + triggerOnFilterStateChange: false, + }); + } + + this.#onFilterStateChange(); + + if (this.#activeSummary == null) { + const firstVisibleSummary = Array.from(this.#nav.childNodes).find( + node => !node.classList.contains(FILTERED_CLASSNAME) + ); + + if (firstVisibleSummary) { + this.setActiveSummary(firstVisibleSummary, { reason: "filter-auto" }); + } + } + }; + + #onFilterStateChange() { + const summaries = Array.from(this.#nav.childNodes); + const hasVisibleSummary = summaries.some( + node => !node.classList.contains(FILTERED_CLASSNAME) + ); + const allFiltered = !!summaries.length && !hasVisibleSummary; + + this.#nav.classList.toggle(ALL_FILTERED_CLASSNAME, allFiltered); + + this.#filterInput + .closest(".devtools-searchbox") + .classList.toggle("devtools-searchbox-no-match", !!allFiltered); + } + + #onFocusFilterInputKeyboardShortcut = e => { + // Prevent the print modal to be displayed. + if (e) { + e.stopPropagation(); + e.preventDefault(); + } + this.#filterInput.select(); + }; + + #onNavKeyDown = event => { + function getFocusedItemWithin(nav) { + let node = nav.ownerDocument.activeElement; + while (node && node.parentNode != nav) { + node = node.parentNode; + } + return node; + } + + // do not steal focus from inside iframes or textboxes + if ( + event.target.ownerDocument != this.#nav.ownerDocument || + event.target.tagName == "input" || + event.target.tagName == "textarea" || + event.target.classList.contains("textbox") + ) { + return false; + } + + // handle keyboard navigation within the items list + const visibleElements = Array.from( + this.#nav.querySelectorAll(`li:not(.${FILTERED_CLASSNAME})`) + ); + // Elements have a different visual order (due to the use of order), so + // we need to sort them by their data-ordinal attribute + visibleElements.sort( + (a, b) => a.getAttribute("data-ordinal") - b.getAttribute("data-ordinal") + ); + + let elementToFocus; + if ( + event.keyCode == lazy.KeyCodes.DOM_VK_PAGE_UP || + event.keyCode == lazy.KeyCodes.DOM_VK_HOME + ) { + elementToFocus = visibleElements[0]; + } else if ( + event.keyCode == lazy.KeyCodes.DOM_VK_PAGE_DOWN || + event.keyCode == lazy.KeyCodes.DOM_VK_END + ) { + elementToFocus = visibleElements.at(-1); + } else if (event.keyCode == lazy.KeyCodes.DOM_VK_UP) { + const focusedIndex = visibleElements.indexOf( + getFocusedItemWithin(this.#nav) + ); + elementToFocus = visibleElements[focusedIndex - 1]; + } else if (event.keyCode == lazy.KeyCodes.DOM_VK_DOWN) { + const focusedIndex = visibleElements.indexOf( + getFocusedItemWithin(this.#nav) + ); + elementToFocus = visibleElements[focusedIndex + 1]; + } + + if (elementToFocus !== undefined) { + event.stopPropagation(); + event.preventDefault(); + elementToFocus.focus(); + return false; + } + + return true; + }; + + /** + * Opens the Options Popup Menu + * + * @params {number} screenX + * @params {number} screenY + * Both obtained from the event object, used to position the popup + */ + #onOptionsButtonClick = ({ screenX, screenY }) => { + this.#optionsMenu = optionsPopupMenu( + this.#toggleOrigSources, + this.#toggleAtRulesSidebar + ); + + this.#optionsMenu.once("open", () => { + this.#optionsButton.setAttribute("open", true); + }); + this.#optionsMenu.once("close", () => { + this.#optionsButton.removeAttribute("open"); + }); + + this.#optionsMenu.popup(screenX, screenY, this.#toolbox.doc); + }; + + /** + * Be called when changing the original sources pref. + */ + #onOrigSourcesPrefChanged = async () => { + this.#clear(); + // When we toggle the source-map preference, we clear the panel and re-fetch the exact + // same stylesheet resources from ResourceCommand, but `_addStyleSheet` will trigger + // or ignore the additional source-map mapping. + this.#root.classList.add("loading"); + for (const resource of this.#toolbox.resourceCommand.getAllResources( + this.#toolbox.resourceCommand.TYPES.STYLESHEET + )) { + await this.#handleStyleSheetResource(resource); + } + + this.#root.classList.remove("loading"); + + this.emit("stylesheets-refreshed"); + }; + + /** + * Remove all editors and add loading indicator. + */ + #clear = () => { + // remember selected sheet and line number for next load + if (this.selectedEditor && this.selectedEditor.sourceEditor) { + const href = this.selectedEditor.styleSheet.href; + const { line, ch } = this.selectedEditor.sourceEditor.getCursor(); + + this.#styleSheetToSelect = { + stylesheet: href, + line, + col: ch, + }; + } + + // remember saved file locations + for (const editor of this.editors) { + if (editor.savedFile) { + const identifier = this.getStyleSheetIdentifier(editor.styleSheet); + this.savedLocations[identifier] = editor.savedFile; + } + } + + this.#clearStyleSheetEditors(); + // Clear the left sidebar items and their associated elements. + while (this.#nav.hasChildNodes()) { + this.removeSplitViewItem(this.#nav.firstChild); + } + + this.selectedEditor = null; + // Here the keys are style sheet actors, and the values are + // promises that resolve to the sheet's editor. See |_addStyleSheet|. + this.#seenSheets = new Map(); + + this.emit("stylesheets-clear"); + }; + + /** + * Add an editor for this stylesheet. Add editors for its original sources + * instead (e.g. Sass sources), if applicable. + * + * @param {Resource} resource + * The STYLESHEET resource which is received from resource command. + * @return {Promise} + * A promise that resolves to the style sheet's editor when the style sheet has + * been fully loaded. If the style sheet has a source map, and source mapping + * is enabled, then the promise resolves to null. + */ + #addStyleSheet(resource) { + if (!this.#seenSheets.has(resource)) { + const promise = (async () => { + let editor = await this.#addStyleSheetEditor(resource); + + const sourceMapLoader = this.#toolbox.sourceMapLoader; + + if ( + !sourceMapLoader || + !Services.prefs.getBoolPref(PREF_ORIG_SOURCES) + ) { + return editor; + } + + const { + href, + nodeHref, + resourceId: id, + sourceMapURL, + sourceMapBaseURL, + } = resource; + const sources = await sourceMapLoader.getOriginalURLs({ + id, + url: href || nodeHref, + sourceMapBaseURL, + sourceMapURL, + }); + // A single generated sheet might map to multiple original + // sheets, so make editors for each of them. + if (sources && sources.length) { + const parentEditorName = editor.friendlyName; + this.#removeStyleSheetEditor(editor); + editor = null; + + for (const { id: originalId, url: originalURL } of sources) { + const original = new lazy.OriginalSource( + originalURL, + originalId, + sourceMapLoader + ); + + // set so the first sheet will be selected, even if it's a source + original.styleSheetIndex = resource.styleSheetIndex; + original.relatedStyleSheet = resource; + original.relatedEditorName = parentEditorName; + original.resourceId = resource.resourceId; + original.targetFront = resource.targetFront; + original.atRules = resource.atRules; + await this.#addStyleSheetEditor(original); + } + } + + return editor; + })(); + this.#seenSheets.set(resource, promise); + } + return this.#seenSheets.get(resource); + } + + #removeStyleSheet(resource, editor) { + this.#seenSheets.delete(resource); + this.#removeStyleSheetEditor(editor); + } + + #getInlineStyleSheetsCount() { + return this.editors.filter(editor => !editor.styleSheet.href).length; + } + + #getNewStyleSheetsCount() { + return this.editors.filter(editor => editor.isNew).length; + } + + /** + * Finds the index to be shown in the Style Editor for inline or + * user-created style sheets, returns undefined if not of either type. + * + * @param {StyleSheet} styleSheet + * Object representing stylesheet + * @return {(Number|undefined)} + * Optional Integer representing the index of the current stylesheet + * among all stylesheets of its type (inline or user-created) + */ + #getNextFriendlyIndex(styleSheet) { + if (styleSheet.href) { + return undefined; + } + + return styleSheet.isNew + ? this.#getNewStyleSheetsCount() + : this.#getInlineStyleSheetsCount(); + } + + /** + * Add a new editor to the UI for a source. + * + * @param {Resource} resource + * The resource which is received from resource command. + * @return {Promise} that is resolved with the created StyleSheetEditor when + * the editor is fully initialized or rejected on error. + */ + async #addStyleSheetEditor(resource) { + const editor = new StyleSheetEditor( + resource, + this.#window, + this.#getNextFriendlyIndex(resource) + ); + + editor.on("property-change", this.#summaryChange.bind(this, editor)); + editor.on("at-rules-changed", this.#updateAtRulesList.bind(this, editor)); + editor.on("linked-css-file", this.#summaryChange.bind(this, editor)); + editor.on("linked-css-file-error", this.#summaryChange.bind(this, editor)); + editor.on("error", this.#onError); + editor.on( + "filter-input-keyboard-shortcut", + this.#onFocusFilterInputKeyboardShortcut + ); + + // onAtRulesChanged fires at-rules-changed, so call the function after + // registering the listener in order to ensure to get at-rules-changed event. + editor.onAtRulesChanged(resource.atRules); + + this.editors.push(editor); + + try { + await editor.fetchSource(); + } catch (e) { + // if the editor was destroyed while fetching dependencies, we don't want to go further. + if (!this.editors.includes(editor)) { + return null; + } + throw e; + } + + this.#sourceLoaded(editor); + + if (resource.fileName) { + this.emit("test:editor-updated", editor); + } + + return editor; + } + + /** + * Import a style sheet from file and asynchronously create a + * new stylesheet on the debuggee for it. + * + * @param {mixed} file + * Optional nsIFile or filename string. + * If not set a file picker will be shown. + * @param {nsIWindow} parentWindow + * Optional parent window for the file picker. + */ + #importFromFile(file, parentWindow) { + const onFileSelected = selectedFile => { + if (!selectedFile) { + // nothing selected + return; + } + lazy.NetUtil.asyncFetch( + { + uri: lazy.NetUtil.newURI(selectedFile), + loadingNode: this.#window.document, + securityFlags: + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT, + contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, + }, + async (stream, status) => { + if (!Components.isSuccessCode(status)) { + this.emit("error", { key: LOAD_ERROR, level: "warning" }); + return; + } + const source = lazy.NetUtil.readInputStreamToString( + stream, + stream.available() + ); + stream.close(); + + const stylesheetsFront = await this.currentTarget.getFront( + "stylesheets" + ); + stylesheetsFront.addStyleSheet(source, selectedFile.path); + } + ); + }; + + showFilePicker(file, false, parentWindow, onFileSelected); + } + + /** + * Forward any error from a stylesheet. + * + * @param {data} data + * The event data + */ + #onError = data => { + this.emit("error", data); + }; + + /** + * Toggle the original sources pref. + */ + #toggleOrigSources() { + const isEnabled = Services.prefs.getBoolPref(PREF_ORIG_SOURCES); + Services.prefs.setBoolPref(PREF_ORIG_SOURCES, !isEnabled); + } + + /** + * Toggle the pref for showing the at-rules sidebar (for @media, @layer, @container, …) + * in each editor. + */ + #toggleAtRulesSidebar() { + const isEnabled = Services.prefs.getBoolPref(PREF_AT_RULES_SIDEBAR); + Services.prefs.setBoolPref(PREF_AT_RULES_SIDEBAR, !isEnabled); + } + + /** + * Toggle the at-rules sidebar in each editor depending on the setting. + */ + #onAtRulesSidebarPrefChanged = () => { + this.editors.forEach(this.#updateAtRulesList); + }; + + /** + * This method handles the following cases related to the context + * menu items "_openLinkNewTabItem" and "_copyUrlItem": + * + * 1) There was a stylesheet clicked on and it is external: show and + * enable the context menu item + * 2) There was a stylesheet clicked on and it is inline: show and + * disable the context menu item + * 3) There was no stylesheet clicked on (the right click happened + * below the list): hide the context menu + */ + #updateContextMenuItems = async () => { + this.#openLinkNewTabItem.hidden = !this.#contextMenuStyleSheet; + this.#copyUrlItem.hidden = !this.#contextMenuStyleSheet; + + if (this.#contextMenuStyleSheet) { + this.#openLinkNewTabItem.setAttribute( + "disabled", + !this.#contextMenuStyleSheet.href + ); + this.#copyUrlItem.setAttribute( + "disabled", + !this.#contextMenuStyleSheet.href + ); + } + }; + + /** + * Open a particular stylesheet in a new tab. + */ + #openLinkNewTab = () => { + if (this.#contextMenuStyleSheet) { + lazy.openContentLink(this.#contextMenuStyleSheet.href); + } + }; + + /** + * Copies a stylesheet's URL. + */ + #copyUrl = () => { + if (this.#contextMenuStyleSheet) { + lazy.copyString(this.#contextMenuStyleSheet.href); + } + }; + + /** + * Remove a particular stylesheet editor from the UI + * + * @param {StyleSheetEditor} editor + * The editor to remove. + */ + #removeStyleSheetEditor(editor) { + if (editor.summary) { + this.removeSplitViewItem(editor.summary); + } else { + const self = this; + this.on("editor-added", function onAdd(added) { + if (editor == added) { + self.off("editor-added", onAdd); + self.removeSplitViewItem(editor.summary); + } + }); + } + + editor.destroy(); + this.editors.splice(this.editors.indexOf(editor), 1); + } + + /** + * Clear all the editors from the UI. + */ + #clearStyleSheetEditors() { + for (const editor of this.editors) { + editor.destroy(); + } + this.editors = []; + } + + /** + * Called when a StyleSheetEditor's source has been fetched. + * Add new sidebar item and editor to the UI + * + * @param {StyleSheetEditor} editor + * Editor to create UI for. + */ + #sourceLoaded(editor) { + // Create the detail and summary nodes from the templates node (declared in index.xhtml) + const details = this.#tplDetails.cloneNode(true); + details.id = ""; + const summary = this.#tplSummary.cloneNode(true); + summary.id = ""; + + let ordinal = editor.styleSheet.styleSheetIndex; + ordinal = ordinal == -1 ? Number.MAX_SAFE_INTEGER : ordinal; + summary.style.order = ordinal; + summary.setAttribute("data-ordinal", ordinal); + + const isSystem = !!editor.styleSheet.system; + if (isSystem) { + summary.classList.add("stylesheet-system"); + } + + this.#nav.appendChild(summary); + this.#side.appendChild(details); + + this.#summaryDataMap.set(summary, { + details, + editor, + }); + + const createdEditor = editor; + createdEditor.summary = summary; + createdEditor.details = details; + + const eventListenersConfig = { signal: this.#uiAbortController.signal }; + + summary.addEventListener( + "click", + event => { + event.stopPropagation(); + this.setActiveSummary(summary); + }, + eventListenersConfig + ); + + const stylesheetToggle = summary.querySelector(".stylesheet-toggle"); + if (isSystem) { + stylesheetToggle.disabled = true; + this.#window.document.l10n.setAttributes( + stylesheetToggle, + "styleeditor-visibility-toggle-system" + ); + } else { + stylesheetToggle.addEventListener( + "click", + event => { + event.stopPropagation(); + event.target.blur(); + + createdEditor.toggleDisabled(); + }, + eventListenersConfig + ); + } + + summary.querySelector(".stylesheet-name").addEventListener( + "keypress", + event => { + if (event.keyCode == lazy.KeyCodes.DOM_VK_RETURN) { + this.setActiveSummary(summary); + } + }, + eventListenersConfig + ); + + summary.querySelector(".stylesheet-saveButton").addEventListener( + "click", + event => { + event.stopPropagation(); + event.target.blur(); + + createdEditor.saveToFile(createdEditor.savedFile); + }, + eventListenersConfig + ); + + this.#updateSummaryForEditor(createdEditor, summary); + + summary.addEventListener( + "contextmenu", + () => { + this.#contextMenuStyleSheet = createdEditor.styleSheet; + }, + eventListenersConfig + ); + + summary.addEventListener( + "focus", + function onSummaryFocus(event) { + if (event.target == summary) { + // autofocus the stylesheet name + summary.querySelector(".stylesheet-name").focus(); + } + }, + eventListenersConfig + ); + + const sidebar = details.querySelector(".stylesheet-sidebar"); + sidebar.style.width = Services.prefs.getIntPref(PREF_SIDEBAR_WIDTH) + "px"; + + const splitter = details.querySelector(".devtools-side-splitter"); + splitter.addEventListener( + "mousemove", + () => { + const sidebarWidth = parseInt(sidebar.style.width, 10); + if (!isNaN(sidebarWidth)) { + Services.prefs.setIntPref(PREF_SIDEBAR_WIDTH, sidebarWidth); + + // update all at-rules sidebars for consistency + const sidebars = [ + ...this.#panelDoc.querySelectorAll(".stylesheet-sidebar"), + ]; + for (const atRuleSidebar of sidebars) { + atRuleSidebar.style.width = sidebarWidth + "px"; + } + } + }, + eventListenersConfig + ); + + // autofocus if it's a new user-created stylesheet + if (createdEditor.isNew) { + this.#selectEditor(createdEditor); + } + + if (this.#isEditorToSelect(createdEditor)) { + this.switchToSelectedSheet(); + } + + // If this is the first stylesheet and there is no pending request to + // select a particular style sheet, select this sheet. + if ( + !this.selectedEditor && + !this.#styleSheetBoundToSelect && + createdEditor.styleSheet.styleSheetIndex == 0 && + !summary.classList.contains(FILTERED_CLASSNAME) + ) { + this.#selectEditor(createdEditor); + } + this.emit("editor-added", createdEditor); + } + + /** + * Switch to the editor that has been marked to be selected. + * + * @return {Promise} + * Promise that will resolve when the editor is selected. + */ + switchToSelectedSheet() { + const toSelect = this.#styleSheetToSelect; + + for (const editor of this.editors) { + if (this.#isEditorToSelect(editor)) { + // The _styleSheetBoundToSelect will always hold the latest pending + // requested style sheet (with line and column) which is not yet + // selected by the source editor. Only after we select that particular + // editor and go the required line and column, it will become null. + this.#styleSheetBoundToSelect = this.#styleSheetToSelect; + this.#styleSheetToSelect = null; + return this.#selectEditor(editor, toSelect.line, toSelect.col); + } + } + + return Promise.resolve(); + } + + /** + * Returns whether a given editor is the current editor to be selected. Tests + * based on href or underlying stylesheet. + * + * @param {StyleSheetEditor} editor + * The editor to test. + */ + #isEditorToSelect(editor) { + const toSelect = this.#styleSheetToSelect; + if (!toSelect) { + return false; + } + const isHref = + toSelect.stylesheet === null || typeof toSelect.stylesheet == "string"; + + return ( + (isHref && editor.styleSheet.href == toSelect.stylesheet) || + toSelect.stylesheet == editor.styleSheet + ); + } + + /** + * Select an editor in the UI. + * + * @param {StyleSheetEditor} editor + * Editor to switch to. + * @param {number} line + * Line number to jump to + * @param {number} col + * Column number to jump to + * @return {Promise} + * Promise that will resolve when the editor is selected and ready + * to be used. + */ + #selectEditor(editor, line = null, col = null) { + // Don't go further if the editor was destroyed in the meantime + if (!this.editors.includes(editor)) { + return null; + } + + const editorPromise = editor.getSourceEditor().then(() => { + // line/col are null when the style editor is initialized and the first stylesheet + // editor is selected. Unfortunately, this function might be called also when the + // panel is opened from clicking on a CSS warning in the WebConsole panel, in which + // case we have specific line+col. + // There's no guarantee which one could be called first, and it happened that we + // were setting the cursor once for the correct line coming from the webconsole, + // and then re-setting it to the default value (which was <0,0>). + // To avoid the race, we simply don't explicitly set the cursor to any default value, + // which is not a big deal as CodeMirror does init it to <0,0> anyway. + // See Bug 1738124 for more information. + if (line !== null || col !== null) { + editor.setCursor(line, col); + } + this.#styleSheetBoundToSelect = null; + }); + + const summaryPromise = this.getEditorSummary(editor).then(summary => { + // Don't go further if the editor was destroyed in the meantime + if (!this.editors.includes(editor)) { + throw new Error("Editor was destroyed"); + } + this.setActiveSummary(summary); + }); + + return Promise.all([editorPromise, summaryPromise]); + } + + getEditorSummary(editor) { + const self = this; + + if (editor.summary) { + return Promise.resolve(editor.summary); + } + + return new Promise(resolve => { + this.on("editor-added", function onAdd(selected) { + if (selected == editor) { + self.off("editor-added", onAdd); + resolve(editor.summary); + } + }); + }); + } + + getEditorDetails(editor) { + const self = this; + + if (editor.details) { + return Promise.resolve(editor.details); + } + + return new Promise(resolve => { + this.on("editor-added", function onAdd(selected) { + if (selected == editor) { + self.off("editor-added", onAdd); + resolve(editor.details); + } + }); + }); + } + + /** + * Returns an identifier for the given style sheet. + * + * @param {StyleSheet} styleSheet + * The style sheet to be identified. + */ + getStyleSheetIdentifier(styleSheet) { + // Identify inline style sheets by their host page URI and index + // at the page. + return styleSheet.href + ? styleSheet.href + : "inline-" + styleSheet.styleSheetIndex + "-at-" + styleSheet.nodeHref; + } + + /** + * Get the OriginalSource object for a given original sourceId returned from + * the sourcemap worker service. + * + * @param {string} sourceId + * The ID to search for from the sourcemap worker. + * + * @return {OriginalSource | null} + */ + getOriginalSourceSheet(sourceId) { + for (const editor of this.editors) { + const { styleSheet } = editor; + if (styleSheet.isOriginalSource && styleSheet.sourceId === sourceId) { + return styleSheet; + } + } + return null; + } + + /** + * Given an URL, find a stylesheet resource with that URL, if one has been + * loaded into the editor.js + * + * Do not use this unless you have no other way to get a StyleSheet resource + * multiple sheets could share the same URL, so this will give you _one_ + * of possibly many sheets with that URL. + * + * @param {string} url + * An arbitrary URL to search for. + * + * @return {StyleSheetResource|null} + */ + getStylesheetResourceForGeneratedURL(url) { + for (const styleSheet of this.#seenSheets.keys()) { + const sheetURL = styleSheet.href || styleSheet.nodeHref; + if (!styleSheet.isOriginalSource && sheetURL === url) { + return styleSheet; + } + } + return null; + } + + /** + * selects a stylesheet and optionally moves the cursor to a selected line + * + * @param {StyleSheetResource} stylesheet + * Stylesheet to select or href of stylesheet to select + * @param {Number} line + * Line to which the caret should be moved (zero-indexed). + * @param {Number} col + * Column to which the caret should be moved (zero-indexed). + * @return {Promise} + * Promise that will resolve when the editor is selected and ready + * to be used. + */ + selectStyleSheet(stylesheet, line, col) { + this.#styleSheetToSelect = { + stylesheet, + line, + col, + }; + + /* Switch to the editor for this sheet, if it exists yet. + Otherwise each editor will be checked when it's created. */ + return this.switchToSelectedSheet(); + } + + /** + * Handler for an editor's 'property-changed' event. + * Update the summary in the UI. + * + * @param {StyleSheetEditor} editor + * Editor for which a property has changed + */ + #summaryChange(editor) { + this.#updateSummaryForEditor(editor); + } + + /** + * Update split view summary of given StyleEditor instance. + * + * @param {StyleSheetEditor} editor + * @param {DOMElement} summary + * Optional item's summary element to update. If none, item + * corresponding to passed editor is used. + */ + #updateSummaryForEditor(editor, summary) { + summary = summary || editor.summary; + if (!summary) { + return; + } + + let ruleCount = editor.styleSheet.ruleCount; + if (editor.styleSheet.relatedStyleSheet) { + ruleCount = editor.styleSheet.relatedStyleSheet.ruleCount; + } + if (ruleCount === undefined) { + ruleCount = "-"; + } + + summary.classList.toggle("disabled", !!editor.styleSheet.disabled); + summary.classList.toggle("unsaved", !!editor.unsaved); + summary.classList.toggle("linked-file-error", !!editor.linkedCSSFileError); + + const label = summary.querySelector(".stylesheet-name > label"); + label.setAttribute("value", editor.friendlyName); + if (editor.styleSheet.href) { + label.setAttribute("tooltiptext", editor.styleSheet.href); + } + + let linkedCSSSource = ""; + if (editor.linkedCSSFile) { + linkedCSSSource = PathUtils.filename(editor.linkedCSSFile); + } else if (editor.styleSheet.relatedEditorName) { + linkedCSSSource = editor.styleSheet.relatedEditorName; + } + text(summary, ".stylesheet-linked-file", linkedCSSSource); + text(summary, ".stylesheet-title", editor.styleSheet.title || ""); + text( + summary, + ".stylesheet-rule-count", + PluralForm.get(ruleCount, getString("ruleCount.label")).replace( + "#1", + ruleCount + ) + ); + + // We may need to change the summary visibility as a result of the changes. + this.handleSummaryVisibility(summary); + } + + /** + * Update the at-rules sidebar for an editor. Hide if there are no rules + * Display a list of the at-rules (@media, @layer, @container, …) in the editor's associated style sheet. + * Emits a 'at-rules-list-changed' event after updating the UI. + * + * @param {StyleSheetEditor} editor + * Editor to update sidebar of + */ + #updateAtRulesList = editor => { + (async function () { + const details = await this.getEditorDetails(editor); + const list = details.querySelector(".stylesheet-at-rules-list"); + + while (list.firstChild) { + list.firstChild.remove(); + } + + const rules = editor.atRules; + const showSidebar = Services.prefs.getBoolPref(PREF_AT_RULES_SIDEBAR); + const sidebar = details.querySelector(".stylesheet-sidebar"); + + let inSource = false; + + for (const rule of rules) { + const { line, column } = rule; + + let location = { + line, + column, + source: editor.styleSheet.href, + styleSheet: editor.styleSheet, + }; + if (editor.styleSheet.isOriginalSource) { + const styleSheet = editor.cssSheet; + location = await editor.styleSheet.getOriginalLocation( + styleSheet, + line, + column + ); + } + + // this at-rule is from a different original source + if (location.source != editor.styleSheet.href) { + continue; + } + inSource = true; + + const div = this.#panelDoc.createElementNS(HTML_NS, "div"); + div.classList.add("at-rule-label", rule.type); + div.addEventListener( + "click", + this.#jumpToLocation.bind(this, location) + ); + + const ruleTextContainer = this.#panelDoc.createElementNS( + HTML_NS, + "div" + ); + const type = this.#panelDoc.createElementNS(HTML_NS, "span"); + type.className = "at-rule-type"; + type.append(this.#panelDoc.createTextNode(`@${rule.type}\u00A0`)); + if (rule.type == "layer" && rule.layerName) { + type.append(this.#panelDoc.createTextNode(`${rule.layerName}\u00A0`)); + } + + const cond = this.#panelDoc.createElementNS(HTML_NS, "span"); + cond.className = "at-rule-condition"; + if (rule.type == "media" && !rule.matches) { + cond.classList.add("media-condition-unmatched"); + } + if (this.#commands.descriptorFront.isLocalTab) { + this.#setConditionContents(cond, rule.conditionText, rule.type); + } else { + cond.textContent = rule.conditionText; + } + + const link = this.#panelDoc.createElementNS(HTML_NS, "div"); + link.className = "at-rule-line theme-link"; + if (location.line != -1) { + link.textContent = ":" + location.line; + } + + ruleTextContainer.append(type, cond); + div.append(ruleTextContainer, link); + list.appendChild(div); + } + + sidebar.hidden = !showSidebar || !inSource; + + this.emit("at-rules-list-changed", editor); + }) + .bind(this)() + .catch(console.error); + }; + + /** + * Set the condition text for the at-rule element. + * For media queries, it also injects links to open RDM at a specific size. + * + * @param {HTMLElement} element + * The element corresponding to the media sidebar condition + * @param {String} ruleConditionText + * The rule conditionText + * @param {String} type + * The type of the at-rule (e.g. "media", "layer", "supports", …) + */ + #setConditionContents(element, ruleConditionText, type) { + if (!ruleConditionText) { + return; + } + + // For non-media rules, we don't do anything more than displaying the conditionText + // as there are no other condition text that would justify opening RDM at a specific + // size (e.g. `@container` condition is relative to a container size, which varies + // depending the node the rule applies to). + if (type !== "media") { + const node = this.#panelDoc.createTextNode(ruleConditionText); + element.appendChild(node); + return; + } + + const minMaxPattern = /(min\-|max\-)(width|height):\s\d+(px)/gi; + + let match = minMaxPattern.exec(ruleConditionText); + let lastParsed = 0; + while (match && match.index != minMaxPattern.lastIndex) { + const matchEnd = match.index + match[0].length; + const node = this.#panelDoc.createTextNode( + ruleConditionText.substring(lastParsed, match.index) + ); + element.appendChild(node); + + const link = this.#panelDoc.createElementNS(HTML_NS, "a"); + link.href = "#"; + link.className = "media-responsive-mode-toggle"; + link.textContent = ruleConditionText.substring(match.index, matchEnd); + link.addEventListener("click", this.#onMediaConditionClick.bind(this)); + element.appendChild(link); + + match = minMaxPattern.exec(ruleConditionText); + lastParsed = matchEnd; + } + + const node = this.#panelDoc.createTextNode( + ruleConditionText.substring(lastParsed, ruleConditionText.length) + ); + element.appendChild(node); + } + + /** + * Called when a media condition is clicked + * If a responsive mode link is clicked, it will launch it. + * + * @param {object} e + * Event object + */ + #onMediaConditionClick(e) { + const conditionText = e.target.textContent; + const isWidthCond = conditionText.toLowerCase().indexOf("width") > -1; + const mediaVal = parseInt(/\d+/.exec(conditionText), 10); + + const options = isWidthCond ? { width: mediaVal } : { height: mediaVal }; + this.#launchResponsiveMode(options); + e.preventDefault(); + e.stopPropagation(); + } + + /** + * Launches the responsive mode with a specific width or height. + * + * @param {object} options + * Object with width or/and height properties. + */ + async #launchResponsiveMode(options = {}) { + const tab = this.#commands.descriptorFront.localTab; + const win = tab.ownerDocument.defaultView; + + await lazy.ResponsiveUIManager.openIfNeeded(win, tab, { + trigger: "style_editor", + }); + this.emit("responsive-mode-opened"); + + lazy.ResponsiveUIManager.getResponsiveUIForTab(tab).setViewportSize( + options + ); + } + + /** + * Jump cursor to the editor for a stylesheet and line number for a rule. + * + * @param {object} location + * Location object with 'line', 'column', and 'source' properties. + */ + #jumpToLocation(location) { + const source = location.styleSheet || location.source; + this.selectStyleSheet(source, location.line - 1, location.column - 1); + } + + #startLoadingStyleSheets() { + this.#root.classList.add("loading"); + this.#loadingStyleSheets = []; + } + + async #waitForLoadingStyleSheets() { + while (this.#loadingStyleSheets?.length > 0) { + const pending = this.#loadingStyleSheets; + this.#loadingStyleSheets = []; + await Promise.all(pending); + } + + this.#loadingStyleSheets = null; + this.#root.classList.remove("loading"); + } + + async #handleStyleSheetResource(resource) { + try { + // The fileName is in resource means this stylesheet was imported from file by user. + const { fileName } = resource; + let file = fileName ? new lazy.FileUtils.File(fileName) : null; + + // recall location of saved file for this sheet after page reload + if (!file) { + const identifier = this.getStyleSheetIdentifier(resource); + const savedFile = this.savedLocations[identifier]; + if (savedFile) { + file = savedFile; + } + } + resource.file = file; + + await this.#addStyleSheet(resource); + } catch (e) { + console.error(e); + this.emit("error", { key: LOAD_ERROR, level: "warning" }); + } + } + + // onAvailable is a mandatory argument for watchTargets, + // but we don't do anything when a new target gets created. + #onTargetAvailable = ({ targetFront }) => {}; + + #onTargetDestroyed = ({ targetFront }) => { + // Iterate over a copy of the list in order to prevent skipping + // over some items when removing items of this list + const editorsCopy = [...this.editors]; + for (const editor of editorsCopy) { + const { styleSheet } = editor; + if (styleSheet.targetFront == targetFront) { + this.#removeStyleSheet(styleSheet, editor); + } + } + }; + + #onResourceAvailable = async resources => { + const promises = []; + for (const resource of resources) { + if ( + resource.resourceType === this.#toolbox.resourceCommand.TYPES.STYLESHEET + ) { + const onStyleSheetHandled = this.#handleStyleSheetResource(resource); + + if (this.#loadingStyleSheets) { + // In case of reloading/navigating and panel's opening + this.#loadingStyleSheets.push(onStyleSheetHandled); + } + promises.push(onStyleSheetHandled); + continue; + } + + if (!resource.targetFront.isTopLevel) { + continue; + } + + if (resource.name === "will-navigate") { + this.#startLoadingStyleSheets(); + this.#clear(); + } else if (resource.name === "dom-complete") { + promises.push(this.#waitForLoadingStyleSheets()); + } + } + await Promise.all(promises); + }; + + #onResourceUpdated = async updates => { + for (const { resource, update } of updates) { + if ( + update.resourceType === this.#toolbox.resourceCommand.TYPES.STYLESHEET + ) { + const editor = this.editors.find( + e => e.resourceId === update.resourceId + ); + + switch (update.updateType) { + case "style-applied": { + editor.onStyleApplied(update); + break; + } + case "property-change": { + for (const [property, value] of Object.entries( + update.resourceUpdates + )) { + editor.onPropertyChange(property, value); + } + break; + } + case "at-rules-changed": + case "matches-change": { + editor.onAtRulesChanged(resource.atRules); + break; + } + } + } + } + }; + + /** + * Set the active item's summary element. + * + * @param DOMElement summary + * @param {Object} options + * @param {String=} options.reason: Indicates why the summary was selected. It's set to + * "filter-auto" when the summary was automatically selected as the result + * of the previous active summary being filtered out. + */ + setActiveSummary(summary, options = {}) { + if (summary == this.#activeSummary) { + return; + } + + if (this.#activeSummary) { + const binding = this.#summaryDataMap.get(this.#activeSummary); + + this.#activeSummary.classList.remove("splitview-active"); + binding.details.classList.remove("splitview-active"); + } + + this.#activeSummary = summary; + if (!summary) { + this.selectedEditor = null; + return; + } + + const { details } = this.#summaryDataMap.get(summary); + summary.classList.add("splitview-active"); + details.classList.add("splitview-active"); + + this.showSummaryEditor(summary, options); + } + + /** + * Show summary's associated editor + * + * @param DOMElement summary + * @param {Object} options + * @param {String=} options.reason: Indicates why the summary was selected. It's set to + * "filter-auto" when the summary was automatically selected as the result + * of the previous active summary being filtered out. + */ + async showSummaryEditor(summary, options) { + const { details, editor } = this.#summaryDataMap.get(summary); + this.selectedEditor = editor; + + try { + if (!editor.sourceEditor) { + // only initialize source editor when we switch to this view + const inputElement = details.querySelector(".stylesheet-editor-input"); + await editor.load(inputElement, this.#cssProperties); + } + + editor.onShow(options); + + this.emit("editor-selected", editor); + } catch (e) { + console.error(e); + } + } + + /** + * Remove an item from the split view. + * + * @param DOMElement summary + * Summary element of the item to remove. + */ + removeSplitViewItem(summary) { + if (summary == this.#activeSummary) { + this.setActiveSummary(null); + } + + const data = this.#summaryDataMap.get(summary); + if (!data) { + return; + } + + summary.remove(); + data.details.remove(); + } + + /** + * Make the passed element visible or not, depending if it matches the current filter + * + * @param {Element} summary + * @param {Object} options + * @param {Boolean} options.triggerOnFilterStateChange: Set to false to avoid calling + * #onFilterStateChange directly here. This can be useful when this + * function is called for every item of the list, like in `setFilter`. + */ + handleSummaryVisibility(summary, { triggerOnFilterStateChange = true } = {}) { + if (!this.#filter) { + summary.classList.remove(FILTERED_CLASSNAME); + return; + } + + const label = summary.querySelector(".stylesheet-name label"); + const itemText = label.value.toLowerCase(); + const matchesSearch = itemText.includes(this.#filter.toLowerCase()); + summary.classList.toggle(FILTERED_CLASSNAME, !matchesSearch); + + if (this.#activeSummary == summary && !matchesSearch) { + this.setActiveSummary(null); + } + + if (triggerOnFilterStateChange) { + this.#onFilterStateChange(); + } + } + + destroy() { + this.#toolbox.resourceCommand.unwatchResources( + [ + this.#toolbox.resourceCommand.TYPES.DOCUMENT_EVENT, + this.#toolbox.resourceCommand.TYPES.STYLESHEET, + ], + { + onAvailable: this.#onResourceAvailable, + onUpdated: this.#onResourceUpdated, + } + ); + this.#commands.targetCommand.unwatchTargets({ + types: [this.#commands.targetCommand.TYPES.FRAME], + onAvailable: this.#onTargetAvailable, + onDestroyed: this.#onTargetDestroyed, + }); + + if (this.#uiAbortController) { + this.#uiAbortController.abort(); + this.#uiAbortController = null; + } + this.#clearStyleSheetEditors(); + + this.#seenSheets = null; + this.#filterInput = null; + this.#filterInputClearButton = null; + this.#nav = null; + this.#side = null; + this.#tplDetails = null; + this.#tplSummary = null; + + const sidebar = this.#panelDoc.querySelector(".splitview-controller"); + const sidebarWidth = parseInt(sidebar.style.width, 10); + if (!isNaN(sidebarWidth)) { + Services.prefs.setIntPref(PREF_NAV_WIDTH, sidebarWidth); + } + + if (this.#sourceMapPrefObserver) { + this.#sourceMapPrefObserver.off( + PREF_ORIG_SOURCES, + this.#onOrigSourcesPrefChanged + ); + this.#sourceMapPrefObserver.destroy(); + this.#sourceMapPrefObserver = null; + } + + if (this.#prefObserver) { + this.#prefObserver.off( + PREF_AT_RULES_SIDEBAR, + this.#onAtRulesSidebarPrefChanged + ); + this.#prefObserver.destroy(); + this.#prefObserver = null; + } + + if (this.#shortcuts) { + this.#shortcuts.destroy(); + this.#shortcuts = null; + } + } +} diff --git a/devtools/client/styleeditor/StyleEditorUtil.sys.mjs b/devtools/client/styleeditor/StyleEditorUtil.sys.mjs new file mode 100644 index 0000000000..739dc55fc5 --- /dev/null +++ b/devtools/client/styleeditor/StyleEditorUtil.sys.mjs @@ -0,0 +1,213 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* All top-level definitions here are exports. */ +/* eslint no-unused-vars: [2, {"vars": "local"}] */ + +const PROPERTIES_URL = "chrome://devtools/locale/styleeditor.properties"; + +import { loader } from "resource://devtools/shared/loader/Loader.sys.mjs"; + +const gStringBundle = Services.strings.createBundle(PROPERTIES_URL); + +const lazy = {}; + +loader.lazyRequireGetter( + lazy, + "Menu", + "resource://devtools/client/framework/menu.js" +); +loader.lazyRequireGetter( + lazy, + "MenuItem", + "resource://devtools/client/framework/menu-item.js" +); + +const PREF_AT_RULES_SIDEBAR = "devtools.styleeditor.showAtRulesSidebar"; +const PREF_ORIG_SOURCES = "devtools.source-map.client-service.enabled"; + +/** + * Returns a localized string with the given key name from the string bundle. + * + * @param name + * @param ...rest + * Optional arguments to format in the string. + * @return string + */ +export function getString(name) { + try { + if (arguments.length == 1) { + return gStringBundle.GetStringFromName(name); + } + const rest = Array.prototype.slice.call(arguments, 1); + return gStringBundle.formatStringFromName(name, rest); + } catch (ex) { + console.error(ex); + throw new Error( + "L10N error. '" + name + "' is missing from " + PROPERTIES_URL + ); + } +} + +/** + * Assert an expression is true or throw if false. + * + * @param expression + * @param message + * Optional message. + * @return expression + */ +export function assert(expression, message) { + if (!expression) { + const msg = message ? "ASSERTION FAILURE:" + message : "ASSERTION FAILURE"; + log(msg); + throw new Error(msg); + } + return expression; +} + +/** + * Retrieve or set the text content of an element. + * + * @param DOMElement root + * The element to use for querySelector. + * @param string selector + * Selector string for the element to get/set the text content. + * @param string textContent + * Optional text to set. + * @return string + * Text content of matching element or null if there were no element + * matching selector. + */ +export function text(root, selector, textContent) { + const element = root.querySelector(selector); + if (!element) { + return null; + } + + if (textContent === undefined) { + return element.textContent; + } + element.textContent = textContent; + return textContent; +} + +/** + * Log a message to the console. + * + * @param ...rest + * One or multiple arguments to log. + * If multiple arguments are given, they will be joined by " " + * in the log. + */ +export function log() { + console.logStringMessage(Array.prototype.slice.call(arguments).join(" ")); +} + +/** + * Show file picker and return the file user selected. + * + * @param mixed file + * Optional nsIFile or string representing the filename to auto-select. + * @param boolean toSave + * If true, the user is selecting a filename to save. + * @param nsIWindow parentWindow + * Optional parent window. If null the parent window of the file picker + * will be the window of the attached input element. + * @param callback + * The callback method, which will be called passing in the selected + * file or null if the user did not pick one. + * @param AString suggestedFilename + * The suggested filename when toSave is true. + */ +export function showFilePicker( + path, + toSave, + parentWindow, + callback, + suggestedFilename +) { + if (typeof path == "string") { + try { + if (Services.io.extractScheme(path) == "file") { + const uri = Services.io.newURI(path); + const file = uri.QueryInterface(Ci.nsIFileURL).file; + callback(file); + return; + } + } catch (ex) { + callback(null); + return; + } + try { + const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); + file.initWithPath(path); + callback(file); + return; + } catch (ex) { + callback(null); + return; + } + } + if (path) { + // "path" is an nsIFile + callback(path); + return; + } + + const fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); + const mode = toSave ? fp.modeSave : fp.modeOpen; + const key = toSave ? "saveStyleSheet" : "importStyleSheet"; + const fpCallback = function (result) { + if (result == Ci.nsIFilePicker.returnCancel) { + callback(null); + } else { + callback(fp.file); + } + }; + + if (toSave && suggestedFilename) { + fp.defaultString = suggestedFilename; + } + + fp.init(parentWindow, getString(key + ".title"), mode); + fp.appendFilter(getString(key + ".filter"), "*.css"); + fp.appendFilters(fp.filterAll); + fp.open(fpCallback); +} + +/** + * Returns a Popup Menu for the Options ("gear") Button + * @param {function} toggleOrigSources + * To toggle the original source pref + * @param {function} toggleAtRulesSidebar + * To toggle the pref to show at-rules side bar + * @return {object} popupMenu + * A Menu object holding the MenuItems + */ +export function optionsPopupMenu(toggleOrigSources, toggleAtRulesSidebar) { + const popupMenu = new lazy.Menu(); + popupMenu.append( + new lazy.MenuItem({ + id: "options-origsources", + label: getString("showOriginalSources.label"), + accesskey: getString("showOriginalSources.accesskey"), + type: "checkbox", + checked: Services.prefs.getBoolPref(PREF_ORIG_SOURCES), + click: () => toggleOrigSources(), + }) + ); + popupMenu.append( + new lazy.MenuItem({ + id: "options-show-at-rules", + label: getString("showAtRulesSidebar.label"), + accesskey: getString("showAtRulesSidebar.accesskey"), + type: "checkbox", + checked: Services.prefs.getBoolPref(PREF_AT_RULES_SIDEBAR), + click: () => toggleAtRulesSidebar(), + }) + ); + + return popupMenu; +} diff --git a/devtools/client/styleeditor/StyleSheetEditor.sys.mjs b/devtools/client/styleeditor/StyleSheetEditor.sys.mjs new file mode 100644 index 0000000000..c863b5b267 --- /dev/null +++ b/devtools/client/styleeditor/StyleSheetEditor.sys.mjs @@ -0,0 +1,1040 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +import { + require, + loader, +} from "resource://devtools/shared/loader/Loader.sys.mjs"; + +const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js"); +const { + shortSource, + prettifyCSS, +} = require("resource://devtools/shared/inspector/css-logic.js"); +const { throttle } = require("resource://devtools/shared/throttle.js"); +const EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +const lazy = {}; + +loader.lazyGetter(lazy, "BufferStream", () => { + return Components.Constructor( + "@mozilla.org/io/arraybuffer-input-stream;1", + "nsIArrayBufferInputStream", + "setData" + ); +}); + +ChromeUtils.defineESModuleGetters(lazy, { + FileUtils: "resource://gre/modules/FileUtils.sys.mjs", +}); +ChromeUtils.defineModuleGetter( + lazy, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); + +import { + getString, + showFilePicker, +} from "resource://devtools/client/styleeditor/StyleEditorUtil.sys.mjs"; + +const LOAD_ERROR = "error-load"; +const SAVE_ERROR = "error-save"; +const SELECTOR_HIGHLIGHTER_TYPE = "SelectorHighlighter"; + +// max update frequency in ms (avoid potential typing lag and/or flicker) +// @see StyleEditor.updateStylesheet +const UPDATE_STYLESHEET_DELAY = 500; + +// Pref which decides if CSS autocompletion is enabled in Style Editor or not. +const AUTOCOMPLETION_PREF = "devtools.styleeditor.autocompletion-enabled"; + +// Pref which decides whether updates to the stylesheet use transitions +const TRANSITION_PREF = "devtools.styleeditor.transitions"; + +// How long to wait to update linked CSS file after original source was saved +// to disk. Time in ms. +const CHECK_LINKED_SHEET_DELAY = 500; + +// How many times to check for linked file changes +const MAX_CHECK_COUNT = 10; + +// How much time should the mouse be still before the selector at that position +// gets highlighted? +const SELECTOR_HIGHLIGHT_TIMEOUT = 500; + +// Minimum delay between firing two at-rules-changed events. +const EMIT_AT_RULES_THROTTLING = 500; + +const STYLE_SHEET_UPDATE_CAUSED_BY_STYLE_EDITOR = "styleeditor"; + +/** + * StyleSheetEditor controls the editor linked to a particular StyleSheet + * object. + * + * Emits events: + * 'property-change': A property on the underlying stylesheet has changed + * 'source-editor-load': The source editor for this editor has been loaded + * 'error': An error has occured + * + * @param {Resource} resource + * The STYLESHEET resource which is received from resource command. + * @param {DOMWindow} win + * panel window for style editor + * @param {Number} styleSheetFriendlyIndex + * Optional Integer representing the index of the current stylesheet + * among all stylesheets of its type (inline or user-created) + */ +export function StyleSheetEditor(resource, win, styleSheetFriendlyIndex) { + EventEmitter.decorate(this); + + this._resource = resource; + this._inputElement = null; + this.sourceEditor = null; + this._window = win; + this._isNew = this.styleSheet.isNew; + this.styleSheetFriendlyIndex = styleSheetFriendlyIndex; + + // True when we've just set the editor text based on a style-applied + // event from the StyleSheetActor. + this._justSetText = false; + + // state to use when inputElement attaches + this._state = { + text: "", + selection: { + start: { line: 0, ch: 0 }, + end: { line: 0, ch: 0 }, + }, + }; + + this._styleSheetFilePath = null; + if ( + this.styleSheet.href && + Services.io.extractScheme(this.styleSheet.href) == "file" + ) { + this._styleSheetFilePath = this.styleSheet.href; + } + + this.onPropertyChange = this.onPropertyChange.bind(this); + this.onAtRulesChanged = this.onAtRulesChanged.bind(this); + this.checkLinkedFileForChanges = this.checkLinkedFileForChanges.bind(this); + this.markLinkedFileBroken = this.markLinkedFileBroken.bind(this); + this.saveToFile = this.saveToFile.bind(this); + this.updateStyleSheet = this.updateStyleSheet.bind(this); + this._updateStyleSheet = this._updateStyleSheet.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + this._focusOnSourceEditorReady = false; + this.savedFile = this.styleSheet.file; + this.linkCSSFile(); + + this.emitAtRulesChanged = throttle( + this.emitAtRulesChanged, + EMIT_AT_RULES_THROTTLING, + this + ); + + this.atRules = []; +} + +StyleSheetEditor.prototype = { + get resourceId() { + return this._resource.resourceId; + }, + + get styleSheet() { + return this._resource; + }, + + /** + * Whether there are unsaved changes in the editor + */ + get unsaved() { + return this.sourceEditor && !this.sourceEditor.isClean(); + }, + + /** + * Whether the editor is for a stylesheet created by the user + * through the style editor UI. + */ + get isNew() { + return this._isNew; + }, + + /** + * The style sheet or the generated style sheet for this source if it's an + * original source. + */ + get cssSheet() { + if (this.styleSheet.isOriginalSource) { + return this.styleSheet.relatedStyleSheet; + } + return this.styleSheet; + }, + + get savedFile() { + return this._savedFile; + }, + + set savedFile(name) { + this._savedFile = name; + + this.linkCSSFile(); + }, + + /** + * Get a user-friendly name for the style sheet. + * + * @return string + */ + get friendlyName() { + if (this.savedFile) { + return this.savedFile.leafName; + } + + if (this._isNew) { + const index = this.styleSheetFriendlyIndex + 1 || 0; + return getString("newStyleSheet", index); + } + + if (!this.styleSheet.href) { + // TODO(bug 1809107): Probably a different index + string for + // constructable stylesheets, they can't be meaningfully edited right now + // because we don't have their original text. + const index = this.styleSheetFriendlyIndex + 1 || 0; + return getString("inlineStyleSheet", index); + } + + if (!this._friendlyName) { + this._friendlyName = shortSource(this.styleSheet); + try { + this._friendlyName = decodeURI(this._friendlyName); + } catch (ex) { + // Ignore. + } + } + return this._friendlyName; + }, + + /** + * Check if transitions are enabled for style changes. + * + * @return Boolean + */ + get transitionsEnabled() { + return Services.prefs.getBoolPref(TRANSITION_PREF); + }, + + /** + * If this is an original source, get the path of the CSS file it generated. + */ + linkCSSFile() { + if (!this.styleSheet.isOriginalSource) { + return; + } + + const relatedSheet = this.styleSheet.relatedStyleSheet; + if (!relatedSheet || !relatedSheet.href) { + return; + } + + let path; + const href = removeQuery(relatedSheet.href); + const uri = lazy.NetUtil.newURI(href); + + if (uri.scheme == "file") { + const file = uri.QueryInterface(Ci.nsIFileURL).file; + path = file.path; + } else if (this.savedFile) { + const origHref = removeQuery(this.styleSheet.href); + const origUri = lazy.NetUtil.newURI(origHref); + path = findLinkedFilePath(uri, origUri, this.savedFile); + } else { + // we can't determine path to generated file on disk + return; + } + + if (this.linkedCSSFile == path) { + return; + } + + this.linkedCSSFile = path; + + this.linkedCSSFileError = null; + + // save last file change time so we can compare when we check for changes. + IOUtils.stat(path).then(info => { + this._fileModDate = info.lastModified; + }, this.markLinkedFileBroken); + + this.emit("linked-css-file"); + }, + + /** + * A helper function that fetches the source text from the style + * sheet. + * + * This will set |this._state.text| to the new text. + */ + async _fetchSourceText(options = {}) { + const styleSheetsFront = await this._getStyleSheetsFront(); + + let longStr = null; + if (this.styleSheet.isOriginalSource) { + // If the stylesheet is OriginalSource, we should get the texts from SourceMapLoader. + // So, for now, we use OriginalSource.getText() as it is. + longStr = await this.styleSheet.getText(); + } else { + longStr = await styleSheetsFront.getText(this.resourceId); + } + + this._state.text = await longStr.string(); + }, + + /** + * Attempt to prettify the current text if the corresponding stylesheet is not + * an original source. The text will be read from |this._state.text|. + * + * This will set |this._state.text| to the prettified text if needed. + */ + _prettifySourceTextIfNeeded() { + if (!this.styleSheet.isOriginalSource) { + const ruleCount = this.styleSheet.ruleCount; + const { result, mappings } = prettifyCSS(this._state.text, ruleCount); + // Store the list of objects with mappings between CSS token positions from the + // original source to the prettified source. These will be used when requested to + // jump to a specific position within the editor. + this._mappings = mappings; + this._state.text = result; + } + }, + + /** + * Start fetching the full text source for this editor's sheet. + */ + async fetchSource() { + try { + await this._fetchSourceText(); + this.sourceLoaded = true; + } catch (e) { + if (this._isDestroyed) { + console.warn( + `Could not fetch the source for ${this.styleSheet.href}, the editor was destroyed` + ); + console.error(e); + } else { + console.error(e); + this.emit("error", { + key: LOAD_ERROR, + append: this.styleSheet.href, + level: "warning", + }); + throw e; + } + } + }, + + /** + * Set the cursor at the given line and column location within the code editor. + * + * @param {Number} line + * @param {Number} column + */ + setCursor(line, column) { + line = line || 0; + column = column || 0; + + const position = this.translateCursorPosition(line, column); + this.sourceEditor.setCursor({ line: position.line, ch: position.column }); + }, + + /** + * If the stylesheet was automatically prettified, there should be a list of line + * and column mappings from the original to the generated source that can be used + * to translate the cursor position to the correct location in the prettified source. + * If no mappings exist, return the original cursor position unchanged. + * + * @param {Number} line + * @param {Numer} column + * + * @return {Object} + */ + translateCursorPosition(line, column) { + if (Array.isArray(this._mappings)) { + for (const mapping of this._mappings) { + if ( + mapping.original.line === line && + mapping.original.column === column + ) { + line = mapping.generated.line; + column = mapping.generated.column; + continue; + } + } + } + + return { line, column }; + }, + + /** + * Forward property-change event from stylesheet. + * + * @param {string} event + * Event type + * @param {string} property + * Property that has changed on sheet + */ + onPropertyChange(property, value) { + this.emit("property-change", property, value); + }, + + /** + * Called when the stylesheet text changes. + * @param {Object} update: The stylesheet resource update packet. + */ + async onStyleApplied(update) { + const updateIsFromSyleSheetEditor = + update?.event?.cause === STYLE_SHEET_UPDATE_CAUSED_BY_STYLE_EDITOR; + + if (updateIsFromSyleSheetEditor) { + // We just applied an edit in the editor, so we can drop this notification. + this.emit("style-applied"); + return; + } + + if (this.sourceEditor) { + await this._fetchSourceText(); + + // sourceEditor is already loaded, so we can prettify immediately. + this._prettifySourceTextIfNeeded(); + + // The updated stylesheet text should have been set in this._state.text + // by _fetchSourceText and _prettifySourceTextIfNeeded. + const sourceText = this._state.text; + + this._justSetText = true; + const firstLine = this.sourceEditor.getFirstVisibleLine(); + const pos = this.sourceEditor.getCursor(); + this.sourceEditor.setText(sourceText); + this.sourceEditor.setFirstVisibleLine(firstLine); + this.sourceEditor.setCursor(pos); + this.emit("style-applied"); + } + }, + + /** + * Handles changes to the list of at-rules (@media, @layer, @container, …) in the stylesheet. + * Emits 'at-rules-changed' if the list has changed. + * + * @param {array} rules + * Array of MediaRuleFronts for new media rules of sheet. + */ + onAtRulesChanged(rules) { + if (!rules.length && !this.atRules.length) { + return; + } + + this.atRules = rules; + this.emitAtRulesChanged(); + }, + + /** + * Forward at-rules-changed event from stylesheet. + */ + emitAtRulesChanged() { + this.emit("at-rules-changed", this.atRules); + }, + + /** + * Create source editor and load state into it. + * @param {DOMElement} inputElement + * Element to load source editor in + * @param {CssProperties} cssProperties + * A css properties database. + * + * @return {Promise} + * Promise that will resolve when the style editor is loaded. + */ + async load(inputElement, cssProperties) { + if (this._isDestroyed) { + throw new Error( + "Won't load source editor as the style sheet has " + + "already been removed from Style Editor." + ); + } + + this._inputElement = inputElement; + + // Attempt to prettify the source before loading the source editor. + this._prettifySourceTextIfNeeded(); + + const walker = await this.getWalker(); + const config = { + value: this._state.text, + lineNumbers: true, + mode: Editor.modes.css, + readOnly: false, + autoCloseBrackets: "{}()", + extraKeys: this._getKeyBindings(), + contextMenu: "sourceEditorContextMenu", + autocomplete: Services.prefs.getBoolPref(AUTOCOMPLETION_PREF), + autocompleteOpts: { walker, cssProperties }, + cssProperties, + }; + const sourceEditor = (this._sourceEditor = new Editor(config)); + + sourceEditor.on("dirty-change", this.onPropertyChange); + + await sourceEditor.appendTo(inputElement); + + sourceEditor.on("saveRequested", this.saveToFile); + + if (!this.styleSheet.isOriginalSource) { + sourceEditor.on("change", this.updateStyleSheet); + } + + this.sourceEditor = sourceEditor; + + if (this._focusOnSourceEditorReady) { + this._focusOnSourceEditorReady = false; + sourceEditor.focus(); + } + + sourceEditor.setSelection( + this._state.selection.start, + this._state.selection.end + ); + + const highlighter = await this.getHighlighter(); + if (highlighter && walker && sourceEditor.container?.contentWindow) { + sourceEditor.container.contentWindow.addEventListener( + "mousemove", + this._onMouseMove + ); + } + + // Add the commands controller for the source-editor. + sourceEditor.insertCommandsController(); + + this.emit("source-editor-load"); + }, + + /** + * Get the source editor for this editor. + * + * @return {Promise} + * Promise that will resolve with the editor. + */ + getSourceEditor() { + const self = this; + + if (this.sourceEditor) { + return Promise.resolve(this); + } + + return new Promise(resolve => { + this.on("source-editor-load", () => { + resolve(self); + }); + }); + }, + + /** + * Focus the Style Editor input. + */ + focus() { + if (this.sourceEditor) { + this.sourceEditor.focus(); + } else { + this._focusOnSourceEditorReady = true; + } + }, + + /** + * Event handler for when the editor is shown. + * + * @param {Object} options + * @param {String} options.reason: Indicates why the editor is shown + */ + onShow(options = {}) { + if (this.sourceEditor) { + // CodeMirror needs refresh to restore scroll position after hiding and + // showing the editor. + this.sourceEditor.refresh(); + } + + // We don't want to focus the editor if it was shown because of the list being filtered, + // as the user might still be typing in the filter input. + if (options.reason !== "filter-auto") { + this.focus(); + } + }, + + /** + * Toggled the disabled state of the underlying stylesheet. + */ + async toggleDisabled() { + const styleSheetsFront = await this._getStyleSheetsFront(); + styleSheetsFront.toggleDisabled(this.resourceId).catch(console.error); + }, + + /** + * Queue a throttled task to update the live style sheet. + */ + updateStyleSheet() { + if (this._updateTask) { + // cancel previous queued task not executed within throttle delay + this._window.clearTimeout(this._updateTask); + } + + this._updateTask = this._window.setTimeout( + this._updateStyleSheet, + UPDATE_STYLESHEET_DELAY + ); + }, + + /** + * Update live style sheet according to modifications. + */ + async _updateStyleSheet() { + if (this.styleSheet.disabled) { + // TODO: do we want to do this? + return; + } + + if (this._justSetText) { + this._justSetText = false; + return; + } + + // reset only if we actually perform an update + // (stylesheet is enabled) so that 'missed' updates + // while the stylesheet is disabled can be performed + // when it is enabled back. @see enableStylesheet + this._updateTask = null; + + if (this.sourceEditor) { + this._state.text = this.sourceEditor.getText(); + } + + try { + const styleSheetsFront = await this._getStyleSheetsFront(); + await styleSheetsFront.update( + this.resourceId, + this._state.text, + this.transitionsEnabled, + STYLE_SHEET_UPDATE_CAUSED_BY_STYLE_EDITOR + ); + + // Clear any existing mappings from automatic CSS prettification + // because they were likely invalided by manually editing the stylesheet. + this._mappings = null; + } catch (e) { + console.error(e); + } + }, + + /** + * Handle mousemove events, calling _highlightSelectorAt after a delay only + * and reseting the delay everytime. + */ + _onMouseMove(e) { + // As we only want to hide an existing highlighter, we can use this.highlighter directly + // (and not this.getHighlighter). + if (this.highlighter) { + this.highlighter.hide(); + } + + if (this.mouseMoveTimeout) { + this._window.clearTimeout(this.mouseMoveTimeout); + this.mouseMoveTimeout = null; + } + + this.mouseMoveTimeout = this._window.setTimeout(() => { + this._highlightSelectorAt(e.clientX, e.clientY); + }, SELECTOR_HIGHLIGHT_TIMEOUT); + }, + + /** + * Highlight nodes matching the selector found at coordinates x,y in the + * editor, if any. + * + * @param {Number} x + * @param {Number} y + */ + async _highlightSelectorAt(x, y) { + const pos = this.sourceEditor.getPositionFromCoords({ left: x, top: y }); + const info = this.sourceEditor.getInfoAt(pos); + if (!info || info.state !== "selector") { + return; + } + + const onGetHighlighter = this.getHighlighter(); + const walker = await this.getWalker(); + const node = await walker.getStyleSheetOwnerNode(this.resourceId); + + const highlighter = await onGetHighlighter; + await highlighter.show(node, { + selector: info.selector, + hideInfoBar: true, + showOnly: "border", + region: "border", + }); + + this.emit("node-highlighted"); + }, + + /** + * Returns the walker front associated with this._resource target. + * + * @returns {Promise} + */ + async getWalker() { + if (this.walker) { + return this.walker; + } + + const { targetFront } = this._resource; + const inspectorFront = await targetFront.getFront("inspector"); + this.walker = inspectorFront.walker; + return this.walker; + }, + + /** + * Returns or creates the selector highlighter associated with this._resource target. + * + * @returns {CustomHighlighterFront|null} + */ + async getHighlighter() { + if (this.highlighter) { + return this.highlighter; + } + + const walker = await this.getWalker(); + try { + this.highlighter = await walker.parentFront.getHighlighterByType( + SELECTOR_HIGHLIGHTER_TYPE + ); + return this.highlighter; + } catch (e) { + // The selectorHighlighter can't always be instantiated, for example + // it doesn't work with XUL windows (until bug 1094959 gets fixed); + // or the selectorHighlighter doesn't exist on the backend. + console.warn( + "The selectorHighlighter couldn't be instantiated, " + + "elements matching hovered selectors will not be highlighted" + ); + } + return null; + }, + + /** + * Save the editor contents into a file and set savedFile property. + * A file picker UI will open if file is not set and editor is not headless. + * + * @param mixed file + * Optional nsIFile or string representing the filename to save in the + * background, no UI will be displayed. + * If not specified, the original style sheet URI is used. + * To implement 'Save' instead of 'Save as', you can pass + * savedFile here. + * @param function(nsIFile aFile) callback + * Optional callback called when the operation has finished. + * aFile has the nsIFile object for saved file or null if the operation + * has failed or has been canceled by the user. + * @see savedFile + */ + saveToFile(file, callback) { + const onFile = returnFile => { + if (!returnFile) { + if (callback) { + callback(null); + } + return; + } + + if (this.sourceEditor) { + this._state.text = this.sourceEditor.getText(); + } + + const ostream = lazy.FileUtils.openSafeFileOutputStream(returnFile); + const buffer = new TextEncoder().encode(this._state.text).buffer; + const istream = new lazy.BufferStream(buffer, 0, buffer.byteLength); + + lazy.NetUtil.asyncCopy(istream, ostream, status => { + if (!Components.isSuccessCode(status)) { + if (callback) { + callback(null); + } + this.emit("error", { key: SAVE_ERROR }); + return; + } + lazy.FileUtils.closeSafeFileOutputStream(ostream); + + this.onFileSaved(returnFile); + + if (callback) { + callback(returnFile); + } + }); + }; + + let defaultName; + if (this._friendlyName) { + defaultName = PathUtils.isAbsolute(this._friendlyName) + ? PathUtils.filename(this._friendlyName) + : this._friendlyName; + } + showFilePicker( + file || this._styleSheetFilePath, + true, + this._window, + onFile, + defaultName + ); + }, + + /** + * Called when this source has been successfully saved to disk. + */ + onFileSaved(returnFile) { + this._friendlyName = null; + this.savedFile = returnFile; + + if (this.sourceEditor) { + this.sourceEditor.setClean(); + } + + this.emit("property-change"); + + // TODO: replace with file watching + this._modCheckCount = 0; + this._window.clearTimeout(this._timeout); + + if (this.linkedCSSFile && !this.linkedCSSFileError) { + this._timeout = this._window.setTimeout( + this.checkLinkedFileForChanges, + CHECK_LINKED_SHEET_DELAY + ); + } + }, + + /** + * Check to see if our linked CSS file has changed on disk, and + * if so, update the live style sheet. + */ + checkLinkedFileForChanges() { + IOUtils.stat(this.linkedCSSFile).then(info => { + const lastChange = info.lastModified; + + if (this._fileModDate && lastChange != this._fileModDate) { + this._fileModDate = lastChange; + this._modCheckCount = 0; + + this.updateLinkedStyleSheet(); + return; + } + + if (++this._modCheckCount > MAX_CHECK_COUNT) { + this.updateLinkedStyleSheet(); + return; + } + + // try again in a bit + this._timeout = this._window.setTimeout( + this.checkLinkedFileForChanges, + CHECK_LINKED_SHEET_DELAY + ); + }, this.markLinkedFileBroken); + }, + + /** + * Notify that the linked CSS file (if this is an original source) + * doesn't exist on disk in the place we think it does. + * + * @param string error + * The error we got when trying to access the file. + */ + markLinkedFileBroken(error) { + this.linkedCSSFileError = error || true; + this.emit("linked-css-file-error"); + + error += + " querying " + + this.linkedCSSFile + + " original source location: " + + this.savedFile.path; + console.error(error); + }, + + /** + * For original sources (e.g. Sass files). Fetch contents of linked CSS + * file from disk and live update the stylesheet object with the contents. + */ + updateLinkedStyleSheet() { + IOUtils.read(this.linkedCSSFile).then(async array => { + const decoder = new TextDecoder(); + const text = decoder.decode(array); + + // Ensure we don't re-fetch the text from the original source + // actor when we're notified that the style sheet changed. + const styleSheetsFront = await this._getStyleSheetsFront(); + + await styleSheetsFront.update( + this.resourceId, + text, + this.transitionsEnabled, + STYLE_SHEET_UPDATE_CAUSED_BY_STYLE_EDITOR + ); + }, this.markLinkedFileBroken); + }, + + /** + * Retrieve custom key bindings objects as expected by Editor. + * Editor action names are not displayed to the user. + * + * @return {array} key binding objects for the source editor + */ + _getKeyBindings() { + const saveStyleSheetKeybind = Editor.accel( + getString("saveStyleSheet.commandkey") + ); + const focusFilterInputKeybind = Editor.accel( + getString("focusFilterInput.commandkey") + ); + + return { + Esc: false, + [saveStyleSheetKeybind]: () => { + this.saveToFile(this.savedFile); + }, + ["Shift-" + saveStyleSheetKeybind]: () => { + this.saveToFile(); + }, + // We can't simply ignore this (with `false`, or returning `CodeMirror.Pass`), as the + // event isn't received by the event listener in StyleSheetUI. + [focusFilterInputKeybind]: () => { + this.emit("filter-input-keyboard-shortcut"); + }, + }; + }, + + _getStyleSheetsFront() { + return this._resource.targetFront.getFront("stylesheets"); + }, + + /** + * Clean up for this editor. + */ + destroy() { + if (this._sourceEditor) { + this._sourceEditor.off("dirty-change", this.onPropertyChange); + this._sourceEditor.off("saveRequested", this.saveToFile); + this._sourceEditor.off("change", this.updateStyleSheet); + if (this._sourceEditor.container?.contentWindow) { + this._sourceEditor.container.contentWindow.removeEventListener( + "mousemove", + this._onMouseMove + ); + } + this._sourceEditor.destroy(); + } + this._isDestroyed = true; + }, +}; + +/** + * Find a path on disk for a file given it's hosted uri, the uri of the + * original resource that generated it (e.g. Sass file), and the location of the + * local file for that source. + * + * @param {nsIURI} uri + * The uri of the resource + * @param {nsIURI} origUri + * The uri of the original source for the resource + * @param {nsIFile} file + * The local file for the resource on disk + * + * @return {string} + * The path of original file on disk + */ +function findLinkedFilePath(uri, origUri, file) { + const { origBranch, branch } = findUnsharedBranches(origUri, uri); + const project = findProjectPath(file, origBranch); + + const parts = project.concat(branch); + const path = PathUtils.join.apply(this, parts); + + return path; +} + +/** + * Find the path of a project given a file in the project and its branch + * off the root. e.g.: + * /Users/moz/proj/src/a.css" and "src/a.css" + * would yield ["Users", "moz", "proj"] + * + * @param {nsIFile} file + * file for that resource on disk + * @param {array} branch + * path parts for branch to chop off file path. + * @return {array} + * array of path parts + */ +function findProjectPath(file, branch) { + const path = PathUtils.split(file.path); + + for (let i = 2; i <= branch.length; i++) { + // work backwards until we find a differing directory name + if (path[path.length - i] != branch[branch.length - i]) { + return path.slice(0, path.length - i + 1); + } + } + + // if we don't find a differing directory, just chop off the branch + return path.slice(0, path.length - branch.length); +} + +/** + * Find the parts of a uri past the root it shares with another uri. e.g: + * "http://localhost/built/a.scss" and "http://localhost/src/a.css" + * would yield ["built", "a.scss"] and ["src", "a.css"] + * + * @param {nsIURI} origUri + * uri to find unshared branch of. Usually is uri for original source. + * @param {nsIURI} uri + * uri to compare against to get a shared root + * @return {object} + * object with 'branch' and 'origBranch' array of path parts for branch + */ +function findUnsharedBranches(origUri, uri) { + origUri = PathUtils.split(origUri.pathQueryRef); + uri = PathUtils.split(uri.pathQueryRef); + + for (let i = 0; i < uri.length - 1; i++) { + if (uri[i] != origUri[i]) { + return { + branch: uri.slice(i), + origBranch: origUri.slice(i), + }; + } + } + return { + branch: uri, + origBranch: origUri, + }; +} + +/** + * Remove the query string from a url. + * + * @param {string} href + * Url to remove query string from + * @return {string} + * Url without query string + */ +function removeQuery(href) { + return href.replace(/\?.*/, ""); +} diff --git a/devtools/client/styleeditor/index.xhtml b/devtools/client/styleeditor/index.xhtml new file mode 100644 index 0000000000..9178f7c2f5 --- /dev/null +++ b/devtools/client/styleeditor/index.xhtml @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/devtools/client/styleeditor/moz.build b/devtools/client/styleeditor/moz.build new file mode 100644 index 0000000000..4c5e58e0c1 --- /dev/null +++ b/devtools/client/styleeditor/moz.build @@ -0,0 +1,18 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +BROWSER_CHROME_MANIFESTS += ["test/browser.ini"] + +DevToolsModules( + "original-source.js", + "panel.js", + "StyleEditorUI.sys.mjs", + "StyleEditorUtil.sys.mjs", + "StyleSheetEditor.sys.mjs", +) + +with Files("**"): + BUG_COMPONENT = ("DevTools", "Style Editor") diff --git a/devtools/client/styleeditor/original-source.js b/devtools/client/styleeditor/original-source.js new file mode 100644 index 0000000000..1c01ae0355 --- /dev/null +++ b/devtools/client/styleeditor/original-source.js @@ -0,0 +1,103 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/** + * An object of this type represents an original source for the style + * editor. An "original" source is one that is mentioned in a source + * map. + * + * @param {String} url + * The URL of the original source. + * @param {String} sourceID + * The source ID of the original source, as used by the source + * map service. + * @param {SourceMapLoader} sourceMapLoader + * The source map loader; @see Toolbox.sourceMapLoader + */ +function OriginalSource(url, sourceId, sourceMapLoader) { + this.isOriginalSource = true; + + this._url = url; + this._sourceId = sourceId; + this._sourceMapLoader = sourceMapLoader; +} + +OriginalSource.prototype = { + get sourceId() { + return this._sourceId; + }, + + /** Get the original source's URL. */ + get url() { + return this._url; + }, + + /** Get the original source's URL. */ + get href() { + return this._url; + }, + + /** + * Return a promise that will resolve to the original source's full + * text. The return result is actually an object with a single + * `string` method; this method will return the source text as a + * string. This is done because the style editor elsewhere expects + * a long string actor. + */ + getText() { + if (!this._sourcePromise) { + this._sourcePromise = this._sourceMapLoader + .getOriginalSourceText(this._sourceId) + .then(contents => { + // Make it look like a long string actor. + return { + string: () => contents.text, + }; + }); + } + return this._sourcePromise; + }, + + /** + * Given a source-mapped, generated style sheet, a line, and a + * column, return the corresponding original location in this style + * sheet. + * + * @param {StyleSheetResource} relatedSheet + * The generated style sheet's resource + * @param {Number} line + * Line number. + * @param {Number} column + * Column number. + * @return {Location} + * The original location, an object with at least + * `sourceUrl`, `source`, `styleSheet`, `line`, and `column` + * properties. + */ + getOriginalLocation(relatedSheet, line, column) { + const { href, nodeHref, resourceId: sourceId } = relatedSheet; + const sourceUrl = href || nodeHref; + return this._sourceMapLoader + .getOriginalLocation({ + sourceId, + line, + column, + sourceUrl, + }) + .then(location => { + // Add some properties for the style editor. + location.source = location.sourceUrl; + location.styleSheet = relatedSheet; + return location; + }); + }, + + // Dummy implementations, as we never emit an event. + on() {}, + off() {}, +}; + +exports.OriginalSource = OriginalSource; diff --git a/devtools/client/styleeditor/panel.js b/devtools/client/styleeditor/panel.js new file mode 100644 index 0000000000..46ea6c28c0 --- /dev/null +++ b/devtools/client/styleeditor/panel.js @@ -0,0 +1,171 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +var { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); +var EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +var { StyleEditorUI } = ChromeUtils.importESModule( + "resource://devtools/client/styleeditor/StyleEditorUI.sys.mjs" +); +var { getString } = ChromeUtils.importESModule( + "resource://devtools/client/styleeditor/StyleEditorUtil.sys.mjs" +); + +var StyleEditorPanel = function StyleEditorPanel(panelWin, toolbox, commands) { + EventEmitter.decorate(this); + + this._toolbox = toolbox; + this._commands = commands; + this._panelWin = panelWin; + this._panelDoc = panelWin.document; + + this._showError = this._showError.bind(this); +}; + +exports.StyleEditorPanel = StyleEditorPanel; + +StyleEditorPanel.prototype = { + get panelWindow() { + return this._panelWin; + }, + + /** + * open is effectively an asynchronous constructor + */ + async open(options) { + // Initialize the CSS properties database. + const { cssProperties } = await this._toolbox.target.getFront( + "cssProperties" + ); + + // Initialize the UI + this.UI = new StyleEditorUI( + this._toolbox, + this._commands, + this._panelDoc, + cssProperties + ); + this.UI.on("error", this._showError); + await this.UI.initialize(options); + + return this; + }, + + /** + * Show an error message from the style editor in the toolbox + * notification box. + * + * @param {string} data + * The parameters to customize the error message + */ + _showError(data) { + if (!this._toolbox) { + // could get an async error after we've been destroyed + return; + } + + let errorMessage = getString(data.key); + if (data.append) { + errorMessage += " " + data.append; + } + + const notificationBox = this._toolbox.getNotificationBox(); + const notification = + notificationBox.getNotificationWithValue("styleeditor-error"); + + let level = notificationBox.PRIORITY_CRITICAL_LOW; + if (data.level === "info") { + level = notificationBox.PRIORITY_INFO_LOW; + } else if (data.level === "warning") { + level = notificationBox.PRIORITY_WARNING_LOW; + } + + if (!notification) { + notificationBox.appendNotification( + errorMessage, + "styleeditor-error", + "", + level + ); + } + }, + + /** + * Select a stylesheet. + * + * @param {StyleSheetResource} stylesheet + * The resource for the stylesheet to find and select in editor. + * @param {number} line + * Line number to jump to after selecting. One-indexed + * @param {number} col + * Column number to jump to after selecting. One-indexed + * @return {Promise} + * Promise that will resolve when the editor is selected and ready + * to be used. + */ + selectStyleSheet(stylesheet, line, col) { + if (!this.UI) { + return null; + } + + return this.UI.selectStyleSheet(stylesheet, line - 1, col ? col - 1 : 0); + }, + + /** + * Given a location in an original file, open that file in the editor. + * + * @param {string} originalId + * The original "sourceId" returned from the sourcemap worker. + * @param {number} line + * Line number to jump to after selecting. One-indexed + * @param {number} col + * Column number to jump to after selecting. One-indexed + * @return {Promise} + * Promise that will resolve when the editor is selected and ready + * to be used. + */ + selectOriginalSheet(originalId, line, col) { + if (!this.UI) { + return null; + } + + const originalSheet = this.UI.getOriginalSourceSheet(originalId); + return this.UI.selectStyleSheet(originalSheet, line - 1, col ? col - 1 : 0); + }, + + getStylesheetResourceForGeneratedURL(url) { + if (!this.UI) { + return null; + } + + return this.UI.getStylesheetResourceForGeneratedURL(url); + }, + + /** + * Destroy the style editor. + */ + destroy() { + if (this._destroyed) { + return; + } + this._destroyed = true; + + this._toolbox = null; + this._panelWin = null; + this._panelDoc = null; + + this.UI.destroy(); + this.UI = null; + }, +}; + +XPCOMUtils.defineLazyGetter(StyleEditorPanel.prototype, "strings", function () { + return Services.strings.createBundle( + "chrome://devtools/locale/styleeditor.properties" + ); +}); diff --git a/devtools/client/styleeditor/test/autocomplete.html b/devtools/client/styleeditor/test/autocomplete.html new file mode 100644 index 0000000000..801eb4d4b9 --- /dev/null +++ b/devtools/client/styleeditor/test/autocomplete.html @@ -0,0 +1,23 @@ + + + + testcase for autocomplete testing + + + + +
parent child
+ + diff --git a/devtools/client/styleeditor/test/browser.ini b/devtools/client/styleeditor/test/browser.ini new file mode 100644 index 0000000000..089f1b26e0 --- /dev/null +++ b/devtools/client/styleeditor/test/browser.ini @@ -0,0 +1,141 @@ +[DEFAULT] +tags = devtools +subsuite = devtools +support-files = + autocomplete.html + bug_1405342_serviceworker_iframes.html + four.html + head.js + iframe_with_service_worker.html + iframe_service_worker.js + import.css + import.html + import2.css + inline-1.html + inline-2.html + longload.html + longname.html + many-media-rules-sourcemaps/index.html + many-media-rules-sourcemaps/sourcemap/sourcemap-css/sourcemaps.css + many-media-rules-sourcemaps/sourcemap/sourcemap-css/sourcemaps.css.map + many-media-rules-sourcemaps/sourcemap/sourcemap-sass/_partial.scss + many-media-rules-sourcemaps/sourcemap/sourcemap-sass/sourcemaps.scss + media-small.css + media.html + media-rules.html + media-rules.css + media-rules-sourcemaps.html + minified.html + missing.html + nostyle.html + pretty.css + resources_inpage.jsi + resources_inpage1.css + resources_inpage2.css + selector-highlighter.html + simple.css + simple.css.gz + simple.css.gz^headers^ + simple.gz.html + simple.html + sjs_huge-css-server.sjs + sourcemap-css/contained.css + sourcemap-css/sourcemaps.css + sourcemap-css/sourcemaps_chrome.css + sourcemap-css/sourcemaps.css.map + # add nosniff header to test against Bug 1330383 + sourcemap-css/sourcemaps.css.map^headers^ + sourcemap-css/media-rules.css + sourcemap-css/media-rules.css.map + sourcemap-css/test-bootstrap-scss.css + sourcemap-css/test-stylus.css + sourcemap-sass/sourcemaps.scss + # add nosniff header to test against Bug 1330383 + sourcemap-sass/sourcemaps.scss^headers^ + sourcemap-sass/media-rules.scss + sourcemap-styl/test-stylus.styl + sourcemaps.html + sourcemaps-inline.html + sourcemaps-large.html + sourcemaps-watching.html + test_private.css + test_private.html + doc_empty.html + doc_fetch_from_netmonitor.html + doc_long_string.css + doc_long.css + doc_short_string.css + doc_sourcemap_chrome.html + doc_xulpage.xhtml + sync.html + sync_with_csp.css + sync_with_csp.html + utf-16.css + veryveryverylongnamethatcanbreakthestyleeditor.css + !/devtools/client/framework/browser-toolbox/test/helpers-browser-toolbox.js + !/devtools/client/inspector/shared/test/head.js + !/devtools/client/inspector/test/head.js + !/devtools/client/inspector/test/shared-head.js + !/devtools/client/shared/test/shared-head.js + !/devtools/client/shared/test/telemetry-test-helpers.js + !/devtools/client/shared/test/highlighter-test-actor.js + +[browser_styleeditor_add_stylesheet.js] +[browser_styleeditor_at_rules_sidebar.js] +[browser_styleeditor_autocomplete-disabled.js] +[browser_styleeditor_autocomplete.js] +[browser_styleeditor_bom.js] +[browser_styleeditor_bug_1247083_inline_stylesheet_numbering.js] +[browser_styleeditor_bug_1405342_serviceworker_iframes.js] +skip-if = !debug && (os == "win") || (os == "linux" && os_version == "18.04") #bug 1424914 +[browser_styleeditor_bug_740541_iframes.js] +[browser_styleeditor_bug_851132_middle_click.js] +[browser_styleeditor_bug_870339.js] +[browser_styleeditor_copyurl.js] +[browser_styleeditor_enabled.js] +[browser_styleeditor_fetch-from-netmonitor.js] +skip-if = http3 # Bug 1829298 +[browser_styleeditor_filesave.js] +skip-if = http3 # Bug 1829298 +[browser_styleeditor_filter.js] +[browser_styleeditor_fission_switch_target.js] +[browser_styleeditor_highlight-selector.js] +[browser_styleeditor_import.js] +[browser_styleeditor_import_rule.js] +[browser_styleeditor_init.js] +[browser_styleeditor_inline_friendly_names.js] +[browser_styleeditor_loading.js] +skip-if = http3 # Bug 1829298 +[browser_styleeditor_loading_with_containers.js] +[browser_styleeditor_media_sidebar_links.js] +[browser_styleeditor_media_sidebar_sourcemaps.js] +[browser_styleeditor_missing_stylesheet.js] +[browser_styleeditor_navigate.js] +[browser_styleeditor_new.js] +[browser_styleeditor_nostyle.js] +[browser_styleeditor_opentab.js] +[browser_styleeditor_pretty.js] +[browser_styleeditor_private_perwindowpb.js] +[browser_styleeditor_reload.js] +[browser_styleeditor_resize_performance.js] +[browser_styleeditor_scroll.js] +[browser_styleeditor_selectstylesheet.js] +[browser_styleeditor_sidebars.js] +[browser_styleeditor_sourcemap_chrome.js] +[browser_styleeditor_sourcemap_large.js] +[browser_styleeditor_sourcemap_watching.js] +skip-if = http3 # Bug 1829298 +[browser_styleeditor_sourcemaps.js] +[browser_styleeditor_sourcemaps_inline.js] +[browser_styleeditor_sv_keynav.js] +[browser_styleeditor_sv_resize.js] +[browser_styleeditor_sync.js] +[browser_styleeditor_syncAddProperty.js] +[browser_styleeditor_syncAddRule.js] +[browser_styleeditor_syncAlreadyOpen.js] +[browser_styleeditor_syncEditSelector.js] +[browser_styleeditor_syncIntoRuleView.js] +[browser_styleeditor_transition_rule.js] +[browser_styleeditor_xul.js] +[browser_toolbox_styleeditor.js] +skip-if = asan # Bug 1591064 diff --git a/devtools/client/styleeditor/test/browser_styleeditor_add_stylesheet.js b/devtools/client/styleeditor/test/browser_styleeditor_add_stylesheet.js new file mode 100644 index 0000000000..794de2c328 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_add_stylesheet.js @@ -0,0 +1,36 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that a newly-added style sheet shows up in the style editor. + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "Two sheets present after load."); + + // We have to wait for the length to change, because we might still + // be seeing events from the initial open. + const added = new Promise(resolve => { + const handler = () => { + if (ui.editors.length === 3) { + ui.off("editor-added", handler); + resolve(); + } + }; + ui.on("editor-added", handler); + }); + + info("Adding a style sheet"); + await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => { + const document = content.document; + const style = document.createElement("style"); + style.appendChild(document.createTextNode("div { background: #f06; }")); + document.head.appendChild(style); + }); + await added; + + is(ui.editors.length, 3, "Three sheets present after new style sheet"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_at_rules_sidebar.js b/devtools/client/styleeditor/test/browser_styleeditor_at_rules_sidebar.js new file mode 100644 index 0000000000..6a7c7cc4b8 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_at_rules_sidebar.js @@ -0,0 +1,312 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// https rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTPS + "media-rules.html"; +const SIDEBAR_PREF = "devtools.styleeditor.showAtRulesSidebar"; + +const RESIZE_W = 300; +const RESIZE_H = 450; +const LABELS = [ + "not all", + "all", + "(max-width: 550px)", + "(min-height: 300px) and (max-height: 320px)", + "(max-width: 750px)", + "print", +]; +const LINE_NOS = [1, 7, 19, 25, 31, 36]; +const NEW_RULE = ` + @media (max-width: 750px) { + div { + color: blue; + } + + @media print { + body { + filter: grayscale(100%); + } + } + }`; + +waitForExplicitFinish(); + +add_task(async function () { + await pushPref("layout.css.container-queries.enabled", true); + + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 4, "correct number of editors"); + + info("Test first plain css editor"); + const plainEditor = ui.editors[0]; + await openEditor(plainEditor); + testPlainEditor(plainEditor); + + info("Test editor for inline sheet with @media rules"); + const inlineMediaEditor = ui.editors[3]; + await openEditor(inlineMediaEditor); + await testInlineMediaEditor(ui, inlineMediaEditor); + + info("Test editor with @media rules"); + const mediaEditor = ui.editors[1]; + await openEditor(mediaEditor); + await testMediaEditor(ui, mediaEditor); + + info("Test that sidebar hides when flipping pref"); + await testShowHide(ui, mediaEditor); + + info("Test adding a rule updates the list"); + await testMediaRuleAdded(ui, mediaEditor); + + info("Test resizing and seeing @media matching state change"); + const originalWidth = window.outerWidth; + const originalHeight = window.outerHeight; + + const onMatchesChange = ui.once("at-rules-list-changed"); + window.resizeTo(RESIZE_W, RESIZE_H); + await onMatchesChange; + + testMediaMatchChanged(mediaEditor); + + window.resizeTo(originalWidth, originalHeight); +}); + +function testPlainEditor(editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + is(sidebar.hidden, true, "sidebar is hidden on editor without @media"); +} + +async function testInlineMediaEditor(ui, editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + is(sidebar.hidden, false, "sidebar is showing on editor with @media"); + + const entries = sidebar.querySelectorAll(".at-rule-label"); + is(entries.length, 5, "5 @media rules displayed in sidebar"); + + await testRule({ + ui, + editor, + rule: entries[0], + conditionText: "screen", + matches: true, + line: 2, + type: "media", + }); + + await testRule({ + ui, + editor, + rule: entries[1], + conditionText: "(display: flex)", + line: 7, + type: "support", + }); + + await testRule({ + ui, + editor, + rule: entries[2], + conditionText: "(1px < height < 10000px)", + matches: true, + line: 8, + type: "media", + }); + + await testRule({ + ui, + editor, + rule: entries[3], + conditionText: "", + line: 16, + type: "layer", + layerName: "myLayer", + }); + + await testRule({ + ui, + editor, + rule: entries[4], + conditionText: "(min-width: 1px)", + line: 17, + type: "container", + }); +} + +async function testMediaEditor(ui, editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + is(sidebar.hidden, false, "sidebar is showing on editor with @media"); + + const entries = [...sidebar.querySelectorAll(".at-rule-label")]; + is(entries.length, 4, "four @media rules displayed in sidebar"); + + await testRule({ + ui, + editor, + rule: entries[0], + conditionText: LABELS[0], + matches: false, + line: LINE_NOS[0], + }); + await testRule({ + ui, + editor, + rule: entries[1], + conditionText: LABELS[1], + matches: true, + line: LINE_NOS[1], + }); + await testRule({ + ui, + editor, + rule: entries[2], + conditionText: LABELS[2], + matches: false, + line: LINE_NOS[2], + }); + await testRule({ + ui, + editor, + rule: entries[3], + conditionText: LABELS[3], + matches: false, + line: LINE_NOS[3], + }); +} + +function testMediaMatchChanged(editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + + const cond = sidebar.querySelectorAll(".at-rule-condition")[2]; + is( + cond.textContent, + "(max-width: 550px)", + "third rule condition text is correct" + ); + ok( + !cond.classList.contains("media-condition-unmatched"), + "media rule is now matched after resizing" + ); +} + +async function testShowHide(ui, editor) { + let sidebarChange = ui.once("at-rules-list-changed"); + Services.prefs.setBoolPref(SIDEBAR_PREF, false); + await sidebarChange; + + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + is(sidebar.hidden, true, "sidebar is hidden after flipping pref"); + + sidebarChange = ui.once("at-rules-list-changed"); + Services.prefs.clearUserPref(SIDEBAR_PREF); + await sidebarChange; + + is(sidebar.hidden, false, "sidebar is showing after flipping pref back"); +} + +async function testMediaRuleAdded(ui, editor) { + await editor.getSourceEditor(); + let text = editor.sourceEditor.getText(); + text += NEW_RULE; + + const listChange = ui.once("at-rules-list-changed"); + editor.sourceEditor.setText(text); + await listChange; + + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + const entries = [...sidebar.querySelectorAll(".at-rule-label")]; + is(entries.length, 6, "six @media rules after changing text"); + + await testRule({ + ui, + editor, + rule: entries[4], + conditionText: LABELS[4], + matches: false, + line: LINE_NOS[4], + }); + + await testRule({ + ui, + editor, + rule: entries[5], + conditionText: LABELS[5], + matches: false, + line: LINE_NOS[5], + }); +} + +/** + * Run assertion on given rule + * + * @param {Object} options + * @param {StyleEditorUI} options.ui + * @param {StyleSheetEditor} options.editor: The editor the rule is displayed in + * @param {Element} options.rule: The rule element in the media sidebar + * @param {String} options.conditionText: media query condition text + * @param {Boolean} options.matches: Whether or not the document matches the rule + * @param {String} options.layerName: Optional name of the @layer + * @param {Number} options.line: Line of the rule + * @param {String} options.type: The type of the rule (container, layer, media, support ). + * Defaults to "media". + */ +async function testRule({ + ui, + editor, + rule, + conditionText, + matches, + layerName, + line, + type = "media", +}) { + const atTypeEl = rule.querySelector(".at-rule-type"); + is( + atTypeEl.textContent, + `@${type}\u00A0${layerName ? `${layerName}\u00A0` : ""}`, + "label for at-rule type is correct" + ); + + const cond = rule.querySelector(".at-rule-condition"); + is( + cond.textContent, + conditionText, + "condition label is correct for " + conditionText + ); + + if (type == "media") { + const matched = !cond.classList.contains("media-condition-unmatched"); + ok( + matches ? matched : !matched, + "media rule is " + (matches ? "matched" : "unmatched") + ); + } + + const ruleLine = rule.querySelector(".at-rule-line"); + is(ruleLine.textContent, ":" + line, "correct line number shown"); + + info( + "Check that clicking on the rule jumps to the expected position in the stylesheet" + ); + rule.click(); + await waitFor( + () => + ui.selectedEditor == editor && + editor.sourceEditor.getCursor().line == line - 1 + ); + ok(true, "Jumped to the expected location"); +} + +/* Helpers */ + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_autocomplete-disabled.js b/devtools/client/styleeditor/test/browser_styleeditor_autocomplete-disabled.js new file mode 100644 index 0000000000..fd7d4969d0 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_autocomplete-disabled.js @@ -0,0 +1,42 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that autocomplete can be disabled. + +const TESTCASE_URI = TEST_BASE_HTTP + "autocomplete.html"; + +// Pref which decides if CSS autocompletion is enabled in Style Editor or not. +const AUTOCOMPLETION_PREF = "devtools.styleeditor.autocompletion-enabled"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + const editor = await ui.editors[0].getSourceEditor(); + editor.sourceEditor.setOption("autocomplete", false); + + is( + editor.sourceEditor.getOption("autocomplete"), + false, + "Autocompletion option does not exist" + ); + ok( + !editor.sourceEditor.getAutocompletionPopup(), + "Autocompletion popup does not exist" + ); +}); + +add_task(async function () { + Services.prefs.setBoolPref(AUTOCOMPLETION_PREF, false); + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + const editor = await ui.editors[0].getSourceEditor(); + + is( + editor.sourceEditor.getOption("autocomplete"), + false, + "Autocompletion option does not exist" + ); +}); + +registerCleanupFunction(() => { + Services.prefs.clearUserPref(AUTOCOMPLETION_PREF); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_autocomplete.js b/devtools/client/styleeditor/test/browser_styleeditor_autocomplete.js new file mode 100644 index 0000000000..b1377c62ab --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_autocomplete.js @@ -0,0 +1,284 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that autocompletion works as expected. + +const TESTCASE_URI = TEST_BASE_HTTP + "autocomplete.html"; +const MAX_SUGGESTIONS = 15; + +// Test cases to test that autocompletion works correctly when enabled. +// Format: +// [ +// key, +// { +// total: Number of suggestions in the popup (-1 if popup is closed), +// current: Index of selected suggestion, +// inserted: 1 to check whether the selected suggestion is inserted into the +// editor or not, +// entered: 1 if the suggestion is inserted and finalized +// } +// ] + +function getTestCases(cssProperties) { + const keywords = getCSSKeywords(cssProperties); + const getSuggestionNumberFor = suggestionNumberGetter(keywords); + + return [ + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["Ctrl+Space", { total: 1, current: 0 }], + ["VK_LEFT"], + ["VK_RIGHT"], + ["VK_DOWN"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["Ctrl+Space", { total: getSuggestionNumberFor("font"), current: 0 }], + ["VK_END"], + ["VK_RETURN"], + ["b", { total: getSuggestionNumberFor("b"), current: 0 }], + ["a", { total: getSuggestionNumberFor("ba"), current: 0 }], + [ + "VK_DOWN", + { total: getSuggestionNumberFor("ba"), current: 0, inserted: 1 }, + ], + [ + "VK_DOWN", + { total: getSuggestionNumberFor("ba"), current: 1, inserted: 1 }, + ], + [ + "VK_TAB", + { total: getSuggestionNumberFor("ba"), current: 2, inserted: 1 }, + ], + ["VK_RETURN", { current: 2, inserted: 1, entered: 1 }], + ["b", { total: getSuggestionNumberFor("background", "b"), current: 0 }], + ["l", { total: getSuggestionNumberFor("background", "bl"), current: 0 }], + [ + "VK_TAB", + { + total: getSuggestionNumberFor("background", "bl"), + current: 0, + inserted: 1, + }, + ], + [ + "VK_DOWN", + { + total: getSuggestionNumberFor("background", "bl"), + current: 1, + inserted: 1, + }, + ], + [ + "VK_UP", + { + total: getSuggestionNumberFor("background", "bl"), + current: 0, + inserted: 1, + }, + ], + [ + "VK_TAB", + { + total: getSuggestionNumberFor("background", "bl"), + current: 1, + inserted: 1, + }, + ], + [ + "VK_TAB", + { + total: getSuggestionNumberFor("background", "bl"), + current: 2, + inserted: 1, + }, + ], + [";"], + ["VK_RETURN"], + ["c", { total: getSuggestionNumberFor("c"), current: 0 }], + ["o", { total: getSuggestionNumberFor("co"), current: 0 }], + ["VK_RETURN", { current: 0, inserted: 1 }], + ["r", { total: getSuggestionNumberFor("color", "r"), current: 0 }], + ["VK_RETURN", { current: 0, inserted: 1 }], + [";"], + ["VK_LEFT"], + ["VK_RIGHT"], + ["VK_DOWN"], + ["VK_RETURN"], + ["b", { total: 2, current: 0 }], + ["u", { total: 1, current: 0 }], + ["VK_RETURN", { current: 0, inserted: 1 }], + ["{"], + ["VK_HOME"], + ["VK_DOWN"], + ["VK_DOWN"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["VK_RIGHT"], + ["Ctrl+Space", { total: 1, current: 0 }], + ]; +} + +add_task(async function () { + // We try to type "background" above, so backdrop-filter enabledness affects + // the expectations. Instead of branching on the test set the pref to true + // here as that is the end state, and it doesn't interact with the test in + // other ways. + await SpecialPowers.pushPrefEnv({ + set: [["layout.css.backdrop-filter.enabled", true]], + }); + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + const { cssProperties } = ui; + const testCases = getTestCases(cssProperties); + + await ui.selectStyleSheet(ui.editors[1].styleSheet); + const editor = await ui.editors[1].getSourceEditor(); + + const sourceEditor = editor.sourceEditor; + const popup = sourceEditor.getAutocompletionPopup(); + + await SimpleTest.promiseFocus(panel.panelWindow); + + for (const index in testCases) { + await testState(testCases, index, sourceEditor, popup, panel.panelWindow); + await checkState(testCases, index, sourceEditor, popup); + } +}); + +function testState(testCases, index, sourceEditor, popup, panelWindow) { + let [key, details] = testCases[index]; + let entered; + if (details) { + entered = details.entered; + } + const mods = {}; + + info( + "pressing key " + + key + + " to get result: " + + JSON.stringify(testCases[index]) + + " for index " + + index + ); + + let evt = "after-suggest"; + + if (key == "Ctrl+Space") { + key = " "; + mods.ctrlKey = true; + } else if (key == "VK_RETURN" && entered) { + evt = "popup-hidden"; + } else if ( + /(left|right|return|home|end)/gi.test(key) || + (key == "VK_DOWN" && !popup.isOpen) + ) { + evt = "cursorActivity"; + } else if (key == "VK_TAB" || key == "VK_UP" || key == "VK_DOWN") { + evt = "suggestion-entered"; + } + + const ready = sourceEditor.once(evt); + EventUtils.synthesizeKey(key, mods, panelWindow); + + return ready; +} + +function checkState(testCases, index, sourceEditor, popup) { + return new Promise(resolve => { + executeSoon(() => { + let [, details] = testCases[index]; + details = details || {}; + const { total, current, inserted } = details; + + if (total != undefined) { + ok(popup.isOpen, "Popup is open for index " + index); + is( + total, + popup.itemCount, + "Correct total suggestions for index " + index + ); + is( + current, + popup.selectedIndex, + "Correct index is selected for index " + index + ); + if (inserted) { + const { text } = popup.getItemAtIndex(current); + const { line, ch } = sourceEditor.getCursor(); + const lineText = sourceEditor.getText(line); + is( + lineText.substring(ch - text.length, ch), + text, + "Current suggestion from the popup is inserted into the editor." + ); + } + } else { + ok(!popup.isOpen, "Popup is closed for index " + index); + if (inserted) { + const { text } = popup.getItemAtIndex(current); + const { line, ch } = sourceEditor.getCursor(); + const lineText = sourceEditor.getText(line); + is( + lineText.substring(ch - text.length, ch), + text, + "Current suggestion from the popup is inserted into the editor." + ); + } + } + resolve(); + }); + }); +} + +/** + * Returns a list of all property names and a map of property name vs possible + * CSS values provided by the Gecko engine. + * + * @return {Object} An object with following properties: + * - CSSProperties {Array} Array of string containing all the possible + * CSS property names. + * - CSSValues {Object|Map} A map where key is the property name and + * value is an array of string containing all the possible + * CSS values the property can have. + */ +function getCSSKeywords(cssProperties) { + const props = {}; + const propNames = cssProperties.getNames(); + propNames.forEach(prop => { + props[prop] = cssProperties.getValues(prop).sort(); + }); + return { + CSSValues: props, + CSSProperties: propNames.sort(), + }; +} + +/** + * Returns a function that returns the number of expected suggestions for the given + * property and value. If the value is not null, returns the number of values starting + * with `value`. Returns the number of properties starting with `property` otherwise. + */ +function suggestionNumberGetter({ CSSProperties, CSSValues }) { + return (property, value) => { + if (value == null) { + return CSSProperties.filter(prop => prop.startsWith(property)).slice( + 0, + MAX_SUGGESTIONS + ).length; + } + return CSSValues[property] + .filter(val => val.startsWith(value)) + .slice(0, MAX_SUGGESTIONS).length; + }; +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bom.js b/devtools/client/styleeditor/test/browser_styleeditor_bom.js new file mode 100644 index 0000000000..863351a32c --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bom.js @@ -0,0 +1,37 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const BOM_CSS = TEST_BASE_HTTPS + "utf-16.css"; +const DOCUMENT = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + [ + "", + "", + " ", + " Bug 1301854", + ' ', + " ", + " ", + " ", + "", + ].join("\n") + ); + +const CONTENTS = + "// Note that this file must be utf-16 with a " + + "BOM for the test to make sense.\n"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(DOCUMENT); + + is(ui.editors.length, 1, "correct number of editors"); + + const editor = ui.editors[0]; + await editor.getSourceEditor(); + + const text = editor.sourceEditor.getText(); + is(text, CONTENTS, "editor contains expected text"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bug_1247083_inline_stylesheet_numbering.js b/devtools/client/styleeditor/test/browser_styleeditor_bug_1247083_inline_stylesheet_numbering.js new file mode 100644 index 0000000000..1f40d44cc1 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_1247083_inline_stylesheet_numbering.js @@ -0,0 +1,104 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that the displayed numbering of inline and user-created stylesheets are independent of their absolute index +// See bug 1247083. + +const SIMPLE = TEST_BASE_HTTP + "simple.css"; +const LONG = TEST_BASE_HTTP + "doc_long.css"; +const DOCUMENT_WITH_LONG_SHEET = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + [ + "", + "", + " ", + " Style editor numbering test page", + + // first inline stylesheet + " ", + // first external stylesheet + ' ', + // second external stylesheet + ' ', + // second inline stylesheet + " ", + + " ", + " ", + " ", + "", + ].join("\n") + ); + +add_task(async function () { + info("Test that inline stylesheets are numbered correctly"); + const { ui } = await openStyleEditorForURL(DOCUMENT_WITH_LONG_SHEET); + + is(ui.editors.length, 4, "4 editors present."); + + const firstEditor = ui.editors[0]; + is( + firstEditor.styleSheetFriendlyIndex, + 0, + "1st inline stylesheet's index is 0" + ); + + is( + firstEditor.styleSheet.styleSheetIndex, + 0, + "1st inline stylesheet is also the first stylesheet declared" + ); + + is(firstEditor.styleSheet.ruleCount, 1, "1st inline stylesheet has 1 rule"); + + const secondEditor = ui.editors[3]; + is( + secondEditor.styleSheetFriendlyIndex, + 1, + "2nd inline stylesheet's index is 1" + ); + + is( + secondEditor.styleSheet.styleSheetIndex, + 3, + "2nd inline stylesheet is the last stylesheet" + ); + + is(secondEditor.styleSheet.ruleCount, 2, "2nd inline stylesheet has 2 rules"); +}); + +add_task(async function () { + info("Test that user-created stylesheets are numbered correctly"); + const { panel, ui } = await openStyleEditorForURL(DOCUMENT_WITH_LONG_SHEET); + await createNewStyleSheet(ui, panel.panelWindow); + await createNewStyleSheet(ui, panel.panelWindow); + + is(ui.editors.length, 6, "6 editors present."); + + ok(ui.editors[4].isNew, "2nd to last editor is user-created"); + is( + ui.editors[4].styleSheetFriendlyIndex, + 0, + "2nd to last user created stylesheet's index is 0" + ); + + ok(ui.editors[5].isNew, "Last editor is user-created"); + is( + ui.editors[5].styleSheetFriendlyIndex, + 1, + "Last user created stylesheet's index is 1" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bug_1405342_serviceworker_iframes.js b/devtools/client/styleeditor/test/browser_styleeditor_bug_1405342_serviceworker_iframes.js new file mode 100644 index 0000000000..cccd92fedd --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_1405342_serviceworker_iframes.js @@ -0,0 +1,27 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that sheets inside cross origin iframes, served from a service worker +// are correctly fetched via the service worker in the stylesheet editor. + +add_task(async function () { + const TEST_URL = + "https://test1.example.com/browser/devtools/client/styleeditor/test/bug_1405342_serviceworker_iframes.html"; + const { ui } = await openStyleEditorForURL(TEST_URL); + + if (ui.editors.length != 1) { + info("Stylesheet isn't available immediately, waiting for it"); + await ui.once("editor-added"); + } + is(ui.editors.length, 1, "Got the iframe stylesheet"); + + await ui.selectStyleSheet(ui.editors[0].styleSheet); + const editor = await ui.editors[0].getSourceEditor(); + const text = editor.sourceEditor.getText(); + is( + text, + "* { color: green; }", + "stylesheet content is the one served by the service worker" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js b/devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js new file mode 100644 index 0000000000..9eaf0be0f2 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js @@ -0,0 +1,107 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that sheets inside iframes are shown in the editor. + +add_task(async function () { + function makeStylesheet(selector) { + return ( + "data:text/css;charset=UTF-8," + encodeURIComponent(selector + " { }") + ); + } + + function makeDocument(stylesheets, framedDocuments) { + stylesheets = stylesheets || []; + framedDocuments = framedDocuments || []; + return ( + "data:text/html;charset=UTF-8," + + encodeURIComponent( + Array.prototype.concat + .call( + [ + "", + "", + "", + "Bug 740541", + ], + stylesheets.map(function (sheet) { + return ( + '' + ); + }), + ["", ""], + framedDocuments.map(function (doc) { + return ''; + }), + ["", ""] + ) + .join("\n") + ) + ); + } + + const DOCUMENT_WITH_INLINE_STYLE = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + [ + "", + "", + " ", + " Bug 740541", + ' ", + " ", + " ", + " ", + " ", + ].join("\n") + ); + + const FOUR = TEST_BASE_HTTP + "four.html"; + + const SIMPLE = TEST_BASE_HTTP + "simple.css"; + + const SIMPLE_DOCUMENT = TEST_BASE_HTTP + "simple.html"; + + const TESTCASE_URI = makeDocument( + [makeStylesheet(".a")], + [ + makeDocument([], [FOUR, DOCUMENT_WITH_INLINE_STYLE]), + makeDocument( + [makeStylesheet(".b"), SIMPLE], + [makeDocument([makeStylesheet(".c")], [])] + ), + makeDocument([SIMPLE], []), + SIMPLE_DOCUMENT, + ] + ); + + const EXPECTED_STYLE_SHEET_COUNT = 12; + + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is( + ui.editors.length, + EXPECTED_STYLE_SHEET_COUNT, + "Got the expected number of style sheets." + ); + + // Verify that stylesheets are removed when their related target is destroyed + if (isFissionEnabled() || isEveryFrameTargetEnabled()) { + info("Remove all iframes"); + await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => { + const iframes = content.document.querySelectorAll("iframe"); + for (const iframe of iframes) { + iframe.remove(); + } + }); + + await waitFor( + () => ui.editors.length == 1, + "Wait until all iframe stylesheets are removed and we only have the top document one" + ); + } +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js b/devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js new file mode 100644 index 0000000000..ed0d5838b2 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js @@ -0,0 +1,63 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that middle click on style sheet doesn't open index.xhtml in a new +// tab (bug 851132). + +const TESTCASE_URI = TEST_BASE_HTTP + "four.html"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + gBrowser.tabContainer.addEventListener("TabOpen", onTabAdded); + + await ui.editors[0].getSourceEditor(); + info("first editor selected"); + + await waitFor( + () => ui.editors[0].sourceEditor.hasFocus(), + "Wait until the initially selected editor grabs the focus" + ); + + info("Left-clicking on the second editor link."); + await clickOnStyleSheetLink(ui.editors[1], 0); + + info("Waiting for the second editor to be selected."); + const editor = await ui.once("editor-selected"); + + ok( + editor.sourceEditor.hasFocus(), + "Left mouse click gave second editor focus." + ); + + // middle mouse click should not open a new tab + info("Middle clicking on the third editor link."); + await clickOnStyleSheetLink(ui.editors[2], 1); +}); + +/** + * A helper that clicks on style sheet link in the sidebar. + * + * @param {StyleSheetEditor} editor + * The editor of which link should be clicked. + * @param {MouseEvent.button} button + * The button to click the link with. + */ +async function clickOnStyleSheetLink(editor, button) { + const window = editor._window; + const link = editor.summary.querySelector(".stylesheet-name"); + + info("Waiting for focus."); + await SimpleTest.promiseFocus(window); + + info("Pressing button " + button + " on style sheet name link."); + EventUtils.synthesizeMouseAtCenter(link, { button }, window); +} + +function onTabAdded() { + ok(false, "middle mouse click has opened a new tab"); +} + +registerCleanupFunction(function () { + gBrowser.tabContainer.removeEventListener("TabOpen", onTabAdded); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_bug_870339.js b/devtools/client/styleeditor/test/browser_styleeditor_bug_870339.js new file mode 100644 index 0000000000..926048223d --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_870339.js @@ -0,0 +1,49 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +const SIMPLE = TEST_BASE_HTTP + "simple.css"; +const DOCUMENT_WITH_ONE_STYLESHEET = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + [ + "", + "", + " ", + " Bug 870339", + ' ', + " ", + " ", + " ", + "", + ].join("\n") + ); + +add_task(async function () { + const { ui } = await openStyleEditorForURL(DOCUMENT_WITH_ONE_STYLESHEET); + + // Spam the "devtools.source-map.client-service.enabled" pref observer callback (#onOrigSourcesPrefChanged) + // multiple times before the StyleEditorActor has a chance to respond to the first one. + const SPAM_COUNT = 2; + let prefValue = false; + for (let i = 0; i < SPAM_COUNT; ++i) { + pushPref("devtools.source-map.client-service.enabled", prefValue); + prefValue = !prefValue; + } + + // Wait for the StyleEditorActor to respond to each pref changes. + await new Promise(resolve => { + let loadCount = 0; + ui.on("stylesheets-refreshed", function onReset() { + ++loadCount; + if (loadCount == SPAM_COUNT) { + ui.off("stylesheets-refreshed", onReset); + // No matter how large SPAM_COUNT is, the number of style + // sheets should never be more than the number of style sheets + // in the document. + is(ui.editors.length, 1, "correct style sheet count"); + resolve(); + } + }); + }); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_copyurl.js b/devtools/client/styleeditor/test/browser_styleeditor_copyurl.js new file mode 100644 index 0000000000..8b2919a173 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_copyurl.js @@ -0,0 +1,43 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test to check the 'Copy URL' functionality in the context menu item for stylesheets. + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + + const doc = panel.panelWindow.document; + const contextMenu = getContextMenuElement(panel); + const copyUrlItem = doc.getElementById("context-copyurl"); + + const onContextMenuShown = new Promise(resolve => { + contextMenu.addEventListener("popupshown", resolve, { once: true }); + }); + + info("Right-click the first stylesheet editor."); + const editor = ui.editors[0]; + + is(editor.friendlyName, "simple.css", "editor is the expected one"); + + const stylesheetEl = editor.summary.querySelector(".stylesheet-name"); + await EventUtils.synthesizeMouseAtCenter( + stylesheetEl, + { button: 2, type: "contextmenu" }, + panel.panelWindow + ); + await onContextMenuShown; + + ok(!copyUrlItem.hidden, "Copy URL menu item should be showing."); + + info( + "Click on Copy URL menu item and wait for the URL to be copied to the clipboard." + ); + await waitForClipboardPromise( + () => contextMenu.activateItem(copyUrlItem), + `${TEST_BASE_HTTPS}simple.css` + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_enabled.js b/devtools/client/styleeditor/test/browser_styleeditor_enabled.js new file mode 100644 index 0000000000..40324b2ea6 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_enabled.js @@ -0,0 +1,129 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that style sheets can be disabled and enabled. + +// https rather than chrome to improve coverage +const SIMPLE_URI = TEST_BASE_HTTPS + "simple.html"; +const LONGNAME_URI = TEST_BASE_HTTPS + "longname.html"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(SIMPLE_URI); + const editor = await ui.editors[0].getSourceEditor(); + + const summary = editor.summary; + const stylesheetToggle = summary.querySelector(".stylesheet-toggle"); + ok(stylesheetToggle, "stylesheet toggle button exists"); + + is( + editor.styleSheet.disabled, + false, + "first stylesheet is initially enabled" + ); + + is( + summary.classList.contains("disabled"), + false, + "first stylesheet is initially enabled, UI does not have DISABLED class" + ); + + info("Disabling the first stylesheet."); + await toggleEnabled(editor, stylesheetToggle, panel.panelWindow); + + is(editor.styleSheet.disabled, true, "first stylesheet is now disabled"); + is( + summary.classList.contains("disabled"), + true, + "first stylesheet is now disabled, UI has DISABLED class" + ); + + info("Enabling the first stylesheet again."); + await toggleEnabled(editor, stylesheetToggle, panel.panelWindow); + + is( + editor.styleSheet.disabled, + false, + "first stylesheet is now enabled again" + ); + is( + summary.classList.contains("disabled"), + false, + "first stylesheet is now enabled again, UI does not have DISABLED class" + ); +}); + +// Check that stylesheets with long names do not prevent the toggle button +// from being visible. +add_task(async function testLongNameStylesheet() { + const { ui } = await openStyleEditorForURL(LONGNAME_URI); + + is(ui.editors.length, 2, "Expected 2 stylesheet editors"); + + // Test that the first editor, which should have a stylesheet with a short + // name. + let editor = ui.editors[0]; + let stylesheetToggle = editor.summary.querySelector(".stylesheet-toggle"); + is(editor.friendlyName, "simple.css"); + ok(stylesheetToggle, "stylesheet toggle button exists"); + ok(stylesheetToggle.getBoundingClientRect().width > 0); + ok(stylesheetToggle.getBoundingClientRect().height > 0); + + const expectedWidth = stylesheetToggle.getBoundingClientRect().width; + const expectedHeight = stylesheetToggle.getBoundingClientRect().height; + + // Test that the second editor, which should have a stylesheet with a long + // name. + editor = ui.editors[1]; + stylesheetToggle = editor.summary.querySelector(".stylesheet-toggle"); + is(editor.friendlyName, "veryveryverylongnamethatcanbreakthestyleeditor.css"); + ok(stylesheetToggle, "stylesheet toggle button exists"); + is(stylesheetToggle.getBoundingClientRect().width, expectedWidth); + is(stylesheetToggle.getBoundingClientRect().height, expectedHeight); +}); + +add_task(async function testSystemStylesheet() { + const { ui } = await openStyleEditorForURL("about:support"); + + const aboutSupportEditor = ui.editors.find( + editor => editor.friendlyName === "aboutSupport.css" + ); + ok(!!aboutSupportEditor, "Found the editor for aboutSupport.css"); + const aboutSupportToggle = + aboutSupportEditor.summary.querySelector(".stylesheet-toggle"); + ok(aboutSupportToggle, "enabled toggle button exists"); + ok(!aboutSupportToggle.disabled, "enabled toggle button is not disabled"); + is( + aboutSupportToggle.getAttribute("tooltiptext"), + "Toggle style sheet visibility" + ); + + const formsEditor = ui.editors.find( + editor => editor.friendlyName === "forms.css" + ); + ok(!!formsEditor, "Found the editor for forms.css"); + const formsToggle = formsEditor.summary.querySelector(".stylesheet-toggle"); + ok(formsToggle, "enabled toggle button exists"); + ok(formsToggle.disabled, "enabled toggle button is disabled"); + is( + formsToggle.getAttribute("tooltiptext"), + "System style sheets can’t be disabled" + ); +}); + +async function toggleEnabled(editor, stylesheetToggle, panelWindow) { + const changed = editor.once("property-change"); + + info("Waiting for focus."); + await SimpleTest.promiseFocus(panelWindow); + + info("Clicking on the toggle."); + EventUtils.synthesizeMouseAtCenter(stylesheetToggle, {}, panelWindow); + + info("Waiting for stylesheet to be disabled."); + let property = await changed; + while (property !== "disabled") { + info("Ignoring property-change for '" + property + "'."); + property = await editor.once("property-change"); + } +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_fetch-from-netmonitor.js b/devtools/client/styleeditor/test/browser_styleeditor_fetch-from-netmonitor.js new file mode 100644 index 0000000000..7169de8bf5 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_fetch-from-netmonitor.js @@ -0,0 +1,80 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// A test to ensure Style Editor only issues 1 request for each stylesheet (instead of 2) +// by using the cache on the platform. + +const EMPTY_TEST_URL = TEST_BASE_HTTPS + "doc_empty.html"; +const TEST_URL = TEST_BASE_HTTPS + "doc_fetch_from_netmonitor.html"; + +add_task(async function () { + info("Opening netmonitor"); + // Navigate first to an empty document in order to: + // * avoid introducing a cross process navigation when calling navigateTo() + // * properly wait for request updates when calling navigateTo, while showToolbox + // won't necessarily wait for all pending requests. (If we were loading TEST_URL + // in the tab, we might have pending updates in the netmonitor which won't be + // awaited for by showToolbox) + const tab = await addTab(EMPTY_TEST_URL); + const toolbox = await gDevTools.showToolboxForTab(tab, { + toolId: "netmonitor", + }); + const monitor = toolbox.getPanel("netmonitor"); + const { store, windowRequire } = monitor.panelWin; + const Actions = windowRequire("devtools/client/netmonitor/src/actions/index"); + const { getSortedRequests } = windowRequire( + "devtools/client/netmonitor/src/selectors/index" + ); + + store.dispatch(Actions.batchEnable(false)); + + info("Navigating to test page"); + await navigateTo(TEST_URL); + + info("Opening Style Editor"); + const styleeditor = await toolbox.selectTool("styleeditor"); + const ui = styleeditor.UI; + + info("Waiting for the sources to be loaded."); + await ui.editors[0].getSourceEditor(); + await ui.selectStyleSheet(ui.editors[1].styleSheet); + await ui.editors[1].getSourceEditor(); + + // Wait till there is 4 requests in Netmonitor store. + await waitUntil(() => getSortedRequests(store.getState()).length == 4); + + info("Checking Netmonitor contents."); + const shortRequests = []; + const longRequests = []; + const hugeRequests = []; + for (const item of getSortedRequests(store.getState())) { + if (item.url.endsWith("doc_short_string.css")) { + shortRequests.push(item); + } + if (item.url.endsWith("doc_long_string.css")) { + longRequests.push(item); + } + if (item.url.endsWith("sjs_huge-css-server.sjs")) { + hugeRequests.push(item); + } + } + + is( + shortRequests.length, + 1, + "Got one request for doc_short_string.css after Style Editor was loaded." + ); + is( + longRequests.length, + 1, + "Got one request for doc_long_string.css after Style Editor was loaded." + ); + + is( + hugeRequests.length, + 1, + "Got one requests for sjs_huge-css-server.sjs after Style Editor was loaded." + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_filesave.js b/devtools/client/styleeditor/test/browser_styleeditor_filesave.js new file mode 100644 index 0000000000..e49d3cf8a9 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_filesave.js @@ -0,0 +1,91 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that 'Save' function works. + +const TESTCASE_URI_HTML = TEST_BASE_HTTP + "simple.html"; +const TESTCASE_URI_CSS = TEST_BASE_HTTP + "simple.css"; + +add_task(async function () { + const htmlFile = await copy(TESTCASE_URI_HTML, "simple.html"); + await copy(TESTCASE_URI_CSS, "simple.css"); + const uri = Services.io.newFileURI(htmlFile); + const filePath = uri.resolve(""); + + const { ui } = await openStyleEditorForURL(filePath); + + const editor = ui.editors[0]; + await editor.getSourceEditor(); + + info("Editing the style sheet."); + let dirty = editor.sourceEditor.once("dirty-change"); + const beginCursor = { line: 0, ch: 0 }; + editor.sourceEditor.replaceText("DIRTY TEXT", beginCursor, beginCursor); + + await dirty; + + is(editor.sourceEditor.isClean(), false, "Editor is dirty."); + ok( + editor.summary.classList.contains("unsaved"), + "Star icon is present in the corresponding summary." + ); + + info("Saving the changes."); + dirty = editor.sourceEditor.once("dirty-change"); + + editor.saveToFile(null, function (file) { + ok(file, "file should get saved directly when using a file:// URI"); + }); + + await dirty; + + is(editor.sourceEditor.isClean(), true, "Editor is clean."); + ok( + !editor.summary.classList.contains("unsaved"), + "Star icon is not present in the corresponding summary." + ); +}); + +function copy(srcChromeURL, destFileName) { + return new Promise(resolve => { + const destFile = FileUtils.getFile("ProfD", [destFileName]); + write(read(srcChromeURL), destFile, resolve); + }); +} + +function read(srcChromeURL) { + const scriptableStream = Cc[ + "@mozilla.org/scriptableinputstream;1" + ].getService(Ci.nsIScriptableInputStream); + + const channel = NetUtil.newChannel({ + uri: srcChromeURL, + loadUsingSystemPrincipal: true, + }); + const input = channel.open(); + scriptableStream.init(input); + + let data = ""; + while (input.available()) { + data = data.concat(scriptableStream.read(input.available())); + } + scriptableStream.close(); + input.close(); + + return data; +} + +function write(data, file, callback) { + const istream = getInputStream(data); + const ostream = FileUtils.openSafeFileOutputStream(file); + + NetUtil.asyncCopy(istream, ostream, function (status) { + if (!Components.isSuccessCode(status)) { + info("Couldn't write to " + file.path); + return; + } + + callback(file); + }); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_filter.js b/devtools/client/styleeditor/test/browser_styleeditor_filter.js new file mode 100644 index 0000000000..c8472b5f40 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_filter.js @@ -0,0 +1,343 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +requestLongerTimeout(2); + +// Check that the stylesheets list can be filtered + +const INITIAL_INLINE_STYLE_SHEETS_COUNT = 100; + +const TEST_URI = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + ` + + + + Test filter + + ${Array.from({ length: INITIAL_INLINE_STYLE_SHEETS_COUNT }) + .map((_, i) => ``) + .join("\n")} + + + + + + ` + ); + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TEST_URI); + const { panelWindow } = panel; + is( + ui.editors.length, + INITIAL_INLINE_STYLE_SHEETS_COUNT + 2, + "correct number of editors" + ); + + const doc = panel.panelWindow.document; + + const filterInput = doc.querySelector(".devtools-filterinput"); + const filterInputClearButton = doc.querySelector( + ".devtools-searchinput-clear" + ); + ok(filterInput, "There's a filter input"); + ok(filterInputClearButton, "There's a clear button next to the filter input"); + ok( + filterInputClearButton.hasAttribute("hidden"), + "The clear button is hidden by default" + ); + + const setFilterInputValue = value => { + // The keyboard shortcut focuses the input and select its content, so we should + // be able to type right-away. + synthesizeKeyShortcut("CmdOrCtrl+P"); + EventUtils.sendString(value); + }; + + info( + "Check that the list can be filtered with the stylesheet name, regardless of the casing" + ); + let onEditorSelected = ui.once("editor-selected"); + setFilterInputValue("PREttY"); + ok( + !filterInputClearButton.hasAttribute("hidden"), + "The clear button is visible when the input isn't empty" + ); + Assert.deepEqual( + getVisibleStyleSheetsNames(doc), + ["pretty.css"], + "Only pretty.css is now displayed" + ); + + await onEditorSelected; + is( + ui.selectedEditor, + ui.editors.at(-1), + "When the selected stylesheet is filtered out, the first visible one gets selected" + ); + is( + filterInput.ownerGlobal.document.activeElement, + filterInput, + "Even when a stylesheet was automatically opened, the filter input is still focused" + ); + ok(!ui.selectedEditor.sourceEditor.hasFocus(), "Editor doesn't have focus."); + + info( + "Clicking on the clear button should clear the input and unfilter the list" + ); + EventUtils.synthesizeMouseAtCenter( + filterInputClearButton, + {}, + panel.panelWindow + ); + is(filterInput.value, "", "input was cleared"); + ok(!isListFiltered(doc), "List isn't filtered anymore"); + ok( + filterInputClearButton.hasAttribute("hidden"), + "The clear button is hidden after clicking on it" + ); + + info("Check that the list can be filtered with name-less stylesheets"); + onEditorSelected = ui.once("editor-selected"); + setFilterInputValue("#1"); + Assert.deepEqual( + getVisibleStyleSheetsNames(doc), + [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ], + `List is showing inline stylesheets whose index start with "1"` + ); + await onEditorSelected; + is( + ui.selectedEditor, + ui.editors[1], + "The first visible stylesheet got selected" + ); + + info("Check that keyboard navigation still works when the list is filtered"); + // Move focus out of the input + EventUtils.synthesizeKey("VK_TAB", {}, panelWindow); + EventUtils.synthesizeKey("VK_DOWN", {}, panelWindow); + + is( + panelWindow.document.activeElement.childNodes[0].value, + "", + "focus is on first inline stylesheet" + ); + + EventUtils.synthesizeKey("VK_DOWN", {}, panelWindow); + is( + panelWindow.document.activeElement.childNodes[0].value, + "", + "focus is on inline stylesheet #10" + ); + + EventUtils.synthesizeKey("VK_DOWN", {}, panelWindow); + is( + panelWindow.document.activeElement.childNodes[0].value, + "", + "focus is on inline stylesheet #11" + ); + + info( + "Check that when stylesheets are added in the page, they respect the filter state" + ); + let onEditorAdded = ui.once("editor-added"); + // Adding an inline stylesheet that will match the search + await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => { + const document = content.document; + const style = document.createElement("style"); + style.appendChild(document.createTextNode(`/* inline 101 */`)); + document.head.appendChild(style); + }); + await onEditorAdded; + ok( + getVisibleStyleSheetsNames(doc).includes(""), + "New inline stylesheet is visible as it matches the search" + ); + + // Adding a stylesheet that won't match the search + onEditorAdded = ui.once("editor-added"); + await SpecialPowers.spawn( + gBrowser.selectedBrowser, + [TEST_BASE_HTTPS], + baseUrl => { + const document = content.document; + const link = document.createElement("link"); + link.setAttribute("rel", "stylesheet"); + link.setAttribute("type", "text/css"); + link.setAttribute("href", `${baseUrl}doc_short_string.css`); + document.head.appendChild(link); + } + ); + await onEditorAdded; + + ok( + !getVisibleStyleSheetsNames(doc).includes("doc_short_string.css"), + "doc_short_string.css is not visible as its name does not match the search" + ); + + info( + "Check that clicking on the Add New Stylesheet button clears the list and show the stylesheet" + ); + onEditorAdded = ui.once("editor-added"); + await createNewStyleSheet(ui, panel.panelWindow); + is(filterInput.value, "", "Filter input was cleared"); + + ok(!isListFiltered(doc), "List is not filtered anymore"); + is(ui.selectedEditor, ui.editors.at(-1), "The new stylesheet got selected"); + + info( + "Check that when no stylesheet matches the search, a class is added to the nav" + ); + setFilterInputValue("sync_with_csp"); + ok(navHasAllFilteredClass(panel), `"splitview-all-filtered" was added`); + ok( + filterInput + .closest(".devtools-searchbox") + .classList.contains("devtools-searchbox-no-match"), + `The searchbox has the "devtools-searchbox-no-match" class` + ); + + info( + "Check that adding a stylesheet matching the search remove the splitview-all-filtered class" + ); + onEditorAdded = ui.once("editor-added"); + await SpecialPowers.spawn( + gBrowser.selectedBrowser, + [TEST_BASE_HTTPS], + baseUrl => { + const document = content.document; + const link = document.createElement("link"); + link.setAttribute("rel", "stylesheet"); + link.setAttribute("type", "text/css"); + link.setAttribute("href", `${baseUrl}sync_with_csp.css`); + document.head.appendChild(link); + } + ); + await onEditorAdded; + ok(!navHasAllFilteredClass(panel), `"splitview-all-filtered" was removed`); + ok( + !filterInput + .closest(".devtools-searchbox") + .classList.contains("devtools-searchbox-no-match"), + `The searchbox does not have the "devtools-searchbox-no-match" class anymore` + ); + + info( + "Check that reloading the page when the filter don't match anything won't select anything" + ); + setFilterInputValue("XXXDONTMATCHANYTHING"); + ok(navHasAllFilteredClass(panel), `"splitview-all-filtered" was added`); + await reloadPageAndWaitForStyleSheets( + ui, + INITIAL_INLINE_STYLE_SHEETS_COUNT + 2 + ); + ok( + navHasAllFilteredClass(panel), + `"splitview-all-filtered" is still applied` + ); + is(getVisibleStyleSheets(doc).length, 0, "No stylesheets are displayed"); + is(ui.selectedEditor, null, "No editor was selected"); + + info( + "Check that reloading the page when the filter was matching elements keep the same state" + ); + onEditorSelected = ui.once("editor-selected"); + setFilterInputValue("pretty"); + await onEditorSelected; + Assert.deepEqual( + getVisibleStyleSheetsNames(doc), + ["pretty.css"], + "Only pretty.css is now displayed" + ); + + onEditorSelected = ui.once("editor-selected"); + await reloadPageAndWaitForStyleSheets( + ui, + INITIAL_INLINE_STYLE_SHEETS_COUNT + 2 + ); + await onEditorSelected; + Assert.deepEqual( + getVisibleStyleSheetsNames(doc), + ["pretty.css"], + "pretty.css is still the only stylesheet displayed" + ); + is( + ui.selectedEditor.friendlyName, + "pretty.css", + "pretty.css editor is active" + ); + + info("Check that clearing the input does show all the stylesheets"); + EventUtils.synthesizeMouseAtCenter( + filterInputClearButton, + {}, + panel.panelWindow + ); + ok(!isListFiltered(doc), "List is not filtered anymore"); + is( + ui.selectedEditor.friendlyName, + "pretty.css", + "pretty.css editor is still active" + ); +}); + +/** + * @param {StyleEditorPanel} panel + * @returns Boolean + */ +function navHasAllFilteredClass(panel) { + return panel.panelWindow.document + .querySelector(".splitview-nav") + .classList.contains("splitview-all-filtered"); +} + +/** + * Returns true if there's at least one stylesheet filtered out + * + * @param {Document} doc: StyleEditor document + * @returns Boolean + */ +function isListFiltered(doc) { + return !!doc.querySelectorAll("ol > li.splitview-filtered").length; +} + +/** + * Returns the list of stylesheet list elements. + * + * @param {Document} doc: StyleEditor document + * @returns Array + */ +function getVisibleStyleSheets(doc) { + return Array.from( + doc.querySelectorAll( + "ol > li:not(.splitview-filtered) .stylesheet-name label" + ) + ); +} + +/** + * Returns the list of stylesheet names visible in the style editor list. + * + * @param {Document} doc: StyleEditor document + * @returns Array + */ +function getVisibleStyleSheetsNames(doc) { + return getVisibleStyleSheets(doc).map(label => label.value); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_fission_switch_target.js b/devtools/client/styleeditor/test/browser_styleeditor_fission_switch_target.js new file mode 100644 index 0000000000..9150e88729 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_fission_switch_target.js @@ -0,0 +1,33 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test switching for the top-level target. + +const PARENT_PROCESS_URI = "about:robots"; +const CONTENT_PROCESS_URI = TEST_BASE_HTTPS + "simple.html"; + +add_task(async function () { + // We use about:robots, because this page will run in the parent process. + // Navigating from about:robots to a regular content page will always trigger a target + // switch, with or without fission. + + info("Open a page that runs in the parent process"); + const { ui } = await openStyleEditorForURL(PARENT_PROCESS_URI); + await waitUntil(() => ui.editors.length === 6); + ok(true, `Six style sheets for ${PARENT_PROCESS_URI}`); + + info("Navigate to a page that runs in the child process"); + await navigateToAndWaitForStyleSheets(CONTENT_PROCESS_URI, ui, 2); + // We also have to wait for the toolbox to complete the target switching + // in order to avoid pending requests during test teardown. + ok( + ui.editors.every( + editor => editor._resource.nodeHref == CONTENT_PROCESS_URI + ), + `Two sheets present for ${CONTENT_PROCESS_URI}` + ); + + info("Wait until the editor is ready"); + await waitFor(() => ui.selectedEditor?.sourceEditor); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js b/devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js new file mode 100644 index 0000000000..8936d86ce6 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js @@ -0,0 +1,199 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test that hovering over a simple selector in the style-editor requests the +// highlighting of the corresponding nodes, even in remote iframes. + +const REMOTE_IFRAME_URL = `https://example.org/document-builder.sjs?html= + +

highlighter test

`; +const TOP_LEVEL_URL = `https://example.com/document-builder.sjs?html= + +

highlighter test

+ `; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TOP_LEVEL_URL); + + info( + "Wait until both stylesheet are loaded and ready to handle mouse events" + ); + await waitFor(() => ui.editors.length == 2); + const topLevelStylesheetEditor = ui.editors.find(e => + e._resource.nodeHref.startsWith("https://example.com") + ); + const iframeStylesheetEditor = ui.editors.find(e => + e._resource.nodeHref.startsWith("https://example.org") + ); + + await ui.selectStyleSheet(topLevelStylesheetEditor.styleSheet); + await waitFor(() => topLevelStylesheetEditor.highlighter); + + info("Check that highlighting works on the top-level document"); + const topLevelHighlighterTestFront = + await topLevelStylesheetEditor._resource.targetFront.getFront( + "highlighterTest" + ); + topLevelHighlighterTestFront.highlighter = + topLevelStylesheetEditor.highlighter; + + info("Expecting a node-highlighted event"); + let onHighlighted = topLevelStylesheetEditor.once("node-highlighted"); + + info("Simulate a mousemove event on the h1 selector"); + // mousemove event listeners is set on editor.sourceEditor, which is not defined right away. + await waitFor(() => !!topLevelStylesheetEditor.sourceEditor); + let selectorEl = querySelectorCodeMirrorCssRuleSelectorToken( + topLevelStylesheetEditor + ); + EventUtils.synthesizeMouseAtCenter( + selectorEl, + { type: "mousemove" }, + selectorEl.ownerDocument.defaultView + ); + await onHighlighted; + + ok( + await topLevelHighlighterTestFront.isNodeRectHighlighted( + await getElementNodeRectWithinTarget(["h1"]) + ), + "The highlighter's outline corresponds to the h1 node" + ); + + info( + "Simulate a mousemove event on the property name to hide the highlighter" + ); + EventUtils.synthesizeMouseAtCenter( + querySelectorCodeMirrorCssPropertyNameToken(topLevelStylesheetEditor), + { type: "mousemove" }, + selectorEl.ownerDocument.defaultView + ); + + await waitFor(async () => !topLevelStylesheetEditor.highlighter.isShown()); + let isVisible = await topLevelHighlighterTestFront.isHighlighting(); + is(isVisible, false, "The highlighter is now hidden"); + + info("Check that highlighting works on the iframe document"); + await ui.selectStyleSheet(iframeStylesheetEditor.styleSheet); + await waitFor(() => iframeStylesheetEditor.highlighter); + + const iframeHighlighterTestFront = + await iframeStylesheetEditor._resource.targetFront.getFront( + "highlighterTest" + ); + iframeHighlighterTestFront.highlighter = iframeStylesheetEditor.highlighter; + + info("Expecting a node-highlighted event"); + onHighlighted = iframeStylesheetEditor.once("node-highlighted"); + + info("Simulate a mousemove event on the h2 selector"); + // mousemove event listeners is set on editor.sourceEditor, which is not defined right away. + await waitFor(() => !!iframeStylesheetEditor.sourceEditor); + selectorEl = querySelectorCodeMirrorCssRuleSelectorToken( + iframeStylesheetEditor + ); + EventUtils.synthesizeMouseAtCenter( + selectorEl, + { type: "mousemove" }, + selectorEl.ownerDocument.defaultView + ); + await onHighlighted; + + isVisible = await iframeHighlighterTestFront.isHighlighting(); + ok(isVisible, "The highlighter is shown"); + ok( + await iframeHighlighterTestFront.isNodeRectHighlighted( + await getElementNodeRectWithinTarget(["iframe", "h2"]) + ), + "The highlighter's outline corresponds to the h2 node" + ); + + info("Simulate a mousemove event elsewhere in the editor"); + EventUtils.synthesizeMouseAtCenter( + querySelectorCodeMirrorCssPropertyNameToken(iframeStylesheetEditor), + { type: "mousemove" }, + selectorEl.ownerDocument.defaultView + ); + + await waitFor(async () => !topLevelStylesheetEditor.highlighter.isShown()); + + isVisible = await iframeHighlighterTestFront.isHighlighting(); + is(isVisible, false, "The highlighter is now hidden"); +}); + +function querySelectorCodeMirrorCssRuleSelectorToken(stylesheetEditor) { + // CSS Rules selector (e.g. `h1`) are displayed in a .cm-tag span + return querySelectorCodeMirror(stylesheetEditor, ".cm-tag"); +} + +function querySelectorCodeMirrorCssPropertyNameToken(stylesheetEditor) { + // properties name (e.g. `color`) are displayed in a .cm-property span + return querySelectorCodeMirror(stylesheetEditor, ".cm-property"); +} + +function querySelectorCodeMirror(stylesheetEditor, selector) { + return stylesheetEditor.sourceEditor.codeMirror + .getWrapperElement() + .querySelector(selector); +} + +/** + * Return the bounds of the element matching the selector, relatively to the target bounds + * (e.g. if Fission is enabled, it's related to the iframe bound, if Fission is disabled, + * it's related to the top level document). + * + * @param {Array} selectors: Arrays of CSS selectors from the root document to the node. + * The last CSS selector of the array is for the node in its frame doc. + * The before-last CSS selector is for the frame in its parent frame, etc... + * Ex: ["frame.first-frame", ..., "frame.last-frame", ".target-node"] + * @returns {Object} with left/top/width/height properties representing the node bounds + */ +async function getElementNodeRectWithinTarget(selectors) { + // Retrieve the browsing context in which the element is + const inBCSelector = selectors.pop(); + const frameSelectors = selectors; + const bc = frameSelectors.length + ? await getBrowsingContextInFrames( + gBrowser.selectedBrowser.browsingContext, + frameSelectors + ) + : gBrowser.selectedBrowser.browsingContext; + + // Get the element bounds within the Firefox window + const elementBounds = await SpecialPowers.spawn( + bc, + [inBCSelector], + _selector => { + const el = content.document.querySelector(_selector); + const { left, top, width, height } = el + .getBoxQuadsFromWindowOrigin()[0] + .getBounds(); + return { left, top, width, height }; + } + ); + + // Then we need to offset the element bounds from a frame bounds + // When fission/EFT is enabled, the highlighter is only shown within the iframe bounds. + // So we only need to retrieve the element bounds within the iframe. + // Otherwise, we retrieve the top frame bounds + const relativeBrowsingContext = + isFissionEnabled() || isEveryFrameTargetEnabled() + ? bc + : gBrowser.selectedBrowser.browsingContext; + const relativeDocumentBounds = await SpecialPowers.spawn( + relativeBrowsingContext, + [], + () => + content.document.documentElement + .getBoxQuadsFromWindowOrigin()[0] + .getBounds() + ); + + // Adjust the element bounds based on the relative document bounds + elementBounds.left = elementBounds.left - relativeDocumentBounds.left; + elementBounds.top = elementBounds.top - relativeDocumentBounds.top; + + return elementBounds; +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_import.js b/devtools/client/styleeditor/test/browser_styleeditor_import.js new file mode 100644 index 0000000000..456985f384 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_import.js @@ -0,0 +1,54 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that the import button in the UI works. + +// http rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTP + "simple.html"; + +const FILENAME = "styleeditor-import-test.css"; +const SOURCE = "body{background:red;}"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + + const added = ui.once("test:editor-updated"); + importSheet(ui, panel.panelWindow); + + info("Waiting for editor to be added for the imported sheet."); + const editor = await added; + + is( + editor.savedFile.leafName, + FILENAME, + "imported stylesheet will be saved directly into the same file" + ); + is( + editor.friendlyName, + FILENAME, + "imported stylesheet has the same name as the filename" + ); +}); + +function importSheet(ui, panelWindow) { + // create file to import first + const file = FileUtils.getFile("ProfD", [FILENAME]); + const ostream = FileUtils.openSafeFileOutputStream(file); + const istream = getInputStream(SOURCE); + + NetUtil.asyncCopy(istream, ostream, function () { + FileUtils.closeSafeFileOutputStream(ostream); + + // click the import button now that the file to import is ready + ui._mockImportFile = file; + + waitForFocus(function () { + const document = panelWindow.document; + const importButton = document.querySelector(".style-editor-importButton"); + ok(importButton, "import button exists"); + + EventUtils.synthesizeMouseAtCenter(importButton, {}, panelWindow); + }, panelWindow); + }); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_import_rule.js b/devtools/client/styleeditor/test/browser_styleeditor_import_rule.js new file mode 100644 index 0000000000..1aba71634c --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_import_rule.js @@ -0,0 +1,32 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that style editor shows sheets loaded with @import rules. + +// http rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTPS + "import.html"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 3, "there are 3 stylesheets after loading @imports"); + + is( + ui.editors[0].styleSheet.href, + TEST_BASE_HTTPS + "simple.css", + "stylesheet 1 is simple.css" + ); + + is( + ui.editors[1].styleSheet.href, + TEST_BASE_HTTPS + "import.css", + "stylesheet 2 is import.css" + ); + + is( + ui.editors[2].styleSheet.href, + TEST_BASE_HTTPS + "import2.css", + "stylesheet 3 is import2.css" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_init.js b/devtools/client/styleeditor/test/browser_styleeditor_init.js new file mode 100644 index 0000000000..2183495441 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_init.js @@ -0,0 +1,52 @@ +"use strict"; +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +// Checks that style editor contains correct stylesheets after initialization. + +const TESTCASE_URI = TEST_BASE_HTTP + "simple.html"; +const EXPECTED_SHEETS = [ + { + sheetIndex: 0, + name: /^simple.css$/, + rules: 1, + active: true, + }, + { + sheetIndex: 1, + name: /^<.*>$/, + rules: 3, + active: false, + }, +]; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "The UI contains two style sheets."); + checkSheet(ui.editors[0], EXPECTED_SHEETS[0]); + checkSheet(ui.editors[1], EXPECTED_SHEETS[1]); +}); + +function checkSheet(editor, expected) { + is( + editor.styleSheet.styleSheetIndex, + expected.sheetIndex, + "Style sheet has correct index." + ); + + const summary = editor.summary; + const name = summary + .querySelector(".stylesheet-name > label") + .getAttribute("value"); + ok(expected.name.test(name), "The name '" + name + "' is correct."); + + const ruleCount = summary.querySelector(".stylesheet-rule-count").textContent; + is(parseInt(ruleCount, 10), expected.rules, "the rule count is correct"); + + is( + summary.classList.contains("splitview-active"), + expected.active, + "The active status for this sheet is correct." + ); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js b/devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js new file mode 100644 index 0000000000..35a23fe016 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js @@ -0,0 +1,101 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that inline style sheets get correct names if they are saved to disk and +// that those names survice a reload but not navigation to another page. + +const FIRST_TEST_PAGE = TEST_BASE_HTTPS + "inline-1.html"; +const SECOND_TEST_PAGE = TEST_BASE_HTTPS + "inline-2.html"; +const SAVE_PATH = "test.css"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(FIRST_TEST_PAGE); + + testIndentifierGeneration(ui); + + await saveFirstInlineStyleSheet(ui); + await testFriendlyNamesAfterSave(ui); + await reloadPageAndWaitForStyleSheets(ui, 2); + await testFriendlyNamesAfterSave(ui); + await navigateToAndWaitForStyleSheets(SECOND_TEST_PAGE, ui, 2); + await testFriendlyNamesAfterNavigation(ui); +}); + +function testIndentifierGeneration(ui) { + const fakeStyleSheetFile = { + href: "http://example.com/test.css", + nodeHref: "http://example.com/", + styleSheetIndex: 1, + }; + + const fakeInlineStyleSheet = { + href: null, + nodeHref: "http://example.com/", + styleSheetIndex: 2, + }; + + is( + ui.getStyleSheetIdentifier(fakeStyleSheetFile), + "http://example.com/test.css", + "URI is the identifier of style sheet file." + ); + + is( + ui.getStyleSheetIdentifier(fakeInlineStyleSheet), + "inline-2-at-http://example.com/", + "Inline sheets are identified by their page and position in the page." + ); +} + +function saveFirstInlineStyleSheet(ui) { + return new Promise(resolve => { + const editor = ui.editors[0]; + const destFile = FileUtils.getFile("ProfD", [SAVE_PATH]); + + editor.saveToFile(destFile, function (file) { + ok(file, "File was correctly saved."); + resolve(); + }); + }); +} + +function testFriendlyNamesAfterSave(ui) { + const firstEditor = ui.editors[0]; + const secondEditor = ui.editors[1]; + + // The friendly name of first sheet should've been remembered, the second + // should not be the same (bug 969900). + is( + firstEditor.friendlyName, + SAVE_PATH, + "Friendly name is correct for the saved inline style sheet." + ); + isnot( + secondEditor.friendlyName, + SAVE_PATH, + "Friendly name for the second inline sheet isn't the same as the first." + ); + + return Promise.resolve(null); +} + +function testFriendlyNamesAfterNavigation(ui) { + const firstEditor = ui.editors[0]; + const secondEditor = ui.editors[1]; + + // Inline style sheets shouldn't have the name of previously saved file as the + // page is different. + isnot( + firstEditor.friendlyName, + SAVE_PATH, + "The first editor doesn't have the save path as a friendly name." + ); + isnot( + secondEditor.friendlyName, + SAVE_PATH, + "The second editor doesn't have the save path as a friendly name." + ); + + return Promise.resolve(null); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_loading.js b/devtools/client/styleeditor/test/browser_styleeditor_loading.js new file mode 100644 index 0000000000..40d70cf924 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_loading.js @@ -0,0 +1,36 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that style editor loads correctly. + +const TESTCASE_URI = TEST_BASE_HTTPS + "longload.html"; + +add_task(async function () { + // launch Style Editor right when the tab is created (before load) + // this checks that the Style Editor still launches correctly when it is + // opened *while* the page is still loading. The Style Editor should not + // signal that it is loaded until the accompanying content page is loaded. + const tabAdded = addTab(TESTCASE_URI); + const tab = gBrowser.selectedTab; + const styleEditorLoaded = gDevTools.showToolboxForTab(tab, { + toolId: "styleeditor", + }); + + await Promise.all([tabAdded, styleEditorLoaded]); + + const toolbox = await gDevTools.getToolboxForTab(tab); + const panel = toolbox.getPanel("styleeditor"); + const { panelWindow } = panel; + + ok( + !getRootElement(panel).classList.contains("loading"), + "style editor root element does not have 'loading' class name anymore" + ); + + let button = panelWindow.document.querySelector(".style-editor-newButton"); + ok(!button.hasAttribute("disabled"), "new style sheet button is enabled"); + + button = panelWindow.document.querySelector(".style-editor-importButton"); + ok(!button.hasAttribute("disabled"), "import button is enabled"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_loading_with_containers.js b/devtools/client/styleeditor/test/browser_styleeditor_loading_with_containers.js new file mode 100644 index 0000000000..ecf788e412 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_loading_with_containers.js @@ -0,0 +1,70 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test that the stylesheets can be loaded correctly with containers +// (bug 1282660). + +const TESTCASE_URI = TEST_BASE_HTTP + "simple.html"; +const EXPECTED_SHEETS = [ + { + sheetIndex: 0, + name: /^simple.css$/, + rules: 1, + active: true, + }, + { + sheetIndex: 1, + name: /^<.*>$/, + rules: 3, + active: false, + }, +]; + +add_task(async function () { + // Using the personal container. + const userContextId = 1; + const { tab } = await openTabInUserContext(TESTCASE_URI, userContextId); + const { ui } = await openStyleEditor(tab); + + is(ui.editors.length, 2, "The UI contains two style sheets."); + checkSheet(ui.editors[0], EXPECTED_SHEETS[0]); + checkSheet(ui.editors[1], EXPECTED_SHEETS[1]); +}); + +async function openTabInUserContext(uri, userContextId) { + // Open the tab in the correct userContextId. + const tab = BrowserTestUtils.addTab(gBrowser, uri, { userContextId }); + + // Select tab and make sure its browser is focused. + gBrowser.selectedTab = tab; + tab.ownerDocument.defaultView.focus(); + + const browser = gBrowser.getBrowserForTab(tab); + await BrowserTestUtils.browserLoaded(browser); + return { tab, browser }; +} + +function checkSheet(editor, expected) { + is( + editor.styleSheet.styleSheetIndex, + expected.sheetIndex, + "Style sheet has correct index." + ); + + const summary = editor.summary; + const name = summary + .querySelector(".stylesheet-name > label") + .getAttribute("value"); + ok(expected.name.test(name), "The name '" + name + "' is correct."); + + const ruleCount = summary.querySelector(".stylesheet-rule-count").textContent; + is(parseInt(ruleCount, 10), expected.rules, "the rule count is correct"); + + is( + summary.classList.contains("splitview-active"), + expected.active, + "The active status for this sheet is correct." + ); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_links.js b/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_links.js new file mode 100644 index 0000000000..1fb9a13195 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_links.js @@ -0,0 +1,158 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* Tests responsive mode links for + * @media sidebar width and height related conditions */ + +loader.lazyRequireGetter( + this, + "ResponsiveUIManager", + "resource://devtools/client/responsive/manager.js" +); + +const TESTCASE_URI = TEST_BASE_HTTPS + "media-rules.html"; +const responsiveModeToggleClass = ".media-responsive-mode-toggle"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + const editor = ui.editors[1]; + await openEditor(editor); + + const tab = gBrowser.selectedTab; + testNumberOfLinks(editor); + await testMediaLink(editor, tab, ui, 2, "width", 550); + await testMediaLink(editor, tab, ui, 3, "height", 300); + + const onMediaChange = waitForManyEvents(ui, 1000); + await closeRDM(tab); + + info("Wait for at-rules-list-changed events to settle on StyleEditorUI"); + await onMediaChange; + doFinalChecks(editor); +}); + +function testNumberOfLinks(editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + const conditions = sidebar.querySelectorAll(".at-rule-condition"); + + info("Testing if media rules have the appropriate number of links"); + ok( + !conditions[0].querySelector(responsiveModeToggleClass), + "There should be no links in the first media rule." + ); + ok( + !conditions[1].querySelector(responsiveModeToggleClass), + "There should be no links in the second media rule." + ); + ok( + conditions[2].querySelector(responsiveModeToggleClass), + "There should be 1 responsive mode link in the media rule" + ); + is( + conditions[3].querySelectorAll(responsiveModeToggleClass).length, + 2, + "There should be 2 responsive mode links in the media rule" + ); +} + +async function testMediaLink(editor, tab, ui, itemIndex, type, value) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + let conditions = sidebar.querySelectorAll(".at-rule-condition"); + + const onMediaChange = once(ui, "at-rules-list-changed"); + const onRDMOpened = once(ui, "responsive-mode-opened"); + + info("Launching responsive mode"); + conditions[itemIndex].querySelector(responsiveModeToggleClass).click(); + await onRDMOpened; + const rdmUI = ResponsiveUIManager.getResponsiveUIForTab(tab); + await waitForResizeTo(rdmUI, type, value); + rdmUI.transitionsEnabled = false; + + info("Wait for RDM ui to be fully loaded"); + await waitForRDMLoaded(rdmUI); + + info("Waiting for the @media list to update"); + await onMediaChange; + + // Ensure that the content has reflowed, which will ensure that all the + // element classes are reported correctly. + await promiseContentReflow(rdmUI); + + ok( + ResponsiveUIManager.isActiveForTab(tab), + "Responsive mode should be active." + ); + conditions = sidebar.querySelectorAll(".at-rule-condition"); + ok( + !conditions[itemIndex].classList.contains("media-condition-unmatched"), + "media rule should now be matched after responsive mode is active" + ); + + const dimension = (await getSizing(rdmUI))[type]; + is(dimension, value, `${type} should be properly set.`); +} + +function doFinalChecks(editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + let conditions = sidebar.querySelectorAll(".at-rule-condition"); + conditions = sidebar.querySelectorAll(".at-rule-condition"); + ok( + conditions[2].classList.contains("media-condition-unmatched"), + "The width condition should now be unmatched" + ); + ok( + conditions[3].classList.contains("media-condition-unmatched"), + "The height condition should now be unmatched" + ); +} + +/* Helpers */ +function waitForResizeTo(rdmUI, type, value) { + return new Promise(resolve => { + const onResize = data => { + if (data[type] != value) { + return; + } + rdmUI.off("content-resize", onResize); + info(`Got content-resize to a ${type} of ${value}`); + resolve(); + }; + info(`Waiting for content-resize to a ${type} of ${value}`); + rdmUI.on("content-resize", onResize); + }); +} + +function promiseContentReflow(ui) { + return SpecialPowers.spawn(ui.getViewportBrowser(), [], async function () { + return new Promise(resolve => { + content.window.requestAnimationFrame(() => { + content.window.requestAnimationFrame(resolve); + }); + }); + }); +} + +async function getSizing(rdmUI) { + const browser = rdmUI.getViewportBrowser(); + const sizing = await SpecialPowers.spawn(browser, [], async function () { + return { + width: content.innerWidth, + height: content.innerHeight, + }; + }); + return sizing; +} + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_sourcemaps.js b/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_sourcemaps.js new file mode 100644 index 0000000000..5086058402 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_media_sidebar_sourcemaps.js @@ -0,0 +1,62 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// https rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTPS + "media-rules-sourcemaps.html"; +const MAP_PREF = "devtools.source-map.client-service.enabled"; + +const LABELS = [ + "screen and (max-width: 320px)", + "screen and (min-width: 1200px)", +]; +const LINE_NOS = [5, 8]; + +waitForExplicitFinish(); + +add_task(async function () { + Services.prefs.setBoolPref(MAP_PREF, true); + + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 1, "correct number of editors"); + + // Test editor with @media rules + const mediaEditor = ui.editors[0]; + await openEditor(mediaEditor); + testAtRulesEditor(mediaEditor); + + Services.prefs.clearUserPref(MAP_PREF); +}); + +function testAtRulesEditor(editor) { + const sidebar = editor.details.querySelector(".stylesheet-sidebar"); + is(sidebar.hidden, false, "sidebar is showing on editor with @media"); + + const entries = [...sidebar.querySelectorAll(".at-rule-label")]; + is(entries.length, 2, "two @media rules displayed in sidebar"); + + testRule(entries[0], LABELS[0], LINE_NOS[0]); + testRule(entries[1], LABELS[1], LINE_NOS[1]); +} + +function testRule(rule, text, lineno) { + const cond = rule.querySelector(".at-rule-condition"); + is(cond.textContent, text, "media label is correct for " + text); + + const line = rule.querySelector(".at-rule-line"); + is(line.textContent, ":" + lineno, "correct line number shown"); +} + +/* Helpers */ + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_missing_stylesheet.js b/devtools/client/styleeditor/test/browser_styleeditor_missing_stylesheet.js new file mode 100644 index 0000000000..97e6b78b49 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_missing_stylesheet.js @@ -0,0 +1,37 @@ +"use strict"; +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +// Checks that the style editor manages to finalize its stylesheet loading phase +// even if one stylesheet is missing, and that an error message is displayed. + +const TESTCASE_URI = TEST_BASE + "missing.html"; + +add_task(async function () { + const { ui, toolbox, panel } = await openStyleEditorForURL(TESTCASE_URI); + + // Note that we're not testing for a specific number of stylesheet editors + // below because the test-page is loaded with chrome:// URL and, right now, + // that means UA stylesheets are shown. So we avoid hardcoding the number of + // stylesheets here. + await waitUntil(() => ui.editors.length); + ok(true, "The UI contains style sheets."); + + const rootEl = panel.panelWindow.document.getElementById( + "style-editor-chrome" + ); + ok(!rootEl.classList.contains("loading"), "The loading indicator is hidden"); + + const notifBox = toolbox.getNotificationBox(); + await waitUntil(() => notifBox.getCurrentNotification()); + const notif = notifBox.getCurrentNotification(); + ok(notif, "The notification box contains a message"); + ok( + notif.label.includes("Style sheet could not be loaded"), + "The error message is the correct one" + ); + ok( + notif.label.includes("missing-stylesheet.css"), + "The error message contains the missing stylesheet's URL" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_navigate.js b/devtools/client/styleeditor/test/browser_styleeditor_navigate.js new file mode 100644 index 0000000000..68f76915e4 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_navigate.js @@ -0,0 +1,31 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that selected sheet and cursor position is reset during navigation. + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; +const NEW_URI = TEST_BASE_HTTPS + "media.html"; + +const LINE_NO = 5; +const COL_NO = 3; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "Two sheets present after load."); + + info("Selecting the second editor"); + await ui.selectStyleSheet(ui.editors[1].styleSheet, LINE_NO, COL_NO); + + await navigateToAndWaitForStyleSheets(NEW_URI, ui, 2); + + info("Waiting for source editor to be ready."); + await ui.editors[0].getSourceEditor(); + + is(ui.selectedEditor, ui.editors[0], "first editor is selected"); + + const { line, ch } = ui.selectedEditor.sourceEditor.getCursor(); + is(line, 0, "first line is selected"); + is(ch, 0, "first column is selected"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_new.js b/devtools/client/styleeditor/test/browser_styleeditor_new.js new file mode 100644 index 0000000000..27df58235c --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_new.js @@ -0,0 +1,97 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that new sheets can be added and edited. + +const TESTCASE_URI = TEST_BASE_HTTP + "simple.html"; + +const TESTCASE_CSS_SOURCE = "body{background-color:red;"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + + const editor = await createNewStyleSheet(ui, panel.panelWindow); + await testInitialState(editor); + + const originalHref = editor.styleSheet.href; + const waitForPropertyChange = onPropertyChange(editor); + + await typeInEditor(editor, panel.panelWindow); + + await waitForPropertyChange; + + testUpdated(editor, originalHref); +}); + +function onPropertyChange(editor) { + return new Promise(resolve => { + editor.on("property-change", function onProp(property) { + // wait for text to be entered fully + const text = editor.sourceEditor.getText(); + if (property == "ruleCount" && text == TESTCASE_CSS_SOURCE + "}") { + editor.off("property-change", onProp); + resolve(); + } + }); + }); +} + +async function testInitialState(editor) { + info("Testing the initial state of the new editor"); + + let summary = editor.summary; + + ok(editor.sourceLoaded, "new editor is loaded when attached"); + ok(editor.isNew, "new editor has isNew flag"); + + if (!editor.sourceEditor.hasFocus()) { + info("Waiting for stylesheet editor to gain focus"); + await editor.sourceEditor.once("focus"); + } + ok(editor.sourceEditor.hasFocus(), "new editor has focus"); + + summary = editor.summary; + const ruleCount = summary.querySelector(".stylesheet-rule-count").textContent; + is(parseInt(ruleCount, 10), 0, "new editor initially shows 0 rules"); + + const color = await getComputedStyleProperty({ + selector: "body", + name: "background-color", + }); + is( + color, + "rgb(255, 255, 255)", + "content's background color is initially white" + ); +} + +function typeInEditor(editor, panelWindow) { + return new Promise(resolve => { + waitForFocus(function () { + for (const c of TESTCASE_CSS_SOURCE) { + EventUtils.synthesizeKey(c, {}, panelWindow); + } + ok(editor.unsaved, "new editor has unsaved flag"); + + resolve(); + }, panelWindow); + }); +} + +function testUpdated(editor, originalHref) { + info("Testing the state of the new editor after editing it"); + + is( + editor.sourceEditor.getText(), + TESTCASE_CSS_SOURCE + "}", + "rule bracket has been auto-closed" + ); + + const ruleCount = editor.summary.querySelector( + ".stylesheet-rule-count" + ).textContent; + is(parseInt(ruleCount, 10), 1, "new editor shows 1 rule after modification"); + + is(editor.styleSheet.href, originalHref, "style sheet href did not change"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_nostyle.js b/devtools/client/styleeditor/test/browser_styleeditor_nostyle.js new file mode 100644 index 0000000000..c8a2134135 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_nostyle.js @@ -0,0 +1,56 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that 'no styles' indicator is shown if a page doesn't contain any style +// sheets. + +const TESTCASE_URI = TEST_BASE_HTTP + "nostyle.html"; + +add_task(async function () { + // Make enough room for the "append style sheet" link to not wrap, + // as it messes up with EvenEventUtils.synthesizeMouse + await pushPref("devtools.styleeditor.navSidebarWidth", 500); + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + const { panelWindow } = panel; + + ok( + !getRootElement(panel).classList.contains("loading"), + "style editor root element does not have 'loading' class name anymore" + ); + + const newButton = panelWindow.document.querySelector( + "toolbarbutton.style-editor-newButton" + ); + ok(!newButton.hasAttribute("disabled"), "new style sheet button is enabled"); + + const importButton = panelWindow.document.querySelector( + ".style-editor-importButton" + ); + ok(!importButton.hasAttribute("disabled"), "import button is enabled"); + + const emptyPlaceHolderEl = + getRootElement(panel).querySelector(".empty.placeholder"); + isnot( + emptyPlaceHolderEl.ownerGlobal.getComputedStyle(emptyPlaceHolderEl).display, + "none", + "showing 'no style' indicator" + ); + + info( + "Check that clicking on the append new stylesheet link do add a stylesheet" + ); + const onEditorAdded = ui.once("editor-added"); + const newLink = emptyPlaceHolderEl.querySelector("a.style-editor-newButton"); + + // Use synthesizeMouse to also check that the element is visible + EventUtils.synthesizeMouseAtCenter(newLink, {}, newLink.ownerGlobal); + await onEditorAdded; + + ok(true, "A stylesheet was added"); + is( + emptyPlaceHolderEl.ownerGlobal.getComputedStyle(emptyPlaceHolderEl).display, + "none", + "The empty placeholder element is now hidden" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_opentab.js b/devtools/client/styleeditor/test/browser_styleeditor_opentab.js new file mode 100644 index 0000000000..55494f4166 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_opentab.js @@ -0,0 +1,133 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// A test to check the 'Open Link in new tab' functionality in the +// context menu item for stylesheets (bug 992947). +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + + const openLinkNewTabItem = panel.panelWindow.document.getElementById( + "context-openlinknewtab" + ); + + let menu = await rightClickStyleSheet(panel, ui.editors[0]); + is( + openLinkNewTabItem.getAttribute("disabled"), + "false", + "The menu item is not disabled" + ); + ok(!openLinkNewTabItem.hidden, "The menu item is not hidden"); + + const url = TEST_BASE_HTTPS + "simple.css"; + + const browserWindow = Services.wm.getMostRecentWindow( + gDevTools.chromeWindowType + ); + const originalOpenWebLinkIn = browserWindow.openWebLinkIn; + const tabOpenedDefer = new Promise(resolve => { + browserWindow.openWebLinkIn = newUrl => { + // Reset the actual openWebLinkIn function before proceeding. + browserWindow.openWebLinkIn = originalOpenWebLinkIn; + + is(newUrl, url, "The correct tab has been opened"); + resolve(); + }; + }); + + const hidden = onPopupHide(menu); + + menu.activateItem(openLinkNewTabItem); + + info(`Waiting for a tab to open - ${url}`); + await tabOpenedDefer; + + await hidden; + + menu = await rightClickInlineStyleSheet(panel, ui.editors[1]); + is( + openLinkNewTabItem.getAttribute("disabled"), + "true", + "The menu item is disabled" + ); + ok(!openLinkNewTabItem.hidden, "The menu item should not be hidden"); + menu.hidePopup(); + + menu = await rightClickNoStyleSheet(panel); + ok(openLinkNewTabItem.hidden, "The menu item should be hidden"); + menu.hidePopup(); +}); + +function onPopupShow(contextMenu) { + return new Promise(resolve => { + contextMenu.addEventListener( + "popupshown", + function () { + resolve(); + }, + { once: true } + ); + }); +} + +function onPopupHide(contextMenu) { + return new Promise(resolve => { + contextMenu.addEventListener( + "popuphidden", + function () { + resolve(); + }, + { once: true } + ); + }); +} + +function rightClickStyleSheet(panel, editor) { + const contextMenu = getContextMenuElement(panel); + return new Promise(resolve => { + onPopupShow(contextMenu).then(() => { + resolve(contextMenu); + }); + + EventUtils.synthesizeMouseAtCenter( + editor.summary.querySelector(".stylesheet-name"), + { button: 2, type: "contextmenu" }, + panel.panelWindow + ); + }); +} + +function rightClickInlineStyleSheet(panel, editor) { + const contextMenu = getContextMenuElement(panel); + return new Promise(resolve => { + onPopupShow(contextMenu).then(() => { + resolve(contextMenu); + }); + + EventUtils.synthesizeMouseAtCenter( + editor.summary.querySelector(".stylesheet-name"), + { button: 2, type: "contextmenu" }, + panel.panelWindow + ); + }); +} + +function rightClickNoStyleSheet(panel) { + const contextMenu = getContextMenuElement(panel); + return new Promise(resolve => { + onPopupShow(contextMenu).then(() => { + resolve(contextMenu); + }); + + EventUtils.synthesizeMouseAtCenter( + panel.panelWindow.document.querySelector( + "#splitview-tpl-summary-stylesheet" + ), + { button: 2, type: "contextmenu" }, + panel.panelWindow + ); + }); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_pretty.js b/devtools/client/styleeditor/test/browser_styleeditor_pretty.js new file mode 100644 index 0000000000..102daf9d97 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_pretty.js @@ -0,0 +1,82 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that minified sheets are automatically prettified but other are left +// untouched. + +const TESTCASE_URI = TEST_BASE_HTTP + "minified.html"; + +/* + body { + background:white; + } + div { + font-size:4em; + color:red + } + span { + color:green; + } +*/ +const PRETTIFIED_SOURCE = + "" + + "body {\r?\n" + + "\tbackground:white;\r?\n" + + "}\r?\n" + + "div {\r?\n" + + "\tfont-size:4em;\r?\n" + + "\tcolor:red\r?\n" + + "}\r?\n" + + "span {\r?\n" + + "\tcolor:green;\r?\n" + + "}\r?\n"; + +/* + body { background: red; } + div { + font-size: 5em; + color: red + } +*/ +const ORIGINAL_SOURCE = + "" + + "body { background: red; }\r?\n" + + "div {\r?\n" + + "font-size: 5em;\r?\n" + + "color: red\r?\n" + + "}"; + +const EXPAND_TAB = "devtools.editor.expandtab"; + +add_task(async function () { + const oldExpandTabPref = SpecialPowers.getBoolPref(EXPAND_TAB); + // The 'EXPAND_TAB' preference has to be set to false because + // the constant 'PRETTIFIED_SOURCE' uses tabs for indentation. + SpecialPowers.setBoolPref(EXPAND_TAB, false); + + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + is(ui.editors.length, 2, "Two sheets present."); + + info("Testing minified style sheet."); + let editor = await ui.editors[0].getSourceEditor(); + + const prettifiedSourceRE = new RegExp(PRETTIFIED_SOURCE); + ok( + prettifiedSourceRE.test(editor.sourceEditor.getText()), + "minified source has been prettified automatically" + ); + + info("Selecting second, non-minified style sheet."); + await ui.selectStyleSheet(ui.editors[1].styleSheet); + + editor = ui.editors[1]; + + const originalSourceRE = new RegExp(ORIGINAL_SOURCE); + ok( + originalSourceRE.test(editor.sourceEditor.getText()), + "non-minified source has been left untouched" + ); + + SpecialPowers.setBoolPref(EXPAND_TAB, oldExpandTabPref); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js b/devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js new file mode 100644 index 0000000000..e372f54ba2 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js @@ -0,0 +1,76 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +// This test makes sure that the style editor does not store any +// content CSS files in the permanent cache when opened from a private window tab. + +const TEST_URL = `http://${TEST_HOST}/browser/devtools/client/styleeditor/test/test_private.html`; + +add_task(async function () { + info("Opening a new private window"); + const win = await BrowserTestUtils.openNewBrowserWindow({ private: true }); + + info("Clearing the browser cache"); + Services.cache2.clear(); + + const { toolbox, ui } = await openStyleEditorForURL(TEST_URL, win); + + is(ui.editors.length, 1, "The style editor contains one sheet."); + const editor = ui.editors[0]; + is( + editor.friendlyName, + "test_private.css", + "The style editor contains the expected stylesheet" + ); + + await editor.getSourceEditor(); + + await checkDiskCacheFor(editor.friendlyName); + + await toolbox.destroy(); + + const onUnload = new Promise(done => { + win.addEventListener("unload", function listener(event) { + if (event.target == win.document) { + win.removeEventListener("unload", listener); + done(); + } + }); + }); + win.close(); + await onUnload; +}); + +function checkDiskCacheFor(fileName) { + let foundPrivateData = false; + + return new Promise(resolve => { + Visitor.prototype = { + onCacheStorageInfo(num) { + info("disk storage contains " + num + " entries"); + }, + onCacheEntryInfo(uri) { + const urispec = uri.asciiSpec; + info(urispec); + foundPrivateData = foundPrivateData || urispec.includes(fileName); + }, + onCacheEntryVisitCompleted() { + is(foundPrivateData, false, "web content present in disk cache"); + resolve(); + }, + }; + function Visitor() {} + + const storage = Services.cache2.diskCacheStorage( + Services.loadContextInfo.default + ); + storage.asyncVisitStorage( + new Visitor(), + /* Do walk entries */ + true + ); + }); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_reload.js b/devtools/client/styleeditor/test/browser_styleeditor_reload.js new file mode 100644 index 0000000000..f568b3f40f --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_reload.js @@ -0,0 +1,42 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that selected sheet and cursor position persists during reload. + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +const LINE_NO = 5; +const COL_NO = 3; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "Two sheets present after load."); + + info("Selecting the second editor"); + await ui.selectStyleSheet(ui.editors[1].styleSheet, LINE_NO, COL_NO); + const selectedStyleSheetIndex = ui.editors[1].styleSheet.styleSheetIndex; + + await reloadPageAndWaitForStyleSheets(ui, 2); + + info("Waiting for source editor to be ready."); + const newEditor = findEditor(ui, selectedStyleSheetIndex); + await newEditor.getSourceEditor(); + + is( + ui.selectedEditor, + newEditor, + "Editor of stylesheet that has styleSheetIndex we selected is selected after reload" + ); + + const { line, ch } = ui.selectedEditor.sourceEditor.getCursor(); + is(line, LINE_NO, "correct line selected"); + is(ch, COL_NO, "correct column selected"); +}); + +function findEditor(ui, styleSheetIndex) { + return ui.editors.find( + editor => editor.styleSheet.styleSheetIndex === styleSheetIndex + ); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_resize_performance.js b/devtools/client/styleeditor/test/browser_styleeditor_resize_performance.js new file mode 100644 index 0000000000..cd978fd624 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_resize_performance.js @@ -0,0 +1,62 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/** + * This is a performance test designed to check we are not redrawing the UI too many times + * after resizing the window, when the styleeditor displays mediaqueries which are source + * mapped. + * See Bug 1453044 for more details. + */ + +const TESTCASE_URI = TEST_BASE_HTTP + "many-media-rules-sourcemaps/index.html"; + +// Maximum delay allowed between two at-rules-list-changed events. +const EVENTS_DELAY = 2000; + +// The window resize will still trigger several resize events which will lead to several +// UI updates. Arbitrary maximum number of events allowed to be fired for a single resize. +// This used to be > 100 events for this test case. +const MAX_EVENTS = 10; + +add_task(async function () { + const { toolbox, ui } = await openStyleEditorForURL(TESTCASE_URI); + + const win = toolbox.win.parent; + const originalWidth = win.outerWidth; + const originalHeight = win.outerHeight; + + // Ensure the window is above 500px wide for @media (min-width: 500px) + if (originalWidth < 500) { + info("Window is too small for the test, resize it to > 800px width"); + const onMediaListChanged = waitForManyEvents(ui, EVENTS_DELAY); + await resizeWindow(800, ui, win); + info("Wait for at-rules-list-changed events to settle"); + await onMediaListChanged; + } + + info( + "Resize the window to stop matching media queries, and trigger the UI updates" + ); + const onMediaListChanged = waitForManyEvents(ui, win, EVENTS_DELAY); + await resizeWindow(400, ui, win); + const eventsCount = await onMediaListChanged; + + ok( + eventsCount < MAX_EVENTS, + `Too many events fired (expected less than ${MAX_EVENTS}, got ${eventsCount})` + ); + + win.resizeTo(originalWidth, originalHeight); +}); + +/** + * Resize the window to the provided width. + */ +async function resizeWindow(width, ui, win) { + const onResize = once(win, "resize"); + win.resizeTo(width, win.outerHeight); + info("Wait for window resize event"); + await onResize; +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_scroll.js b/devtools/client/styleeditor/test/browser_styleeditor_scroll.js new file mode 100644 index 0000000000..d9ae030068 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_scroll.js @@ -0,0 +1,96 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that editor scrolls to correct line if it's selected with +// * selectStyleSheet (specified line) +// * click on the sidebar item (line before the editor was unselected) +// See bug 1148086. + +const SIMPLE = TEST_BASE_HTTP + "simple.css"; +const LONG = TEST_BASE_HTTP + "doc_long.css"; +const DOCUMENT_WITH_LONG_SHEET = + "data:text/html;charset=UTF-8," + + encodeURIComponent( + [ + "", + "", + " ", + " Editor scroll test page", + ' ', + ' ', + " ", + " Editor scroll test page", + "", + ].join("\n") + ); +const LINE_TO_SELECT = 201; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(DOCUMENT_WITH_LONG_SHEET); + + is(ui.editors.length, 2, "Two editors present."); + + const simpleEditor = ui.editors[0]; + const longEditor = ui.editors[1]; + + info(`Selecting doc_long.css and scrolling to line ${LINE_TO_SELECT}`); + + // We need to wait for editor-selected if we want to check the scroll + // position as scrolling occurs after selectStyleSheet resolves but before the + // event is emitted. + let selectEventPromise = waitForEditorToBeSelected(longEditor, ui); + await ui.selectStyleSheet(longEditor.styleSheet, LINE_TO_SELECT); + await selectEventPromise; + + info("Checking that the correct line is visible after initial load"); + + const { from, to } = longEditor.sourceEditor.getViewport(); + info(`Lines ${from}-${to} are visible (expected ${LINE_TO_SELECT}).`); + + ok(from <= LINE_TO_SELECT, "The editor scrolled too much."); + ok(to >= LINE_TO_SELECT, "The editor scrolled too little."); + + const initialScrollTop = longEditor.sourceEditor.getScrollInfo().top; + info(`Storing scrollTop = ${initialScrollTop} for later comparison.`); + + info("Selecting the first editor (simple.css)"); + await ui.selectStyleSheet(simpleEditor.styleSheet); + + info("Selecting doc_long.css again."); + selectEventPromise = waitForEditorToBeSelected(longEditor, ui); + + // Can't use ui.selectStyleSheet here as it will scroll the editor back to top + // and we want to check that the previous scroll position is restored. + const summary = await ui.getEditorSummary(longEditor); + summary.click(); + + info("Waiting for doc_long.css to be selected."); + await selectEventPromise; + + const scrollTop = longEditor.sourceEditor.getScrollInfo().top; + is( + scrollTop, + initialScrollTop, + "Scroll top was restored after the sheet was selected again." + ); +}); + +/** + * A helper that waits "editor-selected" event for given editor. + * + * @param {StyleSheetEditor} editor + * The editor to wait for. + * @param {StyleEditorUI} ui + * The StyleEditorUI the editor belongs to. + */ +var waitForEditorToBeSelected = async function (editor, ui) { + info(`Waiting for ${editor.friendlyName} to be selected.`); + let selected = await ui.once("editor-selected"); + while (selected != editor) { + info(`Ignored editor-selected for editor ${editor.friendlyName}.`); + selected = await ui.once("editor-selected"); + } + + info(`Got editor-selected for ${editor.friendlyName}.`); +}; diff --git a/devtools/client/styleeditor/test/browser_styleeditor_selectstylesheet.js b/devtools/client/styleeditor/test/browser_styleeditor_selectstylesheet.js new file mode 100644 index 0000000000..b455ec3c7f --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_selectstylesheet.js @@ -0,0 +1,25 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that StyleEditorUI.selectStyleSheet selects the correct sheet, line and +// column. + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +const LINE_NO = 5; +const COL_NO = 0; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + const editor = ui.editors[1]; + + info("Selecting style sheet #1."); + await ui.selectStyleSheet(editor.styleSheet, LINE_NO); + + is(ui.selectedEditor, ui.editors[1], "Second editor is selected."); + const { line, ch } = ui.selectedEditor.sourceEditor.getCursor(); + + is(line, LINE_NO, "correct line selected"); + is(ch, COL_NO, "correct column selected"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sidebars.js b/devtools/client/styleeditor/test/browser_styleeditor_sidebars.js new file mode 100644 index 0000000000..d0cdb4acfe --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sidebars.js @@ -0,0 +1,67 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TESTCASE_URI = TEST_BASE_HTTPS + "media-rules.html"; + +const PREF_SHOW_AT_RULES_SIDEBAR = "devtools.styleeditor.showAtRulesSidebar"; +const PREF_SIDEBAR_WIDTH = "devtools.styleeditor.atRulesSidebarWidth"; +const PREF_NAV_WIDTH = "devtools.styleeditor.navSidebarWidth"; + +// Initial widths for the navigation and media sidebars, which will be set via +// the corresponding preferences. +// The widths should remain between the current min-width and max-width for the +// styleeditor sidebars (currently 100px and 400px). +const NAV_WIDTH = 210; +const MEDIA_WIDTH = 250; + +// Test that sidebar in the styleeditor can be resized. +add_task(async function () { + await pushPref(PREF_SHOW_AT_RULES_SIDEBAR, true); + await pushPref(PREF_NAV_WIDTH, NAV_WIDTH); + await pushPref(PREF_SIDEBAR_WIDTH, MEDIA_WIDTH); + + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + const doc = panel.panelWindow.document; + + info("Open editor for inline sheet with @media rules to have both splitters"); + const inlineMediaEditor = ui.editors[3]; + inlineMediaEditor.summary.querySelector(".stylesheet-name").click(); + await inlineMediaEditor.getSourceEditor(); + + info("Check the initial widths of side panels match the preferences values"); + const navSidebar = doc.querySelector(".splitview-controller"); + is(navSidebar.clientWidth, NAV_WIDTH); + + const mediaSidebar = doc.querySelector( + ".splitview-active .stylesheet-sidebar" + ); + is(mediaSidebar.clientWidth, MEDIA_WIDTH); + + info( + "Resize the navigation splitter and check the navigation sidebar is updated" + ); + const navSplitter = doc.querySelector(".devtools-side-splitter"); + dragElement(navSplitter, { startX: 1, startY: 10, deltaX: 50, deltaY: 0 }); + is(navSidebar.clientWidth, NAV_WIDTH + 50); + + info("Resize the media splitter and check the media sidebar is updated"); + const mediaSplitter = doc.querySelector( + ".splitview-active .devtools-side-splitter" + ); + dragElement(mediaSplitter, { startX: 1, startY: 10, deltaX: -50, deltaY: 0 }); + is(mediaSidebar.clientWidth, MEDIA_WIDTH + 50); +}); + +/* Helpers */ + +function dragElement(el, { startX, startY, deltaX, deltaY }) { + const win = el.ownerGlobal; + const endX = startX + deltaX; + const endY = startY + deltaY; + + EventUtils.synthesizeMouse(el, startX, startY, { type: "mousedown" }, win); + EventUtils.synthesizeMouse(el, endX, endY, { type: "mousemove" }, win); + EventUtils.synthesizeMouse(el, endX, endY, { type: "mouseup" }, win); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_chrome.js b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_chrome.js new file mode 100644 index 0000000000..997171e30d --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_chrome.js @@ -0,0 +1,47 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +const TEST_URI = URL_ROOT_SSL + "doc_sourcemap_chrome.html"; +const CHROME_TEST_URI = CHROME_URL_ROOT + "doc_sourcemap_chrome.html"; +const GENERATED_NAME = "sourcemaps_chrome.css"; +const ORIGINAL_NAME = "sourcemaps.scss"; + +/** + * Test that a sourcemap served by a chrome URL for a http document will not be resolved. + */ +add_task(async function () { + const { ui } = await openStyleEditorForURL(TEST_URI); + ok( + findStylesheetByName(ui, GENERATED_NAME), + "Sourcemap not resolved: generated source is listed" + ); + ok( + !findStylesheetByName(ui, ORIGINAL_NAME), + "Sourcemap not resolved: original source is not listed" + ); +}); + +/** + * Test that a sourcemap served by a chrome URL for a chrome document is resolved. + */ +add_task(async function () { + const { ui } = await openStyleEditorForURL(CHROME_TEST_URI); + ok( + findStylesheetByName(ui, ORIGINAL_NAME), + "Sourcemap resolved: original source is listed" + ); + ok( + !findStylesheetByName(ui, GENERATED_NAME), + "Sourcemap resolved: generated source is not listed" + ); +}); + +function findStylesheetByName(ui, name) { + return ui.editors.some( + editor => + editor.summary + .querySelector(".stylesheet-name > label") + .getAttribute("value") === name + ); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_large.js b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_large.js new file mode 100644 index 0000000000..b03cef01c1 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_large.js @@ -0,0 +1,34 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Covers the case from Bug 1128747, where loading a sourcemapped +// file prevents the correct editor from being selected on load, +// and causes a second iframe to be appended when the user clicks +// editor in the list. + +const TESTCASE_URI = TEST_BASE_HTTPS + "sourcemaps-large.html"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + await openEditor(ui.editors[0]); + const iframes = ui.selectedEditor.details.querySelectorAll("iframe"); + + is(iframes.length, 1, "There is only one editor iframe"); + ok( + ui.selectedEditor.summary.classList.contains("splitview-active"), + "The editor is selected" + ); +}); + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js new file mode 100644 index 0000000000..472e34b7fc --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js @@ -0,0 +1,155 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +"use strict"; + +const TESTCASE_URI_HTML = TEST_BASE_HTTP + "sourcemaps-watching.html"; +const TESTCASE_URI_CSS = TEST_BASE_HTTP + "sourcemap-css/sourcemaps.css"; +const TESTCASE_URI_REG_CSS = TEST_BASE_HTTP + "simple.css"; +const TESTCASE_URI_SCSS = TEST_BASE_HTTP + "sourcemap-sass/sourcemaps.scss"; +const TESTCASE_URI_MAP = TEST_BASE_HTTP + "sourcemap-css/sourcemaps.css.map"; +const TESTCASE_SCSS_NAME = "sourcemaps.scss"; + +const TRANSITIONS_PREF = "devtools.styleeditor.transitions"; + +const CSS_TEXT = "* { color: blue }"; + +add_task(async function () { + await new Promise(resolve => { + SpecialPowers.pushPrefEnv({ set: [[TRANSITIONS_PREF, false]] }, resolve); + }); + + // copy all our files over so we don't screw them up for other tests + const HTMLFile = await copy(TESTCASE_URI_HTML, ["sourcemaps.html"]); + const CSSFile = await copy(TESTCASE_URI_CSS, [ + "sourcemap-css", + "sourcemaps.css", + ]); + await copy(TESTCASE_URI_SCSS, ["sourcemap-sass", "sourcemaps.scss"]); + await copy(TESTCASE_URI_MAP, ["sourcemap-css", "sourcemaps.css.map"]); + await copy(TESTCASE_URI_REG_CSS, ["simple.css"]); + + const uri = Services.io.newFileURI(HTMLFile); + const testcaseURI = uri.resolve(""); + + const { ui } = await openStyleEditorForURL(testcaseURI); + + let editor = ui.editors[1]; + if (getStylesheetNameFor(editor) != TESTCASE_SCSS_NAME) { + editor = ui.editors[2]; + } + + is(getStylesheetNameFor(editor), TESTCASE_SCSS_NAME, "found scss editor"); + + const link = getLinkFor(editor); + link.click(); + + await editor.getSourceEditor(); + + let color = await getComputedStyleProperty({ + selector: "div", + name: "color", + }); + is(color, "rgb(255, 0, 102)", "div is red before saving file"); + + const styleApplied = editor.once("style-applied"); + + await pauseForTimeChange(); + + // Edit and save Sass in the editor. This will start off a file-watching + // process waiting for the CSS file to change. + await editSCSS(editor); + + // We can't run Sass or another compiler, so we fake it by just + // directly changing the CSS file. + await editCSSFile(CSSFile); + + info("wrote to CSS file, waiting for style-applied event"); + + await styleApplied; + + color = await getComputedStyleProperty({ selector: "div", name: "color" }); + is(color, "rgb(0, 0, 255)", "div is blue after saving file"); + + // Ensure that the editor didn't revert. Bug 1346662. + is(editor.sourceEditor.getText(), CSS_TEXT, "edits remain applied"); +}); + +function editSCSS(editor) { + return new Promise(resolve => { + editor.sourceEditor.setText(CSS_TEXT); + + editor.saveToFile(null, function (file) { + ok(file, "Scss file should be saved"); + resolve(); + }); + }); +} + +function editCSSFile(CSSFile) { + return write(CSS_TEXT, CSSFile); +} + +function pauseForTimeChange() { + return new Promise(resolve => { + // We have to wait for the system time to turn over > 1000 ms so that + // our file's last change time will show a change. This reflects what + // would happen in real life with a user manually saving the file. + setTimeout(resolve, 2000); + }); +} + +/* Helpers */ + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} + +function getStylesheetNameFor(editor) { + return editor.summary + .querySelector(".stylesheet-name > label") + .getAttribute("value"); +} + +function copy(srcChromeURL, destFilePath) { + const destFile = FileUtils.getFile("ProfD", destFilePath); + return write(read(srcChromeURL), destFile); +} + +function read(srcChromeURL) { + const scriptableStream = Cc[ + "@mozilla.org/scriptableinputstream;1" + ].getService(Ci.nsIScriptableInputStream); + + const channel = NetUtil.newChannel({ + uri: srcChromeURL, + loadUsingSystemPrincipal: true, + }); + const input = channel.open(); + scriptableStream.init(input); + + let data = ""; + while (input.available()) { + data = data.concat(scriptableStream.read(input.available())); + } + scriptableStream.close(); + input.close(); + + return data; +} + +function write(data, file) { + return new Promise(resolve => { + const istream = getInputStream(data); + const ostream = FileUtils.openSafeFileOutputStream(file); + + NetUtil.asyncCopy(istream, ostream, function (status) { + if (!Components.isSuccessCode(status)) { + info("Coudln't write to " + file.path); + return; + } + resolve(file); + }); + }); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps.js b/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps.js new file mode 100644 index 0000000000..452988eb68 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps.js @@ -0,0 +1,152 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// https rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTPS + "sourcemaps.html"; +const PREF = "devtools.source-map.client-service.enabled"; + +const contents = { + "sourcemaps.scss": [ + "", + "$paulrougetpink: #f06;", + "", + "div {", + " color: $paulrougetpink;", + "}", + "", + "span {", + " background-color: #EEE;", + "}", + ].join("\n"), + "contained.scss": [ + "$pink: #f06;", + "", + "#header {", + " color: $pink;", + "}", + ].join("\n"), + "sourcemaps.css": [ + "div {", + " color: #ff0066; }", + "", + "span {", + " background-color: #EEE; }", + "", + "/*# sourceMappingURL=sourcemaps.css.map */", + ].join("\n"), + "contained.css": [ + "#header {", + " color: #f06; }", + "", + "/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJma" + + "WxlIjoiIiwic291cmNlcyI6WyJzYXNzL2NvbnRhaW5lZC5zY3NzIl0sIm5hbWVzIjpbXSwi" + + "bWFwcGluZ3MiOiJBQUVBO0VBQ0UsT0FISyIsInNvdXJjZXNDb250ZW50IjpbIiRwaW5rOiA" + + "jZjA2O1xuXG4jaGVhZGVyIHtcbiAgY29sb3I6ICRwaW5rO1xufSJdfQ==*/", + ].join("\n"), + "test-stylus.styl": [ + "paulrougetpink = #f06;", + "", + "div", + " color: paulrougetpink", + "", + "span", + " background-color: #EEE", + "", + ].join("\n"), + "test-stylus.css": [ + "div {", + " color: #f06;", + "}", + "span {", + " background-color: #eee;", + "}", + "/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb" + + "3VyY2VzIjpbInRlc3Qtc3R5bHVzLnN0eWwiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFB" + + "RUE7RUFDRSxPQUFPLEtBQVA7O0FBRUY7RUFDRSxrQkFBa0IsS0FBbEIiLCJmaWxlIjoidGV" + + "zdC1zdHlsdXMuY3NzIiwic291cmNlc0NvbnRlbnQiOlsicGF1bHJvdWdldHBpbmsgPSAjZj" + + "A2O1xuXG5kaXZcbiAgY29sb3I6IHBhdWxyb3VnZXRwaW5rXG5cbnNwYW5cbiAgYmFja2dyb" + + "3VuZC1jb2xvcjogI0VFRVxuIl19 */", + ].join("\n"), +}; + +const cssNames = ["sourcemaps.css", "contained.css", "test-stylus.css"]; +const origNames = ["sourcemaps.scss", "contained.scss", "test-stylus.styl"]; + +waitForExplicitFinish(); + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is( + ui.editors.length, + 4, + "correct number of editors with source maps enabled" + ); + + // Test first plain css editor + testFirstEditor(ui.editors[0]); + + // Test Scss editors + await testEditor(ui.editors[1], origNames); + await testEditor(ui.editors[2], origNames); + await testEditor(ui.editors[3], origNames); + + // Test disabling original sources + await togglePref(ui); + + is(ui.editors.length, 4, "correct number of editors after pref toggled"); + + // Test CSS editors + await testEditor(ui.editors[1], cssNames); + await testEditor(ui.editors[2], cssNames); + await testEditor(ui.editors[3], cssNames); + + Services.prefs.clearUserPref(PREF); +}); + +function testFirstEditor(editor) { + const name = getStylesheetNameFor(editor); + is(name, "simple.css", "First style sheet display name is correct"); +} + +function testEditor(editor, possibleNames) { + const name = getStylesheetNameFor(editor); + ok(possibleNames.includes(name), name + " editor name is correct"); + + return openEditor(editor).then(() => { + const expectedText = contents[name]; + + const text = editor.sourceEditor.getText(); + + is(text, expectedText, name + " editor contains expected text"); + }); +} + +/* Helpers */ + +function togglePref(UI) { + const editorsPromise = UI.once("stylesheets-refreshed"); + const selectedPromise = UI.once("editor-selected"); + + Services.prefs.setBoolPref(PREF, false); + + return Promise.all([editorsPromise, selectedPromise]); +} + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} + +function getStylesheetNameFor(editor) { + return editor.summary + .querySelector(".stylesheet-name > label") + .getAttribute("value"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps_inline.js b/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps_inline.js new file mode 100644 index 0000000000..933a128a74 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemaps_inline.js @@ -0,0 +1,89 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// https rather than chrome to improve coverage +const TESTCASE_URI = TEST_BASE_HTTPS + "sourcemaps-inline.html"; +const PREF = "devtools.source-map.client-service.enabled"; + +const sassContent = `body { + background-color: black; + & > h1 { + color: white; + } +} +`; + +const cssContent = + `body { + background-color: black; +} +body > h1 { + color: white; +} +` + + "/*# sourceMappingURL=data:application/json;base64,ewoidmVyc2lvbiI6IDMsCiJtY" + + "XBwaW5ncyI6ICJBQUFBLElBQUs7RUFDSCxnQkFBZ0IsRUFBRSxLQUFLO0VBQ3ZCLFNBQU87SUFD" + + "TCxLQUFLLEVBQUUsS0FBSyIsCiJzb3VyY2VzIjogWyJ0ZXN0LnNjc3MiXSwKInNvdXJjZXNDb25" + + "0ZW50IjogWyJib2R5IHtcbiAgYmFja2dyb3VuZC1jb2xvcjogYmxhY2s7XG4gICYgPiBoMSB7XG" + + "4gICAgY29sb3I6IHdoaXRlO1xuICB9XG59XG4iXSwKIm5hbWVzIjogW10sCiJmaWxlIjogInRlc" + + "3QuY3NzIgp9Cg== */"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is( + ui.editors.length, + 1, + "correct number of editors with source maps enabled" + ); + + await testEditor(ui.editors[0], "test.scss", sassContent); + + // Test disabling original sources + await togglePref(ui); + + is(ui.editors.length, 1, "correct number of editors after pref toggled"); + + // Test CSS editors + await testEditor(ui.editors[0], "", cssContent); + + Services.prefs.clearUserPref(PREF); +}); + +async function testEditor(editor, expectedName, expectedText) { + const name = getStylesheetNameFor(editor); + is(expectedName, name, name + " editor name is correct"); + + await openEditor(editor); + const text = editor.sourceEditor.getText(); + is(text, expectedText, name + " editor contains expected text"); +} + +/* Helpers */ + +function togglePref(UI) { + const editorsPromise = UI.once("stylesheets-refreshed"); + const selectedPromise = UI.once("editor-selected"); + + Services.prefs.setBoolPref(PREF, false); + + return Promise.all([editorsPromise, selectedPromise]); +} + +function openEditor(editor) { + getLinkFor(editor).click(); + + return editor.getSourceEditor(); +} + +function getLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} + +function getStylesheetNameFor(editor) { + return editor.summary + .querySelector(".stylesheet-name > label") + .getAttribute("value"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js b/devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js new file mode 100644 index 0000000000..5967eb40b5 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js @@ -0,0 +1,85 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that the style sheet list can be navigated with keyboard. + +const TESTCASE_URI = TEST_BASE_HTTP + "four.html"; + +add_task(async function () { + const { panel, ui } = await openStyleEditorForURL(TESTCASE_URI); + + info("Waiting for source editor to load."); + await ui.editors[0].getSourceEditor(); + + const onEditorSelected = new Promise(resolve => { + const off = ui.on("editor-selected", editor => { + if (editor == ui.editors[2]) { + resolve(); + off(); + } + }); + }); + + info("Testing keyboard navigation on the sheet list."); + testKeyboardNavigation(ui.editors[0], panel); + + info("Waiting for editor #2 to be selected due to keyboard navigation."); + await onEditorSelected; + ok(ui.editors[2].sourceEditor.hasFocus(), "Editor #2 has focus."); +}); + +function getStylesheetNameLinkFor(editor) { + return editor.summary.querySelector(".stylesheet-name"); +} + +function testKeyboardNavigation(editor, panel) { + const panelWindow = panel.panelWindow; + const ui = panel.UI; + waitForFocus(function () { + const summary = editor.summary; + EventUtils.synthesizeMouseAtCenter(summary, {}, panelWindow); + + let item = getStylesheetNameLinkFor(ui.editors[0]); + is( + panelWindow.document.activeElement, + item, + "editor 0 item is the active element" + ); + + EventUtils.synthesizeKey("VK_DOWN", {}, panelWindow); + item = getStylesheetNameLinkFor(ui.editors[1]); + is( + panelWindow.document.activeElement, + item, + "editor 1 item is the active element" + ); + + EventUtils.synthesizeKey("VK_HOME", {}, panelWindow); + item = getStylesheetNameLinkFor(ui.editors[0]); + is( + panelWindow.document.activeElement, + item, + "fist editor item is the active element" + ); + + EventUtils.synthesizeKey("VK_END", {}, panelWindow); + item = getStylesheetNameLinkFor(ui.editors[3]); + is( + panelWindow.document.activeElement, + item, + "last editor item is the active element" + ); + + EventUtils.synthesizeKey("VK_UP", {}, panelWindow); + item = getStylesheetNameLinkFor(ui.editors[2]); + is( + panelWindow.document.activeElement, + item, + "editor 2 item is the active element" + ); + + EventUtils.synthesizeKey("VK_RETURN", {}, panelWindow); + // this will attach and give focus editor 2 + }, panelWindow); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sv_resize.js b/devtools/client/styleeditor/test/browser_styleeditor_sv_resize.js new file mode 100644 index 0000000000..76098145bc --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sv_resize.js @@ -0,0 +1,53 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test that resizing the source editor container doesn't move the caret. + +const TESTCASE_URI = TEST_BASE_HTTP + "simple.html"; + +const { Toolbox } = require("resource://devtools/client/framework/toolbox.js"); + +add_task(async function () { + const { toolbox, ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "There are 2 style sheets initially"); + + info("Changing toolbox host to a window."); + await toolbox.switchHost(Toolbox.HostType.WINDOW); + + const editor = await ui.editors[0].getSourceEditor(); + const originalSourceEditor = editor.sourceEditor; + + const hostWindow = toolbox.win.parent; + const originalWidth = hostWindow.outerWidth; + const originalHeight = hostWindow.outerHeight; + + // to check the caret is preserved + originalSourceEditor.setCursor(originalSourceEditor.getPosition(4)); + + info("Resizing window."); + hostWindow.resizeTo(120, 480); + + const sourceEditor = ui.editors[0].sourceEditor; + is( + sourceEditor, + originalSourceEditor, + "the editor still references the same Editor instance" + ); + + is( + sourceEditor.getOffset(sourceEditor.getCursor()), + 4, + "the caret position has been preserved" + ); + + info("Restoring window to original size."); + hostWindow.resizeTo(originalWidth, originalHeight); +}); + +registerCleanupFunction(() => { + // Restore the host type for other tests. + Services.prefs.clearUserPref("devtools.toolbox.host"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_sync.js b/devtools/client/styleeditor/test/browser_styleeditor_sync.js new file mode 100644 index 0000000000..6b97e1cae0 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_sync.js @@ -0,0 +1,73 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that changes in the style inspector are synchronized into the +// style editor. + +const TESTCASE_URI = TEST_BASE_HTTP + "sync.html"; + +const expectedText = ` + body { + border-width: 15px; + /*! color: red; */ + } + + #testid { + /*! font-size: 4em; */ + } + `; + +async function closeAndReopenToolbox() { + await gDevTools.closeToolboxForTab(gBrowser.selectedTab); + const { ui: newui } = await openStyleEditor(); + return newui; +} + +add_task(async function () { + await addTab(TESTCASE_URI); + const { inspector, view } = await openRuleView(); + await selectNode("#testid", inspector); + let ruleEditor = getRuleViewRuleEditor(view, 1); + + // Disable the "font-size" property. + let propEditor = ruleEditor.rule.textProps[0].editor; + let onModification = view.once("ruleview-changed"); + propEditor.enable.click(); + await onModification; + + // Disable the "color" property. Note that this property is in a + // rule that also contains a non-inherited property -- so this test + // is also testing that property editing works properly in this + // situation. + ruleEditor = getRuleViewRuleEditor(view, 3); + propEditor = ruleEditor.rule.textProps[1].editor; + onModification = view.once("ruleview-changed"); + propEditor.enable.click(); + await onModification; + + let { ui } = await openStyleEditor(); + + let editor = await ui.editors[0].getSourceEditor(); + let text = editor.sourceEditor.getText(); + is(text, expectedText, "style inspector changes are synced"); + + // Close and reopen the toolbox, to see that the edited text remains + // available. + ui = await closeAndReopenToolbox(); + editor = await ui.editors[0].getSourceEditor(); + text = editor.sourceEditor.getText(); + is(text, expectedText, "changes remain after close and reopen"); + + // For the time being, the actor does not update the style's owning + // node's textContent. See bug 1205380. + const textContent = await SpecialPowers.spawn( + gBrowser.selectedBrowser, + [], + async function () { + return content.document.querySelector("style").textContent; + } + ); + + isnot(textContent, expectedText, "changes not written back to style node"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_syncAddProperty.js b/devtools/client/styleeditor/test/browser_styleeditor_syncAddProperty.js new file mode 100644 index 0000000000..51546eaba6 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_syncAddProperty.js @@ -0,0 +1,52 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that adding a new rule is synced to the style editor. + +const TESTCASE_URI = TEST_BASE_HTTP + "sync.html"; +const TESTCASE_URI_WITH_CSP = TEST_BASE_HTTP + "sync_with_csp.html"; + +const expectedText = ` + body { + border-width: 15px; + color: red; + } + + #testid { + font-size: 4em; + /*! background-color: yellow; */ + } + `; + +add_task(async function () { + const URIs = [TESTCASE_URI, TESTCASE_URI_WITH_CSP]; + + for (const URI of URIs) { + await addTab(URI); + const { inspector, view } = await openRuleView(); + await selectNode("#testid", inspector); + + info("Focusing a new property name in the rule-view on " + URI); + const ruleEditor = getRuleViewRuleEditor(view, 1); + const editor = await focusEditableField(view, ruleEditor.closeBrace); + is( + inplaceEditor(ruleEditor.newPropSpan), + editor, + "The new property editor has focus" + ); + + const input = editor.input; + input.value = "/* background-color: yellow; */"; + + info("Pressing return to commit and focus the new value field"); + const onModifications = view.once("ruleview-changed"); + EventUtils.synthesizeKey("VK_RETURN", {}, view.styleWindow); + await onModifications; + + const { ui } = await openStyleEditor(); + const sourceEditor = await ui.editors[0].getSourceEditor(); + const text = sourceEditor.sourceEditor.getText(); + is(text, expectedText, "selector edits are synced"); + } +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_syncAddRule.js b/devtools/client/styleeditor/test/browser_styleeditor_syncAddRule.js new file mode 100644 index 0000000000..e46ae57ed3 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_syncAddRule.js @@ -0,0 +1,30 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that adding a new rule is synced to the style editor. + +const TESTCASE_URI = TEST_BASE_HTTP + "sync.html"; + +const expectedText = ` +#testid { +}`; + +add_task(async function () { + await addTab(TESTCASE_URI); + const { inspector, view } = await openRuleView(); + await selectNode("#testid", inspector); + + const onRuleViewChanged = once(view, "ruleview-changed"); + view.addRuleButton.click(); + await onRuleViewChanged; + + const { ui } = await openStyleEditor(); + + info("Selecting the second editor"); + await ui.selectStyleSheet(ui.editors[1].styleSheet); + + const editor = ui.editors[1]; + const text = editor.sourceEditor.getText(); + is(text, expectedText, "selector edits are synced"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_syncAlreadyOpen.js b/devtools/client/styleeditor/test/browser_styleeditor_syncAlreadyOpen.js new file mode 100644 index 0000000000..f91441e7ea --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_syncAlreadyOpen.js @@ -0,0 +1,50 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that changes in the style inspector are synchronized into the +// style editor. + +const TESTCASE_URI = TEST_BASE_HTTP + "sync.html"; + +const expectedText = ` + body { + border-width: 15px; + color: red; + } + + #testid { + /*! font-size: 4em; */ + } + `; + +add_task(async function () { + await addTab(TESTCASE_URI); + + const { inspector, view, toolbox } = await openRuleView(); + + // In this test, make sure the style editor is open before making + // changes in the inspector. + const { ui } = await openStyleEditor(); + const editor = await ui.editors[0].getSourceEditor(); + + const onEditorChange = new Promise(resolve => { + editor.sourceEditor.on("change", resolve); + }); + + await toolbox.getPanel("inspector"); + await selectNode("#testid", inspector); + const ruleEditor = getRuleViewRuleEditor(view, 1); + + // Disable the "font-size" property. + const propEditor = ruleEditor.rule.textProps[0].editor; + const onModification = view.once("ruleview-changed"); + propEditor.enable.click(); + await onModification; + + await openStyleEditor(); + await onEditorChange; + + const text = editor.sourceEditor.getText(); + is(text, expectedText, "style inspector changes are synced"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_syncEditSelector.js b/devtools/client/styleeditor/test/browser_styleeditor_syncEditSelector.js new file mode 100644 index 0000000000..c82000aada --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_syncEditSelector.js @@ -0,0 +1,38 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that changes in the style inspector are synchronized into the +// style editor. + +const TESTCASE_URI = TEST_BASE_HTTP + "sync.html"; + +const expectedText = ` + body { + border-width: 15px; + color: red; + } + + #testid, span { + font-size: 4em; + } + `; + +add_task(async function () { + await addTab(TESTCASE_URI); + const { inspector, view } = await openRuleView(); + await selectNode("#testid", inspector); + const ruleEditor = getRuleViewRuleEditor(view, 1); + + let editor = await focusEditableField(view, ruleEditor.selectorText); + editor.input.value = "#testid, span"; + const onRuleViewChanged = once(view, "ruleview-changed"); + EventUtils.synthesizeKey("KEY_Enter"); + await onRuleViewChanged; + + const { ui } = await openStyleEditor(); + + editor = await ui.editors[0].getSourceEditor(); + const text = editor.sourceEditor.getText(); + is(text, expectedText, "selector edits are synced"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js b/devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js new file mode 100644 index 0000000000..210e9b2bce --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js @@ -0,0 +1,41 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +// Test that changes in the style editor are synchronized into the +// style inspector. + +const TEST_URI = ` + +
Styled Node
+`; + +const TESTCASE_CSS_SOURCE = "#testid { color: chartreuse; }"; + +add_task(async function () { + await addTab("data:text/html;charset=utf-8," + encodeURIComponent(TEST_URI)); + + info("Open the inspector and select the node we want to add style to"); + const { inspector, view } = await openRuleView(); + await selectNode("#testid", inspector); + + info("Open the StyleEditor"); + const { panel, ui } = await openStyleEditor(); + + const editor = await ui.editors[0].getSourceEditor(); + const onRuleViewRefreshed = view.once("ruleview-refreshed"); + await new Promise(res => waitForFocus(res, panel.panelWindow)); + + info("Type new rule in stylesheet"); + editor.focus(); + EventUtils.sendString(TESTCASE_CSS_SOURCE, panel.panelWindow); + ok(editor.unsaved, "new editor has unsaved flag"); + + info("Wait for ruleview to update"); + await onRuleViewRefreshed; + + info("Check that edits were synced to rule view"); + const value = getRuleViewPropertyValue(view, "#testid", "color"); + is(value, "chartreuse", "Got the expected color property"); +}); diff --git a/devtools/client/styleeditor/test/browser_styleeditor_transition_rule.js b/devtools/client/styleeditor/test/browser_styleeditor_transition_rule.js new file mode 100644 index 0000000000..7fd1c0bd1b --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_transition_rule.js @@ -0,0 +1,51 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TESTCASE_URI = TEST_BASE_HTTPS + "simple.html"; + +const NEW_RULE = "body { background-color: purple; }"; + +add_task(async function () { + const { ui } = await openStyleEditorForURL(TESTCASE_URI); + + is(ui.editors.length, 2, "correct number of editors"); + + const editor = ui.editors[0]; + await openEditor(editor); + + // Set text twice in a row + const styleChanges = listenForStyleChange(editor); + + editor.sourceEditor.setText(NEW_RULE); + editor.sourceEditor.setText(NEW_RULE + " "); + + await styleChanges; + + const rules = await SpecialPowers.spawn( + gBrowser.selectedBrowser, + [0], + async function (index) { + const sheet = content.document.styleSheets[index]; + return [...sheet.cssRules].map(rule => rule.cssText); + } + ); + + // Test that we removed the transition rule, but kept the rule we added + is(rules.length, 1, "only one rule in stylesheet"); + is(rules[0], NEW_RULE, "stylesheet only contains rule we added"); +}); + +/* Helpers */ + +function openEditor(editor) { + const link = editor.summary.querySelector(".stylesheet-name"); + link.click(); + + return editor.getSourceEditor(); +} + +function listenForStyleChange(editor) { + return editor.once("style-applied"); +} diff --git a/devtools/client/styleeditor/test/browser_styleeditor_xul.js b/devtools/client/styleeditor/test/browser_styleeditor_xul.js new file mode 100644 index 0000000000..e5843b9e79 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_styleeditor_xul.js @@ -0,0 +1,23 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +// Test that the style-editor initializes correctly for XUL windows. + +"use strict"; + +waitForExplicitFinish(); + +const TEST_URL = TEST_BASE + "doc_xulpage.xhtml"; + +add_task(async function () { + const tab = await addTab(TEST_URL); + const toolbox = await gDevTools.showToolboxForTab(tab, { + toolId: "styleeditor", + }); + const panel = toolbox.getCurrentPanel(); + + ok( + panel, + "The style-editor panel did initialize correctly for the XUL window" + ); +}); diff --git a/devtools/client/styleeditor/test/browser_toolbox_styleeditor.js b/devtools/client/styleeditor/test/browser_toolbox_styleeditor.js new file mode 100644 index 0000000000..a099551db6 --- /dev/null +++ b/devtools/client/styleeditor/test/browser_toolbox_styleeditor.js @@ -0,0 +1,100 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Test that stylesheets from parent and content processes are displayed in the styleeditor. + +"use strict"; + +requestLongerTimeout(4); + +const TEST_URI = `data:text/html, + + + + + Test browser toolbox`; + +/* global gToolbox */ +Services.scriptloader.loadSubScript( + "chrome://mochitests/content/browser/devtools/client/framework/browser-toolbox/test/helpers-browser-toolbox.js", + this +); + +add_task(async function () { + await pushPref("devtools.browsertoolbox.scope", "everything"); + await pushPref("devtools.styleeditor.transitions", false); + await addTab(TEST_URI); + const ToolboxTask = await initBrowserToolboxTask(); + + await ToolboxTask.importFunctions({ + waitUntil, + }); + + await ToolboxTask.spawn(null, async () => { + await gToolbox.selectTool("styleeditor"); + const panel = gToolbox.getCurrentPanel(); + + function getStyleEditorItems() { + return Array.from( + panel.panelWindow.document.querySelectorAll(".splitview-nav li") + ); + } + + info(`check if "parent process" stylesheets are displayed`); + const isUAStyleSheet = el => + el.querySelector(".stylesheet-name label").value == "ua.css"; + await waitUntil(() => getStyleEditorItems().find(isUAStyleSheet)); + ok(true, "Found ua.css stylesheet"); + + info("check if content page stylesheets are displayed"); + const isTabStyleSheet = el => + el.querySelector(".stylesheet-name label").value == "simple.css"; + await waitUntil(() => getStyleEditorItems().find(isTabStyleSheet)); + ok(true, "Found simple.css tab stylesheet"); + + info("Select the stylesheet and update its content"); + const contentStylesheetSummaryEl = + getStyleEditorItems().find(isTabStyleSheet); + + let tabStyleSheetEditor; + if (panel.UI.selectedEditor.friendlyName === "simple.css") { + // simple.css might be selected by default, depending on the order in + // which the stylesheets have been loaded in the style editor. + tabStyleSheetEditor = panel.UI.selectedEditor; + } else { + // We might get events for the initial, default selected stylesheet, so wait until + // we get the one for the simple.css stylesheet. + const onTabStyleSheetEditorSelected = new Promise(resolve => { + const onEditorSelected = editor => { + if (editor.summary == contentStylesheetSummaryEl) { + resolve(editor); + panel.UI.off("editor-selected", onEditorSelected); + } + }; + panel.UI.on("editor-selected", onEditorSelected); + }); + panel.UI.setActiveSummary(contentStylesheetSummaryEl); + tabStyleSheetEditor = await onTabStyleSheetEditorSelected; + } + const onStyleApplied = tabStyleSheetEditor.once("style-applied"); + tabStyleSheetEditor.sourceEditor.setText( + tabStyleSheetEditor.sourceEditor.getText() + "\n body {color: red;}" + ); + await onStyleApplied; + }); + + info("Check that the edit done in the style editor were applied to the page"); + const bodyColorStyle = await getComputedStyleProperty({ + selector: "body", + name: "color", + }); + + is( + bodyColorStyle, + "rgb(255, 0, 0)", + "Changes made to simple.css were applied to the page" + ); + + await ToolboxTask.destroy(); +}); diff --git a/devtools/client/styleeditor/test/bug_1405342_serviceworker_iframes.html b/devtools/client/styleeditor/test/bug_1405342_serviceworker_iframes.html new file mode 100644 index 0000000000..7bcbcf875c --- /dev/null +++ b/devtools/client/styleeditor/test/bug_1405342_serviceworker_iframes.html @@ -0,0 +1,10 @@ + + + + + Bug 1405342 + + +