work on planner templates in progress

This commit is contained in:
2019-02-07 21:58:38 +01:00
parent f220c6c960
commit 29b2f076bf
10 changed files with 209 additions and 108 deletions

Binary file not shown.

View File

@@ -15,7 +15,7 @@ pub mod fields {
/// representing the main use of the resulting preparation.
///
/// It is stored as Integer
#[derive(Debug, Copy, Clone, FromSqlRow, AsExpression)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, FromSqlRow, AsExpression)]
#[sql_type = "SmallInt"]
pub enum RecipeCategory {
Breakfast = 0,

View File

@@ -7,6 +7,7 @@ use self::cookbook::*;
use self::cookbook::recipes::Recipe;
use self::planner::solver::{Variables, Domain, Problem};
type DomainValues<'a, V> = Vec<&'a V>;
/// We want a mapping of the week meals (matin, midi, soir)
/// Breakfast => RecipeCategory::Breakfast
/// Lunch => RecipeCategory::MainCourse
@@ -14,31 +15,25 @@ use self::planner::solver::{Variables, Domain, Problem};
mod template {
//! Exports the [`Template`] struct.
use super::{Domain, DomainValues, Variables, Recipe};
type Day = String;
const DAYS: &[&str] = &["Lundi", "Mardi", "Mercredi"];
const DAYS: &[&str] = &[
"Lundi", "Mardi", "Mercredi",
"Jeudi", "Vendredi", "Samedi",
"Dimanche"];
/// An enum to discriminate every meals
#[allow(dead_code)]
enum Meals {
pub enum Meals {
Breakfast(Day),
Lunch(Day),
Dinner(Day)
}
pub struct Template;
impl Template {
fn empty() {
}
}
}
impl Into<String> for Meals {
fn into(self) -> String {
match self {
impl From<Meals> for String {
fn from(item: Meals) -> String {
match item {
Meals::Breakfast(d) => format!("{}_Breakfast", d),
Meals::Lunch(d) => format!("{}_Lunch", d),
Meals::Dinner(d) => format!("{}_Dinner", d),
@@ -46,20 +41,61 @@ impl Into<String> for Meals {
}
}
/// It may also contains an initial value for each variable
fn generate_variables<V>(domain: &Domain<V>) -> Vec<(String, &Domain<V>, Option<&V>)> {
let mut vars = Vec::new();
/// A fixed template of meals
///
/// TODO: mask -> disabled choosen meals
/// initials -> fixed values
pub struct Template;
impl Template {
fn keys() -> Vec<Meals> {
let mut keys = Vec::new();
for day in DAYS {
vars.push((Meals::Lunch(day.to_string()).into(), domain, None));
vars.push((Meals::Dinner(day.to_string()).into(), domain, None));
for meal in &[Meals::Breakfast, Meals::Lunch, Meals::Dinner] {
keys.push(meal(day.to_string()))
}
}
keys
}
/// Build a [`Template`] from a variables assignment map,
/// usually a solution returned by solver
pub(super) fn from_variables<'a, V>(_vars: Variables<'a,V>) -> Template{
Template
}
/// Builds a vector of variables, to be used with
/// [`ProblemBuilder`].
pub(super) fn generate_variables(domain: &Domain<Recipe>)
-> Vec<(String, DomainValues<Recipe>, Option<&Recipe>)>
{
use cookbook::recipes::RecipeCategory;
let mut vars = Vec::new();
for key in Self::keys().into_iter() {
//TODO: Use key variants to set filters on domain
//TODO: Initial values
let _filter: fn(&&Recipe) -> bool = match key {
Meals::Breakfast(_) => |r: &&Recipe| {
r.category == RecipeCategory::Breakfast // Breakfast
},
Meals::Lunch(_) => |r: &&Recipe| {
r.category as i16 == 2i16 // MainCourse
},
Meals::Dinner(_) => |r: &&Recipe| {
r.category as i16 == 1i16 // Starter
}
};
vars.push((key.into(), domain.filter(_filter), None));
}
vars
}
}
}
fn ingredients_contains<'a>(assign: &Variables<'a,Recipe>) -> bool {
let id = 0;
assign.get("Lundi_Lunch").unwrap().unwrap().ingredients.contains(&id)
&& !assign.get("Mardi_Lunch").unwrap().unwrap().ingredients.contains(&id)
fn ingredients_contains<'a>(_assign: &Variables<'a,Recipe>) -> bool {
true
}
@@ -80,7 +116,7 @@ fn get_planning_all_results() -> String {
let possible_values = recipes::load_all(&conn);
let domain = Domain::new(possible_values);
let mut problem = Problem::build();
for (var, dom, ini) in generate_variables(&domain) {
for (var, dom, ini) in template::Template::generate_variables(&domain) {
problem = problem.add_variable(var, dom, ini);
}
let mut problem = problem

View File

@@ -14,7 +14,7 @@ enum Assignment<'a, V> {
}
type Domains<'a, V> = HashMap<String, &'a Domain<V>>;
pub type DomainValues<'a, V> = Vec<&'a V>;
/// The domain of values that can be assigned to variables
#[derive(Clone)]
pub struct Domain<V> {
@@ -26,10 +26,11 @@ impl<V> Domain<V> {
Domain { values }
}
pub fn values(&self) -> &Vec<V> {
&self.values
/// Returns all values of a Domain instance
pub fn all(&self) -> DomainValues<V> {
self.values.iter().collect()
}
/// Returns a new domain with the given filter applied to inner values
/// Returns a Filter filter applied to inner values
///
/// # Examples
///
@@ -40,12 +41,10 @@ impl<V> Domain<V> {
/// fn even(i: &i32) -> bool { i % 2 == 0 };
/// assert_eq!(&domain.filter(even).values, &vec![2]);
/// ```
pub fn filter(&self, f: fn(&V) -> bool) -> Domain<V>
pub fn filter(&self, f: fn(&&V) -> bool) -> DomainValues<V>
where V: std::clone::Clone
{
Domain {
values: self.values.iter().cloned().filter(f).collect(),
}
self.values.iter().filter(f).collect()
}
}
@@ -62,7 +61,7 @@ pub struct Problem<'a, V> {
/// The initial assignements map
variables: Variables<'a, V>,
/// Each variable has its associated domain
domains: Domains<'a,V>,
domains: HashMap<String, DomainValues<'a,V>>,
/// Set of constraints to validate
constraints: Vec<Constraint<'a,V>>,
}
@@ -78,14 +77,14 @@ impl<'a,V> Problem<'a, V> {
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V>>> {
// TODO: should be able to inject a choosing strategy
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
let domain = self.domains.get(key).expect("No domain for variable !");
let domain_values = self.domains.get(key).expect("No domain for variable !");
// Push a clear assignment first, just before going up the stack.
let mut updates = vec![Assignment::Clear(key.clone())];
if domain.values.is_empty() { panic!("No value in domain !"); }
if domain_values.is_empty() { panic!("No value in domain !"); }
// TODO: should be able to filter domain values (inference, pertinence)
for value in domain.values.iter() {
updates.push(Assignment::Update(key.clone(), value));
for value in domain_values.into_iter() {
updates.push(Assignment::Update(key.clone(), *value));
}
Some(updates)
} else { // End of assignements
@@ -147,7 +146,7 @@ impl<'a, V> ProblemBuilder<'a, V> {
})
}
pub fn add_variable<S>(mut self, name: S, domain: &'a Domain<V>, value: Option<&'a V>) -> Self
pub fn add_variable<S>(mut self, name: S, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
where S: Into<String>
{
let name = name.into();
@@ -174,8 +173,8 @@ mod tests {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_> = Problem::build()
.add_variable(String::from("Left"), &domain, None)
.add_variable(String::from("Right"), &domain, None)
.add_variable(String::from("Left"), domain.all(), None)
.add_variable(String::from("Right"), domain.all(), None)
.add_constraint(|assign: &Variables<i32>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})
@@ -195,8 +194,8 @@ mod tests {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_> = Problem::build()
.add_variable("Left".to_string(), &domain, None)
.add_variable("Right".to_string(), &domain, Some(&2))
.add_variable("Left".to_string(), domain.all(), None)
.add_variable("Right".to_string(), domain.all(), Some(&2))
.add_constraint( |assign: &Variables<i32>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})

View File

@@ -8,6 +8,7 @@
"lint": "vue-cli-service lint"
},
"dependencies": {
"bulma": "^0.7.2",
"vue": "^2.5.22"
},
"devDependencies": {

View File

@@ -1,30 +1,53 @@
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<p>{{ items }}</p>
<section class="section has-background-primary" id="heading">
<Heading msg="Cook-Assistant"/>
</section>
<section class="section" id="recipes-view">
<p v-if="is_loading">Loading...</p>
<h2 v-else class="subtitle">Livre de recettes</h2>
<div class="container">
<keep-alive>
<RecipeDetails v-if="active_view > -1"
v-bind:item="items[active_view]"
v-on:close="closeActiveView" />
<RecipeList v-else
v-bind:items="items"
v-on:open-details="setActiveView" />
</keep-alive>
</div>
</section>
<section class="section has-background-grey-lighter" id="planner-view">
<h2 class="subtitle">Planning</h2>
</section>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import 'bulma/css/bulma.css'
import Heading from './components/Heading.vue'
import RecipeDetails from './components/RecipeDetails.vue'
import RecipeList from './components/RecipeList.vue'
export default {
name: 'app',
components: {
HelloWorld,
RecipeDetails
Heading,
RecipeDetails,
RecipeList,
},
data () {
return {
items: []
is_loading: true,
items: [],
// Index of the item
// activated for details view
active_view: -1,
}
},
methods: {
setActiveCategory: function(id) {
this.active_category = id;
},
setActiveView: function(idx) {
this.active_view = idx;
},
@@ -47,19 +70,15 @@ export default {
fetchRecipesList: function() {
fetch("http://localhost:8000/api/list")
.then((res) => res.json())
.then((data) => this.items = data)
.then((data) => {
this.items = data;
this.is_loading = false;
})
.catch(function(err) {
console.error(err);
});
}
},
computed: {
displayed: function() {
return this.items.filter(
rec => rec.category == this.active_category
);
}
},
mounted () {
this.fetchRecipesList();
}

View File

@@ -0,0 +1,16 @@
<template>
<h1 class="title">{{ msg }}</h1>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

View File

@@ -1,37 +0,0 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br>
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

View File

@@ -1,5 +1,5 @@
<template>
<div class="box">
<div class="container box">
<button @click="$emit('close')" class="button is-pulled-right">X close</button>
<h4 class="title">{{ item.title }}</h4>
<h6 class="subtitle">{{ categories[item.category].name }}</h6>
@@ -15,8 +15,21 @@
</template>
<script>
export default {
name: 'RecipeDetails',
props: ['item'],
props: {
item: {
type: Object,
required: true,
default () {
return {id: 0, title: "", category: 0, ingredients: ""};
},
}
},
data () {
return {
categories: ["test", "test", "test"],
}
}
}
</script>

View File

@@ -0,0 +1,54 @@
<template>
<div class="container">
<div v-if="active_category == -1" class="columns">
<div v-for="c in categories" :key="c.id" class="column">
<button @click="setActiveCategory(c.id)" class="button is-large is-primary has-text-dark">{{ c.name }}</button>
</div>
</div>
<div v-else class="box">
<button @click="setActiveCategory(-1)" class="button is-pulled-left"><< back</button>
<h2 class="subtitle">{{ categories[active_category].name }}</h2>
<ul>
<li v-for="item in displayed" :key="item.id">
<a href=""
@click.prevent="$emit(
'open-details',
items.findIndex((i) => i.id ==item.id))">
{{ item.title }}</a>
</li>
</ul>
</div>
</div>
</template>
<script>
export const categories = [
{id: 0, name: "Petit-déjeuner"},
{id: 1, name: "Entrée"},
{id: 2, name: "Plat principal"},
{id: 3, name: "Dessert"}
];
export default {
name: 'RecipeList',
props: ["items"],
data () {
return {
active_category: -1,
categories,
}
},
methods: {
setActiveCategory: function(id) {
this.active_category = id;
},
},
computed: {
displayed: function() {
return this.items.filter(
rec => rec.category == this.active_category
);
}
},
}
</script>