Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sass: Resolving component dependencies (an improved version) #sass
// ----
// Sass (v3.4.4)
// Compass (v1.0.1)
// ----
// Sass: Resolving component dependencies
// An improved version of https://gist.github.com/whizark/51ccdfbf57dbcb73953f
// Other ideas: https://github.com/whizark/xass#ideas
$x\dependencies: (
-components: ()
);
// Functions
@function x\dependencies\-get-components() {
@return map-get($x\dependencies, '-components');
}
@function x\dependencies\-is-registered($id) {
$components: x\dependencies\-get-components();
@return map-has-key($components, '-#{$id}');
}
@function x\dependencies\-get($id) {
$components: x\dependencies\-get-components();
@if not map-has-key($components, '-#{$id}')
{
@error 'The component `#{id}` is not registered.';
}
@return map-get($components, '-#{$id}');
}
@function x\dependencies\-get-dependencies($id) {
$component: x\dependencies\-get($id);
@return map-get($component, '-dependencies');
}
@function x\dependencies\-resolve($id) {
@if not x\dependencies\-is-registered($id)
{
@return false;
}
$components: x\dependencies\-get-components();
$dependencies: x\dependencies\-get-dependencies($id);
@each $dependency in $dependencies
{
@if not x\dependencies\-resolve($dependency)
{
@error 'Cannot resolve the dependency `#{$dependency}` for `#{$id}`.';
}
}
@return true;
}
@function x\dependencies\register($id, $dependencies: ()) {
@if x\dependencies\-is-registered($id) {
@error 'The component `#{$id}` has already been registered.';
}
$components: x\dependencies\-get-components();
$component: (
-id : $id,
-dependencies: $dependencies
);
$components: map-merge($components, (-#{$id}: $component));
$x\dependencies: map-merge($x\dependencies, (-components: $components)) !global;
$is-resolved: x\dependencies\-resolve($id);
@return $dependencies;
}
// Register a component and the dependencies
@mixin x\dependencies\register($id, $dependencies: ()) {
$dependencies: x\dependencies\register($id, $dependencies);
}
// Use case
// File: dependency-1/_provider.scss
@include x\dependencies\register('dependency-1', ());
// File: dependency-2/_provider.scss
@include x\dependencies\register('dependency-2', ('dependency-1'));
// File: component-1/_provider.scss
@include x\dependencies\register('component-1', ('dependency-2', 'dependency-1'));
// File: client.scss
// @import 'dependency-1/provider.scss';
// @import 'dependency-2/provider.scss';
// @import 'component-1/provider.scss';
@st32lthx

This comment has been minimized.

Copy link

@st32lthx st32lthx commented May 23, 2015

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment