From 1fe1147901e0268a28da9fb2e65fce19f9b2786f Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Mon, 13 Oct 2014 12:43:36 -0600 Subject: [PATCH] Add group parameter to StyleManager::addStyleSheet This can be used to sequence style elements at the correct location in the cascade even if they are loaded later than elements in a subsequent group. --- spec/style-manager-spec.coffee | 12 ++++++++++++ src/style-manager.coffee | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/spec/style-manager-spec.coffee b/spec/style-manager-spec.coffee index d7f0b0e97..3b70e7ad4 100644 --- a/spec/style-manager-spec.coffee +++ b/spec/style-manager-spec.coffee @@ -56,3 +56,15 @@ describe "StyleManager", -> expect(addEvents.length).toBe 1 expect(addEvents[0].sourcePath).toBe '/foo/bar' expect(addEvents[0].styleElement.textContent).toBe "a {color: yellow;}" + + describe "when a group parameter is specified", -> + it "inserts the stylesheet at the end of any existing stylesheets for the same group", -> + manager.addStyleSheet("a {color: red}", group: 'a') + manager.addStyleSheet("a {color: blue}", group: 'b') + manager.addStyleSheet("a {color: green}", group: 'a') + + expect(manager.getStyleElements().map (elt) -> elt.textContent).toEqual [ + "a {color: red}" + "a {color: green}" + "a {color: blue}" + ] diff --git a/src/style-manager.coffee b/src/style-manager.coffee index cd4604f8e..cf3be51c9 100644 --- a/src/style-manager.coffee +++ b/src/style-manager.coffee @@ -21,20 +21,31 @@ class StyleManager addStyleSheet: (source, params) -> sourcePath = params?.sourcePath + group = params?.group + if sourcePath? and styleElement = @styleElementsBySourcePath[sourcePath] updated = true else styleElement = document.createElement('style') + styleElement.group = group if group? styleElement.textContent = source - @styleElements.push(styleElement) + if group? + for existingElement, index in @styleElements + if existingElement.group is group + insertIndex = index + 1 + else + break if insertIndex? + insertIndex ?= @styleElements.length + + @styleElements.splice(insertIndex, 0, styleElement) @styleElementsBySourcePath[sourcePath] ?= styleElement if sourcePath? if updated - @emitter.emit 'did-update-style-sheet', {styleElement, sourcePath} + @emitter.emit 'did-update-style-sheet', {styleElement, sourcePath, group} else - @emitter.emit 'did-add-style-sheet', {styleElement, sourcePath} + @emitter.emit 'did-add-style-sheet', {styleElement, sourcePath, group} new Disposable => @removeStyleElement(styleElement, params)