Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sass: Resolving component dependencies #sass
// Sass: Resolving component dependencies
// Other ideas: https://github.com/whizark/xass#ideas
// The storage for dependency management
$container: (
-components: (),
-frozen: ()
);
// Functions
@function components() {
@return map-get($container, '-components');
}
@function -frozen() {
@return map-get($container, '-frozen');
}
@function -is-frozen($id) {
$frozen: -frozen();
@return (index($frozen, $id) != null);
}
@function component($id) {
$components: components();
@if not map-has-key($components, $id) {
@error 'The id #{id} is not registered.';
}
@return map-get($components, $id);
}
@function component-name($id) {
$component: component($id);
@return map-get($component, '-name');
}
@function component-dependencies($id) {
$component: component($id);
@return map-get($component, '-dependencies');
}
@function component-path($id) {
$component: component($id);
@return map-get($component, '-path');
}
@function register($id, $dependencies: (), $path: null) {
@if -is-frozen($id) {
@error 'The id #{$id} has already been resolved.';
}
$components: components();
$properties: (
-name : $id,
-dependencies: $dependencies,
-path: $path
);
$components: map-merge($components, (#{$id}: $properties));
$container: map-merge($container, (-components: $components));
@return $container;
}
// Register a component and the dependencies
@mixin register($id, $dependencies: (), $path: null)
{
$container: register($id, $dependencies, $path) !global;
}
// Resolve dependencies
@function resolve($id) {
$paths: ();
$components: components();
$dependencies: component-dependencies($id);
@each $dependency in $dependencies {
@if not -is-frozen($dependency) {
$paths: append($paths, resolve($dependency), comma);
}
}
@if not -is-frozen($id) {
$paths: append($paths, component-path($id), comma);
$frozen: append(-frozen(), $id);
$container: map-merge($container, (-frozen: $frozen)) !global;
}
@return $paths;
}
// Component definitions
@include register('component-1', ('dependency-2', 'dependency-1'), '_component-1');
@include register('dependency-2', ('dependency-1'), '_dependency-2');
@include register('dependency-1', (), '_dependency-1');
// Tests
.resolver {
$paths: inspect(resolve('component-1'));
// Returns filepaths based on the dependencies.
component-1: $paths;
// Returns empty string after the dependencies are resolved.
component-1: inspect(resolve('component-1'));
}
// @todo Normalize List & import components
// @import $paths;
.resolver {
component-1: ((("_dependency-1",)), "_dependency-2"), "_component-1";
component-1: ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment