Skip to content

Commit

Permalink
Merge pull request #21 from a-ignatov-parc/css-as-deps
Browse files Browse the repository at this point in the history
Загрузка стилей для секций
  • Loading branch information
a-ignatov-parc committed Aug 12, 2014
2 parents 2a34f9a + 8f7f734 commit 4a0426d
Show file tree
Hide file tree
Showing 9 changed files with 159 additions and 109 deletions.
1 change: 1 addition & 0 deletions app/client/config.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ define [
"utils/preprocessors/clicks"
], (popupsModule, scrollPreprocessor, clicksPreprocessor) ->
widgetDataAttributeName: "data-js-widgets"
widgetCssAttributeName: "data-css-widgets"
reloadParamsDataAttributeName: "data-reload-params"
reloadSectionsDataAttributeName: "data-reload-sections"
baseWidgetsPath: ""
Expand Down
1 change: 0 additions & 1 deletion app/client/loader.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ define [
# ищет все блоки виджетов и отдает их на загрузку в loadWidgetModule
#
search: (node, ready) ->

loader.widgets widgetsData(node), ready


Expand Down
2 changes: 1 addition & 1 deletion app/client/sections.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ define [
isNewState = (history.state or {}).url isnt state.url
method = if isNewState and !state.userReplaceState then "pushState" else "replaceState"
history[method] state, state.title, state.url
@last = new Transition state, (if @current?.next_transition? and @current.next_transition.index < state.index then @current else @last)
@last = new Transition state, (if @current?.next_transition?.index < state.index then @current else @last)
return @last

###### transitions.go(index)
Expand Down
16 changes: 4 additions & 12 deletions app/client/sections/invoker.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -137,21 +137,13 @@ define [
insertionData[target] =
back: sections.back[target]
forward: sections.forward[target]

insertionData

.each (section, target, context) ->
# приостановка выполнения очереди, так как дальше опять
# идет асинхронная
#context.pause() —— из-за этой штуки получается странный баг
# — cancel http запросов браузера

section.back.turnOff()
section.forward.turnOn()

# возобновление выполнения очереди
#context.resume() —— FIXME: странный cancel
# http запросов картинок и т.д. в браузере
context.pause()
section.forward.turnOn ->
section.back.turnOff()
, context.resume

.next ->
# Сообщаем об окончании вставки секций
Expand Down
66 changes: 51 additions & 15 deletions app/client/sections/section.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ define [
"clicks/forms"
"dom"
], (events, config, loader, widgets, widgetsData, _, forms, dom) ->
extensionRegex = /\.css$/

Section = () ->
@name
@params = {}
Expand All @@ -21,21 +23,58 @@ define [
@

Section:: =
turnOn: () ->
@turnOnWidgets()
@insertIntoDOM()
@onInsert()
turnOn: (before, after) ->
@loadStyles =>
before?()
@turnOnWidgets()
@insertIntoDOM()
@onInsert()
after?()

# Из-за того что браузеры отменяют загрузку ресурсов после удаления DOM элементов, то после
# смены секций мы возобновляем загрузку ресурсов за счет резолва html строки в DOM элемент.
dom @getSectionHtml()

loadStyles: (callback) ->
depList = []
headElement = dom('head')[0]
hasExternalPlugin = require.specified "css"

for element in dom(@getSectionHtml()).find("[#{config.widgetCssAttributeName}]").get()
if element.getAttribute?
cssPath = element.getAttribute config.widgetCssAttributeName
cssPath = "#{cssPath.replace(extensionRegex, "")}.css" if cssPath?

if not hasExternalPlugin
linkNode = document.createElement "link"
linkNode.rel = "stylesheet"
linkNode.type = "text/css"
linkNode.href = cssPath
headElement.appendChild linkNode
depList.push "css!#{cssPath}"

if depList.length
if hasExternalPlugin
# Если загрузчик поддерживает обработчик завершения загрузки стилей, то чтоб стили
# точно успели применится делаем задержку в 100мс перед возобновлением пайплайна смены
# секций.
require depList, -> setTimeout callback, 100
else
console.warn "External plugin for loading css is not found. Creating direct links..."
callback?()
else
callback?()

turnOff: () ->
turnOff: ->
@turnOffWidgets()
@removeFromDOM()
@onRemove()

removeFromDOM: () ->
removeFromDOM: ->
for element in @getSectionHtml()
element.parentNode.removeChild element if element.parentNode?

insertIntoDOM: () ->
insertIntoDOM: ->
return unless @params.target
switch @params.target
when "icon"
Expand All @@ -55,22 +94,19 @@ define [
for element in @getSectionHtml()
container.appendChild element

turnOnWidgets: () ->
loader.search @getSectionHtml(), (widgetsList) =>
# удобно, но пока кажется избыточным такой notify
#notifyAll "turnedOn", "-widgets", widgetsList
on
turnOnWidgets: ->
loader.search @getSectionHtml()

turnOffWidgets: () ->
turnOffWidgets: ->
for data in widgetsData @getSectionHtml()
widgets.get(data.name, data.element)?.sleepDown()

onInsert: () ->
onInsert: ->
postfix = "inserted"
@notifyAll postfix
@processNamespaces postfix

onRemove: () ->
onRemove: ->
postfix = "removed"
@notifyAll postfix
@processNamespaces postfix
Expand Down
8 changes: 4 additions & 4 deletions app/client/utils/sections.coffee
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#### *module* utils/sections
#
# Вспомогательный модуль для загрузки модулей без использования навигационого
# Вспомогательный модуль для загрузки модулей без использования навигационого
# модуля.
# Модули загружаются без событий pageTransition.
# Модули могут быть загружены данным модулем, как вызовом на прямую, так и
# Модули могут быть загружены данным модулем, как вызовом на прямую, так и
# через параметры в ссылках.
#
#
# Загрузка модуля на прямую:
# require("utils/sections").load("UserBarWidget", "#UserBarWidget")
#
#
# Загрузка модуля через ссылку:
# <a href="./" data-reload-sections='UserBarWidget: #UserBarWidget' data-reload-params='{ "loadSectionsSilently": true }'>Text</a>
#
Expand Down
2 changes: 1 addition & 1 deletion app/client/widgets.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ define ["events", "dom", "utils/destroyer", "config", "utils/guid", "underscore"
widgets =
_instances: {}
_id_attr: (name) ->
return "data-#{name}-id".replace /\/|\?|=|&/g, "-"
return "data-#{name}-id".replace /[\/?=&!]/g, "-"

remove: (widget) ->
widget.element.removeAttribute @_id_attr widget.name
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"grunt-groc": "~0.3.0",
"grunt-open": "~0.2.0",
"grunt-concat-sourcemap": "*",
"grunt-notify": "~0.2.4"
"grunt-notify": "~0.3.0"
},
"some": {
"jade": "*",
Expand Down
Loading

0 comments on commit 4a0426d

Please sign in to comment.